SemaOverload.cpp revision 74e386e8ead6654fade7f8661e28e10100dd4005
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 "Sema.h"
15#include "Lookup.h"
16#include "SemaInit.h"
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/Basic/PartialDiagnostic.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/STLExtras.h"
27#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
33ImplicitConversionCategory
34GetConversionCategory(ImplicitConversionKind Kind) {
35  static const ImplicitConversionCategory
36    Category[(int)ICK_Num_Conversion_Kinds] = {
37    ICC_Identity,
38    ICC_Lvalue_Transformation,
39    ICC_Lvalue_Transformation,
40    ICC_Lvalue_Transformation,
41    ICC_Identity,
42    ICC_Qualification_Adjustment,
43    ICC_Promotion,
44    ICC_Promotion,
45    ICC_Promotion,
46    ICC_Conversion,
47    ICC_Conversion,
48    ICC_Conversion,
49    ICC_Conversion,
50    ICC_Conversion,
51    ICC_Conversion,
52    ICC_Conversion,
53    ICC_Conversion,
54    ICC_Conversion,
55    ICC_Conversion
56  };
57  return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63  static const ImplicitConversionRank
64    Rank[(int)ICK_Num_Conversion_Kinds] = {
65    ICR_Exact_Match,
66    ICR_Exact_Match,
67    ICR_Exact_Match,
68    ICR_Exact_Match,
69    ICR_Exact_Match,
70    ICR_Exact_Match,
71    ICR_Promotion,
72    ICR_Promotion,
73    ICR_Promotion,
74    ICR_Conversion,
75    ICR_Conversion,
76    ICR_Conversion,
77    ICR_Conversion,
78    ICR_Conversion,
79    ICR_Conversion,
80    ICR_Conversion,
81    ICR_Conversion,
82    ICR_Conversion,
83    ICR_Complex_Real_Conversion
84  };
85  return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
91  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
92    "No conversion",
93    "Lvalue-to-rvalue",
94    "Array-to-pointer",
95    "Function-to-pointer",
96    "Noreturn adjustment",
97    "Qualification",
98    "Integral promotion",
99    "Floating point promotion",
100    "Complex promotion",
101    "Integral conversion",
102    "Floating conversion",
103    "Complex conversion",
104    "Floating-integral conversion",
105    "Complex-real conversion",
106    "Pointer conversion",
107    "Pointer-to-member conversion",
108    "Boolean conversion",
109    "Compatible-types conversion",
110    "Derived-to-base conversion"
111  };
112  return Name[Kind];
113}
114
115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118  First = ICK_Identity;
119  Second = ICK_Identity;
120  Third = ICK_Identity;
121  DeprecatedStringLiteralToCharPtr = false;
122  ReferenceBinding = false;
123  DirectBinding = false;
124  RRefBinding = false;
125  CopyConstructor = 0;
126}
127
128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132  ImplicitConversionRank Rank = ICR_Exact_Match;
133  if  (GetConversionRank(First) > Rank)
134    Rank = GetConversionRank(First);
135  if  (GetConversionRank(Second) > Rank)
136    Rank = GetConversionRank(Second);
137  if  (GetConversionRank(Third) > Rank)
138    Rank = GetConversionRank(Third);
139  return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
144/// used as part of the ranking of standard conversion sequences
145/// (C++ 13.3.3.2p4).
146bool StandardConversionSequence::isPointerConversionToBool() const {
147  // Note that FromType has not necessarily been transformed by the
148  // array-to-pointer or function-to-pointer implicit conversions, so
149  // check for their presence as well as checking whether FromType is
150  // a pointer.
151  if (getToType(1)->isBooleanType() &&
152      (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
153       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154    return true;
155
156  return false;
157}
158
159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
163bool
164StandardConversionSequence::
165isPointerConversionToVoidPointer(ASTContext& Context) const {
166  QualType FromType = getFromType();
167  QualType ToType = getToType(1);
168
169  // Note that FromType has not necessarily been transformed by the
170  // array-to-pointer implicit conversion, so check for its presence
171  // and redo the conversion to get a pointer.
172  if (First == ICK_Array_To_Pointer)
173    FromType = Context.getArrayDecayedType(FromType);
174
175  if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
176    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
177      return ToPtrType->getPointeeType()->isVoidType();
178
179  return false;
180}
181
182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185  llvm::raw_ostream &OS = llvm::errs();
186  bool PrintedSomething = false;
187  if (First != ICK_Identity) {
188    OS << GetImplicitConversionName(First);
189    PrintedSomething = true;
190  }
191
192  if (Second != ICK_Identity) {
193    if (PrintedSomething) {
194      OS << " -> ";
195    }
196    OS << GetImplicitConversionName(Second);
197
198    if (CopyConstructor) {
199      OS << " (by copy constructor)";
200    } else if (DirectBinding) {
201      OS << " (direct reference binding)";
202    } else if (ReferenceBinding) {
203      OS << " (reference binding)";
204    }
205    PrintedSomething = true;
206  }
207
208  if (Third != ICK_Identity) {
209    if (PrintedSomething) {
210      OS << " -> ";
211    }
212    OS << GetImplicitConversionName(Third);
213    PrintedSomething = true;
214  }
215
216  if (!PrintedSomething) {
217    OS << "No conversions required";
218  }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
224  llvm::raw_ostream &OS = llvm::errs();
225  if (Before.First || Before.Second || Before.Third) {
226    Before.DebugPrint();
227    OS << " -> ";
228  }
229  OS << "'" << ConversionFunction->getNameAsString() << "'";
230  if (After.First || After.Second || After.Third) {
231    OS << " -> ";
232    After.DebugPrint();
233  }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
239  llvm::raw_ostream &OS = llvm::errs();
240  switch (ConversionKind) {
241  case StandardConversion:
242    OS << "Standard conversion: ";
243    Standard.DebugPrint();
244    break;
245  case UserDefinedConversion:
246    OS << "User-defined conversion: ";
247    UserDefined.DebugPrint();
248    break;
249  case EllipsisConversion:
250    OS << "Ellipsis conversion";
251    break;
252  case AmbiguousConversion:
253    OS << "Ambiguous conversion";
254    break;
255  case BadConversion:
256    OS << "Bad conversion";
257    break;
258  }
259
260  OS << "\n";
261}
262
263void AmbiguousConversionSequence::construct() {
264  new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268  conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273  FromTypePtr = O.FromTypePtr;
274  ToTypePtr = O.ToTypePtr;
275  new (&conversions()) ConversionSet(O.conversions());
276}
277
278
279// IsOverload - Determine whether the given New declaration is an
280// overload of the declarations in Old. This routine returns false if
281// New and Old cannot be overloaded, e.g., if New has the same
282// signature as some function in Old (C++ 1.3.10) or if the Old
283// declarations aren't functions (or function templates) at all. When
284// it does return false, MatchedDecl will point to the decl that New
285// cannot be overloaded with.  This decl may be a UsingShadowDecl on
286// top of the underlying declaration.
287//
288// Example: Given the following input:
289//
290//   void f(int, float); // #1
291//   void f(int, int); // #2
292//   int f(int, int); // #3
293//
294// When we process #1, there is no previous declaration of "f",
295// so IsOverload will not be used.
296//
297// When we process #2, Old contains only the FunctionDecl for #1.  By
298// comparing the parameter types, we see that #1 and #2 are overloaded
299// (since they have different signatures), so this routine returns
300// false; MatchedDecl is unchanged.
301//
302// When we process #3, Old is an overload set containing #1 and #2. We
303// compare the signatures of #3 to #1 (they're overloaded, so we do
304// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
305// identical (return types of functions are not part of the
306// signature), IsOverload returns false and MatchedDecl will be set to
307// point to the FunctionDecl for #2.
308Sema::OverloadKind
309Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
310                    NamedDecl *&Match) {
311  for (LookupResult::iterator I = Old.begin(), E = Old.end();
312         I != E; ++I) {
313    NamedDecl *OldD = (*I)->getUnderlyingDecl();
314    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
315      if (!IsOverload(New, OldT->getTemplatedDecl())) {
316        Match = *I;
317        return Ovl_Match;
318      }
319    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
320      if (!IsOverload(New, OldF)) {
321        Match = *I;
322        return Ovl_Match;
323      }
324    } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
325      // We can overload with these, which can show up when doing
326      // redeclaration checks for UsingDecls.
327      assert(Old.getLookupKind() == LookupUsingDeclName);
328    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
329      // Optimistically assume that an unresolved using decl will
330      // overload; if it doesn't, we'll have to diagnose during
331      // template instantiation.
332    } else {
333      // (C++ 13p1):
334      //   Only function declarations can be overloaded; object and type
335      //   declarations cannot be overloaded.
336      Match = *I;
337      return Ovl_NonFunction;
338    }
339  }
340
341  return Ovl_Overload;
342}
343
344bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
345  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
346  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
347
348  // C++ [temp.fct]p2:
349  //   A function template can be overloaded with other function templates
350  //   and with normal (non-template) functions.
351  if ((OldTemplate == 0) != (NewTemplate == 0))
352    return true;
353
354  // Is the function New an overload of the function Old?
355  QualType OldQType = Context.getCanonicalType(Old->getType());
356  QualType NewQType = Context.getCanonicalType(New->getType());
357
358  // Compare the signatures (C++ 1.3.10) of the two functions to
359  // determine whether they are overloads. If we find any mismatch
360  // in the signature, they are overloads.
361
362  // If either of these functions is a K&R-style function (no
363  // prototype), then we consider them to have matching signatures.
364  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
365      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
366    return false;
367
368  FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
369  FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
370
371  // The signature of a function includes the types of its
372  // parameters (C++ 1.3.10), which includes the presence or absence
373  // of the ellipsis; see C++ DR 357).
374  if (OldQType != NewQType &&
375      (OldType->getNumArgs() != NewType->getNumArgs() ||
376       OldType->isVariadic() != NewType->isVariadic() ||
377       !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
378                   NewType->arg_type_begin())))
379    return true;
380
381  // C++ [temp.over.link]p4:
382  //   The signature of a function template consists of its function
383  //   signature, its return type and its template parameter list. The names
384  //   of the template parameters are significant only for establishing the
385  //   relationship between the template parameters and the rest of the
386  //   signature.
387  //
388  // We check the return type and template parameter lists for function
389  // templates first; the remaining checks follow.
390  if (NewTemplate &&
391      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
392                                       OldTemplate->getTemplateParameters(),
393                                       false, TPL_TemplateMatch) ||
394       OldType->getResultType() != NewType->getResultType()))
395    return true;
396
397  // If the function is a class member, its signature includes the
398  // cv-qualifiers (if any) on the function itself.
399  //
400  // As part of this, also check whether one of the member functions
401  // is static, in which case they are not overloads (C++
402  // 13.1p2). While not part of the definition of the signature,
403  // this check is important to determine whether these functions
404  // can be overloaded.
405  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
406  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
407  if (OldMethod && NewMethod &&
408      !OldMethod->isStatic() && !NewMethod->isStatic() &&
409      OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
410    return true;
411
412  // The signatures match; this is not an overload.
413  return false;
414}
415
416/// TryImplicitConversion - Attempt to perform an implicit conversion
417/// from the given expression (Expr) to the given type (ToType). This
418/// function returns an implicit conversion sequence that can be used
419/// to perform the initialization. Given
420///
421///   void f(float f);
422///   void g(int i) { f(i); }
423///
424/// this routine would produce an implicit conversion sequence to
425/// describe the initialization of f from i, which will be a standard
426/// conversion sequence containing an lvalue-to-rvalue conversion (C++
427/// 4.1) followed by a floating-integral conversion (C++ 4.9).
428//
429/// Note that this routine only determines how the conversion can be
430/// performed; it does not actually perform the conversion. As such,
431/// it will not produce any diagnostics if no conversion is available,
432/// but will instead return an implicit conversion sequence of kind
433/// "BadConversion".
434///
435/// If @p SuppressUserConversions, then user-defined conversions are
436/// not permitted.
437/// If @p AllowExplicit, then explicit user-defined conversions are
438/// permitted.
439/// If @p UserCast, the implicit conversion is being done for a user-specified
440/// cast.
441ImplicitConversionSequence
442Sema::TryImplicitConversion(Expr* From, QualType ToType,
443                            bool SuppressUserConversions,
444                            bool AllowExplicit,
445                            bool InOverloadResolution,
446                            bool UserCast) {
447  ImplicitConversionSequence ICS;
448  if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
449    ICS.setStandard();
450    return ICS;
451  }
452
453  if (!getLangOptions().CPlusPlus) {
454    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
455    return ICS;
456  }
457
458  OverloadCandidateSet Conversions(From->getExprLoc());
459  OverloadingResult UserDefResult
460    = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
461                              !SuppressUserConversions, AllowExplicit,
462                              UserCast);
463
464  if (UserDefResult == OR_Success) {
465    ICS.setUserDefined();
466    // C++ [over.ics.user]p4:
467    //   A conversion of an expression of class type to the same class
468    //   type is given Exact Match rank, and a conversion of an
469    //   expression of class type to a base class of that type is
470    //   given Conversion rank, in spite of the fact that a copy
471    //   constructor (i.e., a user-defined conversion function) is
472    //   called for those cases.
473    if (CXXConstructorDecl *Constructor
474          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
475      QualType FromCanon
476        = Context.getCanonicalType(From->getType().getUnqualifiedType());
477      QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
478      if (Constructor->isCopyConstructor() &&
479          (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
480        // Turn this into a "standard" conversion sequence, so that it
481        // gets ranked with standard conversion sequences.
482        ICS.setStandard();
483        ICS.Standard.setAsIdentityConversion();
484        ICS.Standard.setFromType(From->getType());
485        ICS.Standard.setAllToTypes(ToType);
486        ICS.Standard.CopyConstructor = Constructor;
487        if (ToCanon != FromCanon)
488          ICS.Standard.Second = ICK_Derived_To_Base;
489      }
490    }
491
492    // C++ [over.best.ics]p4:
493    //   However, when considering the argument of a user-defined
494    //   conversion function that is a candidate by 13.3.1.3 when
495    //   invoked for the copying of the temporary in the second step
496    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
497    //   13.3.1.6 in all cases, only standard conversion sequences and
498    //   ellipsis conversion sequences are allowed.
499    if (SuppressUserConversions && ICS.isUserDefined()) {
500      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
501    }
502  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
503    ICS.setAmbiguous();
504    ICS.Ambiguous.setFromType(From->getType());
505    ICS.Ambiguous.setToType(ToType);
506    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
507         Cand != Conversions.end(); ++Cand)
508      if (Cand->Viable)
509        ICS.Ambiguous.addConversion(Cand->Function);
510  } else {
511    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
512  }
513
514  return ICS;
515}
516
517/// \brief Determine whether the conversion from FromType to ToType is a valid
518/// conversion that strips "noreturn" off the nested function type.
519static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
520                                 QualType ToType, QualType &ResultTy) {
521  if (Context.hasSameUnqualifiedType(FromType, ToType))
522    return false;
523
524  // Strip the noreturn off the type we're converting from; noreturn can
525  // safely be removed.
526  FromType = Context.getNoReturnType(FromType, false);
527  if (!Context.hasSameUnqualifiedType(FromType, ToType))
528    return false;
529
530  ResultTy = FromType;
531  return true;
532}
533
534/// IsStandardConversion - Determines whether there is a standard
535/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
536/// expression From to the type ToType. Standard conversion sequences
537/// only consider non-class types; for conversions that involve class
538/// types, use TryImplicitConversion. If a conversion exists, SCS will
539/// contain the standard conversion sequence required to perform this
540/// conversion and this routine will return true. Otherwise, this
541/// routine will return false and the value of SCS is unspecified.
542bool
543Sema::IsStandardConversion(Expr* From, QualType ToType,
544                           bool InOverloadResolution,
545                           StandardConversionSequence &SCS) {
546  QualType FromType = From->getType();
547
548  // Standard conversions (C++ [conv])
549  SCS.setAsIdentityConversion();
550  SCS.DeprecatedStringLiteralToCharPtr = false;
551  SCS.IncompatibleObjC = false;
552  SCS.setFromType(FromType);
553  SCS.CopyConstructor = 0;
554
555  // There are no standard conversions for class types in C++, so
556  // abort early. When overloading in C, however, we do permit
557  if (FromType->isRecordType() || ToType->isRecordType()) {
558    if (getLangOptions().CPlusPlus)
559      return false;
560
561    // When we're overloading in C, we allow, as standard conversions,
562  }
563
564  // The first conversion can be an lvalue-to-rvalue conversion,
565  // array-to-pointer conversion, or function-to-pointer conversion
566  // (C++ 4p1).
567
568  DeclAccessPair AccessPair;
569
570  // Lvalue-to-rvalue conversion (C++ 4.1):
571  //   An lvalue (3.10) of a non-function, non-array type T can be
572  //   converted to an rvalue.
573  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
574  if (argIsLvalue == Expr::LV_Valid &&
575      !FromType->isFunctionType() && !FromType->isArrayType() &&
576      Context.getCanonicalType(FromType) != Context.OverloadTy) {
577    SCS.First = ICK_Lvalue_To_Rvalue;
578
579    // If T is a non-class type, the type of the rvalue is the
580    // cv-unqualified version of T. Otherwise, the type of the rvalue
581    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
582    // just strip the qualifiers because they don't matter.
583    FromType = FromType.getUnqualifiedType();
584  } else if (FromType->isArrayType()) {
585    // Array-to-pointer conversion (C++ 4.2)
586    SCS.First = ICK_Array_To_Pointer;
587
588    // An lvalue or rvalue of type "array of N T" or "array of unknown
589    // bound of T" can be converted to an rvalue of type "pointer to
590    // T" (C++ 4.2p1).
591    FromType = Context.getArrayDecayedType(FromType);
592
593    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
594      // This conversion is deprecated. (C++ D.4).
595      SCS.DeprecatedStringLiteralToCharPtr = true;
596
597      // For the purpose of ranking in overload resolution
598      // (13.3.3.1.1), this conversion is considered an
599      // array-to-pointer conversion followed by a qualification
600      // conversion (4.4). (C++ 4.2p2)
601      SCS.Second = ICK_Identity;
602      SCS.Third = ICK_Qualification;
603      SCS.setAllToTypes(FromType);
604      return true;
605    }
606  } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
607    // Function-to-pointer conversion (C++ 4.3).
608    SCS.First = ICK_Function_To_Pointer;
609
610    // An lvalue of function type T can be converted to an rvalue of
611    // type "pointer to T." The result is a pointer to the
612    // function. (C++ 4.3p1).
613    FromType = Context.getPointerType(FromType);
614  } else if (From->getType() == Context.OverloadTy) {
615    if (FunctionDecl *Fn
616          = ResolveAddressOfOverloadedFunction(From, ToType, false,
617                                               AccessPair)) {
618      // Address of overloaded function (C++ [over.over]).
619      SCS.First = ICK_Function_To_Pointer;
620
621      // We were able to resolve the address of the overloaded function,
622      // so we can convert to the type of that function.
623      FromType = Fn->getType();
624      if (ToType->isLValueReferenceType())
625        FromType = Context.getLValueReferenceType(FromType);
626      else if (ToType->isRValueReferenceType())
627        FromType = Context.getRValueReferenceType(FromType);
628      else if (ToType->isMemberPointerType()) {
629        // Resolve address only succeeds if both sides are member pointers,
630        // but it doesn't have to be the same class. See DR 247.
631        // Note that this means that the type of &Derived::fn can be
632        // Ret (Base::*)(Args) if the fn overload actually found is from the
633        // base class, even if it was brought into the derived class via a
634        // using declaration. The standard isn't clear on this issue at all.
635        CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
636        FromType = Context.getMemberPointerType(FromType,
637                      Context.getTypeDeclType(M->getParent()).getTypePtr());
638      } else {
639        FromType = Context.getPointerType(FromType);
640      }
641    } else {
642      return false;
643    }
644  } else {
645    // We don't require any conversions for the first step.
646    SCS.First = ICK_Identity;
647  }
648  SCS.setToType(0, FromType);
649
650  // The second conversion can be an integral promotion, floating
651  // point promotion, integral conversion, floating point conversion,
652  // floating-integral conversion, pointer conversion,
653  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
654  // For overloading in C, this can also be a "compatible-type"
655  // conversion.
656  bool IncompatibleObjC = false;
657  if (Context.hasSameUnqualifiedType(FromType, ToType)) {
658    // The unqualified versions of the types are the same: there's no
659    // conversion to do.
660    SCS.Second = ICK_Identity;
661  } else if (IsIntegralPromotion(From, FromType, ToType)) {
662    // Integral promotion (C++ 4.5).
663    SCS.Second = ICK_Integral_Promotion;
664    FromType = ToType.getUnqualifiedType();
665  } else if (IsFloatingPointPromotion(FromType, ToType)) {
666    // Floating point promotion (C++ 4.6).
667    SCS.Second = ICK_Floating_Promotion;
668    FromType = ToType.getUnqualifiedType();
669  } else if (IsComplexPromotion(FromType, ToType)) {
670    // Complex promotion (Clang extension)
671    SCS.Second = ICK_Complex_Promotion;
672    FromType = ToType.getUnqualifiedType();
673  } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
674           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
675    // Integral conversions (C++ 4.7).
676    SCS.Second = ICK_Integral_Conversion;
677    FromType = ToType.getUnqualifiedType();
678  } else if (FromType->isComplexType() && ToType->isComplexType()) {
679    // Complex conversions (C99 6.3.1.6)
680    SCS.Second = ICK_Complex_Conversion;
681    FromType = ToType.getUnqualifiedType();
682  } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
683             (ToType->isComplexType() && FromType->isArithmeticType())) {
684    // Complex-real conversions (C99 6.3.1.7)
685    SCS.Second = ICK_Complex_Real;
686    FromType = ToType.getUnqualifiedType();
687  } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
688    // Floating point conversions (C++ 4.8).
689    SCS.Second = ICK_Floating_Conversion;
690    FromType = ToType.getUnqualifiedType();
691  } else if ((FromType->isFloatingType() &&
692              ToType->isIntegralType() && (!ToType->isBooleanType() &&
693                                           !ToType->isEnumeralType())) ||
694             ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
695              ToType->isFloatingType())) {
696    // Floating-integral conversions (C++ 4.9).
697    SCS.Second = ICK_Floating_Integral;
698    FromType = ToType.getUnqualifiedType();
699  } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
700                                 FromType, IncompatibleObjC)) {
701    // Pointer conversions (C++ 4.10).
702    SCS.Second = ICK_Pointer_Conversion;
703    SCS.IncompatibleObjC = IncompatibleObjC;
704  } else if (IsMemberPointerConversion(From, FromType, ToType,
705                                       InOverloadResolution, FromType)) {
706    // Pointer to member conversions (4.11).
707    SCS.Second = ICK_Pointer_Member;
708  } else if (ToType->isBooleanType() &&
709             (FromType->isArithmeticType() ||
710              FromType->isEnumeralType() ||
711              FromType->isAnyPointerType() ||
712              FromType->isBlockPointerType() ||
713              FromType->isMemberPointerType() ||
714              FromType->isNullPtrType())) {
715    // Boolean conversions (C++ 4.12).
716    SCS.Second = ICK_Boolean_Conversion;
717    FromType = Context.BoolTy;
718  } else if (!getLangOptions().CPlusPlus &&
719             Context.typesAreCompatible(ToType, FromType)) {
720    // Compatible conversions (Clang extension for C function overloading)
721    SCS.Second = ICK_Compatible_Conversion;
722  } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
723    // Treat a conversion that strips "noreturn" as an identity conversion.
724    SCS.Second = ICK_NoReturn_Adjustment;
725  } else {
726    // No second conversion required.
727    SCS.Second = ICK_Identity;
728  }
729  SCS.setToType(1, FromType);
730
731  QualType CanonFrom;
732  QualType CanonTo;
733  // The third conversion can be a qualification conversion (C++ 4p1).
734  if (IsQualificationConversion(FromType, ToType)) {
735    SCS.Third = ICK_Qualification;
736    FromType = ToType;
737    CanonFrom = Context.getCanonicalType(FromType);
738    CanonTo = Context.getCanonicalType(ToType);
739  } else {
740    // No conversion required
741    SCS.Third = ICK_Identity;
742
743    // C++ [over.best.ics]p6:
744    //   [...] Any difference in top-level cv-qualification is
745    //   subsumed by the initialization itself and does not constitute
746    //   a conversion. [...]
747    CanonFrom = Context.getCanonicalType(FromType);
748    CanonTo = Context.getCanonicalType(ToType);
749    if (CanonFrom.getLocalUnqualifiedType()
750                                       == CanonTo.getLocalUnqualifiedType() &&
751        CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
752      FromType = ToType;
753      CanonFrom = CanonTo;
754    }
755  }
756  SCS.setToType(2, FromType);
757
758  // If we have not converted the argument type to the parameter type,
759  // this is a bad conversion sequence.
760  if (CanonFrom != CanonTo)
761    return false;
762
763  return true;
764}
765
766/// IsIntegralPromotion - Determines whether the conversion from the
767/// expression From (whose potentially-adjusted type is FromType) to
768/// ToType is an integral promotion (C++ 4.5). If so, returns true and
769/// sets PromotedType to the promoted type.
770bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
771  const BuiltinType *To = ToType->getAs<BuiltinType>();
772  // All integers are built-in.
773  if (!To) {
774    return false;
775  }
776
777  // An rvalue of type char, signed char, unsigned char, short int, or
778  // unsigned short int can be converted to an rvalue of type int if
779  // int can represent all the values of the source type; otherwise,
780  // the source rvalue can be converted to an rvalue of type unsigned
781  // int (C++ 4.5p1).
782  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
783      !FromType->isEnumeralType()) {
784    if (// We can promote any signed, promotable integer type to an int
785        (FromType->isSignedIntegerType() ||
786         // We can promote any unsigned integer type whose size is
787         // less than int to an int.
788         (!FromType->isSignedIntegerType() &&
789          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
790      return To->getKind() == BuiltinType::Int;
791    }
792
793    return To->getKind() == BuiltinType::UInt;
794  }
795
796  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
797  // can be converted to an rvalue of the first of the following types
798  // that can represent all the values of its underlying type: int,
799  // unsigned int, long, or unsigned long (C++ 4.5p2).
800
801  // We pre-calculate the promotion type for enum types.
802  if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
803    if (ToType->isIntegerType())
804      return Context.hasSameUnqualifiedType(ToType,
805                                FromEnumType->getDecl()->getPromotionType());
806
807  if (FromType->isWideCharType() && ToType->isIntegerType()) {
808    // Determine whether the type we're converting from is signed or
809    // unsigned.
810    bool FromIsSigned;
811    uint64_t FromSize = Context.getTypeSize(FromType);
812
813    // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
814    FromIsSigned = true;
815
816    // The types we'll try to promote to, in the appropriate
817    // order. Try each of these types.
818    QualType PromoteTypes[6] = {
819      Context.IntTy, Context.UnsignedIntTy,
820      Context.LongTy, Context.UnsignedLongTy ,
821      Context.LongLongTy, Context.UnsignedLongLongTy
822    };
823    for (int Idx = 0; Idx < 6; ++Idx) {
824      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
825      if (FromSize < ToSize ||
826          (FromSize == ToSize &&
827           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
828        // We found the type that we can promote to. If this is the
829        // type we wanted, we have a promotion. Otherwise, no
830        // promotion.
831        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
832      }
833    }
834  }
835
836  // An rvalue for an integral bit-field (9.6) can be converted to an
837  // rvalue of type int if int can represent all the values of the
838  // bit-field; otherwise, it can be converted to unsigned int if
839  // unsigned int can represent all the values of the bit-field. If
840  // the bit-field is larger yet, no integral promotion applies to
841  // it. If the bit-field has an enumerated type, it is treated as any
842  // other value of that type for promotion purposes (C++ 4.5p3).
843  // FIXME: We should delay checking of bit-fields until we actually perform the
844  // conversion.
845  using llvm::APSInt;
846  if (From)
847    if (FieldDecl *MemberDecl = From->getBitField()) {
848      APSInt BitWidth;
849      if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
850          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
851        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
852        ToSize = Context.getTypeSize(ToType);
853
854        // Are we promoting to an int from a bitfield that fits in an int?
855        if (BitWidth < ToSize ||
856            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
857          return To->getKind() == BuiltinType::Int;
858        }
859
860        // Are we promoting to an unsigned int from an unsigned bitfield
861        // that fits into an unsigned int?
862        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
863          return To->getKind() == BuiltinType::UInt;
864        }
865
866        return false;
867      }
868    }
869
870  // An rvalue of type bool can be converted to an rvalue of type int,
871  // with false becoming zero and true becoming one (C++ 4.5p4).
872  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
873    return true;
874  }
875
876  return false;
877}
878
879/// IsFloatingPointPromotion - Determines whether the conversion from
880/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
881/// returns true and sets PromotedType to the promoted type.
882bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
883  /// An rvalue of type float can be converted to an rvalue of type
884  /// double. (C++ 4.6p1).
885  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
886    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
887      if (FromBuiltin->getKind() == BuiltinType::Float &&
888          ToBuiltin->getKind() == BuiltinType::Double)
889        return true;
890
891      // C99 6.3.1.5p1:
892      //   When a float is promoted to double or long double, or a
893      //   double is promoted to long double [...].
894      if (!getLangOptions().CPlusPlus &&
895          (FromBuiltin->getKind() == BuiltinType::Float ||
896           FromBuiltin->getKind() == BuiltinType::Double) &&
897          (ToBuiltin->getKind() == BuiltinType::LongDouble))
898        return true;
899    }
900
901  return false;
902}
903
904/// \brief Determine if a conversion is a complex promotion.
905///
906/// A complex promotion is defined as a complex -> complex conversion
907/// where the conversion between the underlying real types is a
908/// floating-point or integral promotion.
909bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
910  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
911  if (!FromComplex)
912    return false;
913
914  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
915  if (!ToComplex)
916    return false;
917
918  return IsFloatingPointPromotion(FromComplex->getElementType(),
919                                  ToComplex->getElementType()) ||
920    IsIntegralPromotion(0, FromComplex->getElementType(),
921                        ToComplex->getElementType());
922}
923
924/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
925/// the pointer type FromPtr to a pointer to type ToPointee, with the
926/// same type qualifiers as FromPtr has on its pointee type. ToType,
927/// if non-empty, will be a pointer to ToType that may or may not have
928/// the right set of qualifiers on its pointee.
929static QualType
930BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
931                                   QualType ToPointee, QualType ToType,
932                                   ASTContext &Context) {
933  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
934  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
935  Qualifiers Quals = CanonFromPointee.getQualifiers();
936
937  // Exact qualifier match -> return the pointer type we're converting to.
938  if (CanonToPointee.getLocalQualifiers() == Quals) {
939    // ToType is exactly what we need. Return it.
940    if (!ToType.isNull())
941      return ToType;
942
943    // Build a pointer to ToPointee. It has the right qualifiers
944    // already.
945    return Context.getPointerType(ToPointee);
946  }
947
948  // Just build a canonical type that has the right qualifiers.
949  return Context.getPointerType(
950         Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
951                                  Quals));
952}
953
954/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
955/// the FromType, which is an objective-c pointer, to ToType, which may or may
956/// not have the right set of qualifiers.
957static QualType
958BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
959                                             QualType ToType,
960                                             ASTContext &Context) {
961  QualType CanonFromType = Context.getCanonicalType(FromType);
962  QualType CanonToType = Context.getCanonicalType(ToType);
963  Qualifiers Quals = CanonFromType.getQualifiers();
964
965  // Exact qualifier match -> return the pointer type we're converting to.
966  if (CanonToType.getLocalQualifiers() == Quals)
967    return ToType;
968
969  // Just build a canonical type that has the right qualifiers.
970  return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
971}
972
973static bool isNullPointerConstantForConversion(Expr *Expr,
974                                               bool InOverloadResolution,
975                                               ASTContext &Context) {
976  // Handle value-dependent integral null pointer constants correctly.
977  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
978  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
979      Expr->getType()->isIntegralType())
980    return !InOverloadResolution;
981
982  return Expr->isNullPointerConstant(Context,
983                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
984                                        : Expr::NPC_ValueDependentIsNull);
985}
986
987/// IsPointerConversion - Determines whether the conversion of the
988/// expression From, which has the (possibly adjusted) type FromType,
989/// can be converted to the type ToType via a pointer conversion (C++
990/// 4.10). If so, returns true and places the converted type (that
991/// might differ from ToType in its cv-qualifiers at some level) into
992/// ConvertedType.
993///
994/// This routine also supports conversions to and from block pointers
995/// and conversions with Objective-C's 'id', 'id<protocols...>', and
996/// pointers to interfaces. FIXME: Once we've determined the
997/// appropriate overloading rules for Objective-C, we may want to
998/// split the Objective-C checks into a different routine; however,
999/// GCC seems to consider all of these conversions to be pointer
1000/// conversions, so for now they live here. IncompatibleObjC will be
1001/// set if the conversion is an allowed Objective-C conversion that
1002/// should result in a warning.
1003bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1004                               bool InOverloadResolution,
1005                               QualType& ConvertedType,
1006                               bool &IncompatibleObjC) {
1007  IncompatibleObjC = false;
1008  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1009    return true;
1010
1011  // Conversion from a null pointer constant to any Objective-C pointer type.
1012  if (ToType->isObjCObjectPointerType() &&
1013      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1014    ConvertedType = ToType;
1015    return true;
1016  }
1017
1018  // Blocks: Block pointers can be converted to void*.
1019  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1020      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1021    ConvertedType = ToType;
1022    return true;
1023  }
1024  // Blocks: A null pointer constant can be converted to a block
1025  // pointer type.
1026  if (ToType->isBlockPointerType() &&
1027      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1028    ConvertedType = ToType;
1029    return true;
1030  }
1031
1032  // If the left-hand-side is nullptr_t, the right side can be a null
1033  // pointer constant.
1034  if (ToType->isNullPtrType() &&
1035      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1036    ConvertedType = ToType;
1037    return true;
1038  }
1039
1040  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1041  if (!ToTypePtr)
1042    return false;
1043
1044  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1045  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1046    ConvertedType = ToType;
1047    return true;
1048  }
1049
1050  // Beyond this point, both types need to be pointers
1051  // , including objective-c pointers.
1052  QualType ToPointeeType = ToTypePtr->getPointeeType();
1053  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1054    ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1055                                                       ToType, Context);
1056    return true;
1057
1058  }
1059  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1060  if (!FromTypePtr)
1061    return false;
1062
1063  QualType FromPointeeType = FromTypePtr->getPointeeType();
1064
1065  // An rvalue of type "pointer to cv T," where T is an object type,
1066  // can be converted to an rvalue of type "pointer to cv void" (C++
1067  // 4.10p2).
1068  if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
1069    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1070                                                       ToPointeeType,
1071                                                       ToType, Context);
1072    return true;
1073  }
1074
1075  // When we're overloading in C, we allow a special kind of pointer
1076  // conversion for compatible-but-not-identical pointee types.
1077  if (!getLangOptions().CPlusPlus &&
1078      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1079    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1080                                                       ToPointeeType,
1081                                                       ToType, Context);
1082    return true;
1083  }
1084
1085  // C++ [conv.ptr]p3:
1086  //
1087  //   An rvalue of type "pointer to cv D," where D is a class type,
1088  //   can be converted to an rvalue of type "pointer to cv B," where
1089  //   B is a base class (clause 10) of D. If B is an inaccessible
1090  //   (clause 11) or ambiguous (10.2) base class of D, a program that
1091  //   necessitates this conversion is ill-formed. The result of the
1092  //   conversion is a pointer to the base class sub-object of the
1093  //   derived class object. The null pointer value is converted to
1094  //   the null pointer value of the destination type.
1095  //
1096  // Note that we do not check for ambiguity or inaccessibility
1097  // here. That is handled by CheckPointerConversion.
1098  if (getLangOptions().CPlusPlus &&
1099      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1100      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1101      !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1102      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1103    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1104                                                       ToPointeeType,
1105                                                       ToType, Context);
1106    return true;
1107  }
1108
1109  return false;
1110}
1111
1112/// isObjCPointerConversion - Determines whether this is an
1113/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1114/// with the same arguments and return values.
1115bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1116                                   QualType& ConvertedType,
1117                                   bool &IncompatibleObjC) {
1118  if (!getLangOptions().ObjC1)
1119    return false;
1120
1121  // First, we handle all conversions on ObjC object pointer types.
1122  const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
1123  const ObjCObjectPointerType *FromObjCPtr =
1124    FromType->getAs<ObjCObjectPointerType>();
1125
1126  if (ToObjCPtr && FromObjCPtr) {
1127    // Objective C++: We're able to convert between "id" or "Class" and a
1128    // pointer to any interface (in both directions).
1129    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1130      ConvertedType = ToType;
1131      return true;
1132    }
1133    // Conversions with Objective-C's id<...>.
1134    if ((FromObjCPtr->isObjCQualifiedIdType() ||
1135         ToObjCPtr->isObjCQualifiedIdType()) &&
1136        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1137                                                  /*compare=*/false)) {
1138      ConvertedType = ToType;
1139      return true;
1140    }
1141    // Objective C++: We're able to convert from a pointer to an
1142    // interface to a pointer to a different interface.
1143    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1144      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1145      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1146      if (getLangOptions().CPlusPlus && LHS && RHS &&
1147          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1148                                                FromObjCPtr->getPointeeType()))
1149        return false;
1150      ConvertedType = ToType;
1151      return true;
1152    }
1153
1154    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1155      // Okay: this is some kind of implicit downcast of Objective-C
1156      // interfaces, which is permitted. However, we're going to
1157      // complain about it.
1158      IncompatibleObjC = true;
1159      ConvertedType = FromType;
1160      return true;
1161    }
1162  }
1163  // Beyond this point, both types need to be C pointers or block pointers.
1164  QualType ToPointeeType;
1165  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1166    ToPointeeType = ToCPtr->getPointeeType();
1167  else if (const BlockPointerType *ToBlockPtr =
1168            ToType->getAs<BlockPointerType>()) {
1169    // Objective C++: We're able to convert from a pointer to any object
1170    // to a block pointer type.
1171    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1172      ConvertedType = ToType;
1173      return true;
1174    }
1175    ToPointeeType = ToBlockPtr->getPointeeType();
1176  }
1177  else if (FromType->getAs<BlockPointerType>() &&
1178           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1179    // Objective C++: We're able to convert from a block pointer type to a
1180    // pointer to any object.
1181    ConvertedType = ToType;
1182    return true;
1183  }
1184  else
1185    return false;
1186
1187  QualType FromPointeeType;
1188  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1189    FromPointeeType = FromCPtr->getPointeeType();
1190  else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
1191    FromPointeeType = FromBlockPtr->getPointeeType();
1192  else
1193    return false;
1194
1195  // If we have pointers to pointers, recursively check whether this
1196  // is an Objective-C conversion.
1197  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1198      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1199                              IncompatibleObjC)) {
1200    // We always complain about this conversion.
1201    IncompatibleObjC = true;
1202    ConvertedType = ToType;
1203    return true;
1204  }
1205  // Allow conversion of pointee being objective-c pointer to another one;
1206  // as in I* to id.
1207  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1208      ToPointeeType->getAs<ObjCObjectPointerType>() &&
1209      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1210                              IncompatibleObjC)) {
1211    ConvertedType = ToType;
1212    return true;
1213  }
1214
1215  // If we have pointers to functions or blocks, check whether the only
1216  // differences in the argument and result types are in Objective-C
1217  // pointer conversions. If so, we permit the conversion (but
1218  // complain about it).
1219  const FunctionProtoType *FromFunctionType
1220    = FromPointeeType->getAs<FunctionProtoType>();
1221  const FunctionProtoType *ToFunctionType
1222    = ToPointeeType->getAs<FunctionProtoType>();
1223  if (FromFunctionType && ToFunctionType) {
1224    // If the function types are exactly the same, this isn't an
1225    // Objective-C pointer conversion.
1226    if (Context.getCanonicalType(FromPointeeType)
1227          == Context.getCanonicalType(ToPointeeType))
1228      return false;
1229
1230    // Perform the quick checks that will tell us whether these
1231    // function types are obviously different.
1232    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1233        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1234        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1235      return false;
1236
1237    bool HasObjCConversion = false;
1238    if (Context.getCanonicalType(FromFunctionType->getResultType())
1239          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1240      // Okay, the types match exactly. Nothing to do.
1241    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1242                                       ToFunctionType->getResultType(),
1243                                       ConvertedType, IncompatibleObjC)) {
1244      // Okay, we have an Objective-C pointer conversion.
1245      HasObjCConversion = true;
1246    } else {
1247      // Function types are too different. Abort.
1248      return false;
1249    }
1250
1251    // Check argument types.
1252    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1253         ArgIdx != NumArgs; ++ArgIdx) {
1254      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1255      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1256      if (Context.getCanonicalType(FromArgType)
1257            == Context.getCanonicalType(ToArgType)) {
1258        // Okay, the types match exactly. Nothing to do.
1259      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1260                                         ConvertedType, IncompatibleObjC)) {
1261        // Okay, we have an Objective-C pointer conversion.
1262        HasObjCConversion = true;
1263      } else {
1264        // Argument types are too different. Abort.
1265        return false;
1266      }
1267    }
1268
1269    if (HasObjCConversion) {
1270      // We had an Objective-C conversion. Allow this pointer
1271      // conversion, but complain about it.
1272      ConvertedType = ToType;
1273      IncompatibleObjC = true;
1274      return true;
1275    }
1276  }
1277
1278  return false;
1279}
1280
1281/// CheckPointerConversion - Check the pointer conversion from the
1282/// expression From to the type ToType. This routine checks for
1283/// ambiguous or inaccessible derived-to-base pointer
1284/// conversions for which IsPointerConversion has already returned
1285/// true. It returns true and produces a diagnostic if there was an
1286/// error, or returns false otherwise.
1287bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1288                                  CastExpr::CastKind &Kind,
1289                                  bool IgnoreBaseAccess) {
1290  QualType FromType = From->getType();
1291
1292  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1293    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1294      QualType FromPointeeType = FromPtrType->getPointeeType(),
1295               ToPointeeType   = ToPtrType->getPointeeType();
1296
1297      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1298          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
1299        // We must have a derived-to-base conversion. Check an
1300        // ambiguous or inaccessible conversion.
1301        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1302                                         From->getExprLoc(),
1303                                         From->getSourceRange(),
1304                                         IgnoreBaseAccess))
1305          return true;
1306
1307        // The conversion was successful.
1308        Kind = CastExpr::CK_DerivedToBase;
1309      }
1310    }
1311  if (const ObjCObjectPointerType *FromPtrType =
1312        FromType->getAs<ObjCObjectPointerType>())
1313    if (const ObjCObjectPointerType *ToPtrType =
1314          ToType->getAs<ObjCObjectPointerType>()) {
1315      // Objective-C++ conversions are always okay.
1316      // FIXME: We should have a different class of conversions for the
1317      // Objective-C++ implicit conversions.
1318      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1319        return false;
1320
1321  }
1322  return false;
1323}
1324
1325/// IsMemberPointerConversion - Determines whether the conversion of the
1326/// expression From, which has the (possibly adjusted) type FromType, can be
1327/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1328/// If so, returns true and places the converted type (that might differ from
1329/// ToType in its cv-qualifiers at some level) into ConvertedType.
1330bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1331                                     QualType ToType,
1332                                     bool InOverloadResolution,
1333                                     QualType &ConvertedType) {
1334  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1335  if (!ToTypePtr)
1336    return false;
1337
1338  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1339  if (From->isNullPointerConstant(Context,
1340                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1341                                        : Expr::NPC_ValueDependentIsNull)) {
1342    ConvertedType = ToType;
1343    return true;
1344  }
1345
1346  // Otherwise, both types have to be member pointers.
1347  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1348  if (!FromTypePtr)
1349    return false;
1350
1351  // A pointer to member of B can be converted to a pointer to member of D,
1352  // where D is derived from B (C++ 4.11p2).
1353  QualType FromClass(FromTypePtr->getClass(), 0);
1354  QualType ToClass(ToTypePtr->getClass(), 0);
1355  // FIXME: What happens when these are dependent? Is this function even called?
1356
1357  if (IsDerivedFrom(ToClass, FromClass)) {
1358    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1359                                                 ToClass.getTypePtr());
1360    return true;
1361  }
1362
1363  return false;
1364}
1365
1366/// CheckMemberPointerConversion - Check the member pointer conversion from the
1367/// expression From to the type ToType. This routine checks for ambiguous or
1368/// virtual or inaccessible base-to-derived member pointer conversions
1369/// for which IsMemberPointerConversion has already returned true. It returns
1370/// true and produces a diagnostic if there was an error, or returns false
1371/// otherwise.
1372bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1373                                        CastExpr::CastKind &Kind,
1374                                        bool IgnoreBaseAccess) {
1375  QualType FromType = From->getType();
1376  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1377  if (!FromPtrType) {
1378    // This must be a null pointer to member pointer conversion
1379    assert(From->isNullPointerConstant(Context,
1380                                       Expr::NPC_ValueDependentIsNull) &&
1381           "Expr must be null pointer constant!");
1382    Kind = CastExpr::CK_NullToMemberPointer;
1383    return false;
1384  }
1385
1386  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1387  assert(ToPtrType && "No member pointer cast has a target type "
1388                      "that is not a member pointer.");
1389
1390  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1391  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1392
1393  // FIXME: What about dependent types?
1394  assert(FromClass->isRecordType() && "Pointer into non-class.");
1395  assert(ToClass->isRecordType() && "Pointer into non-class.");
1396
1397  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/ true,
1398                     /*DetectVirtual=*/true);
1399  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1400  assert(DerivationOkay &&
1401         "Should not have been called if derivation isn't OK.");
1402  (void)DerivationOkay;
1403
1404  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1405                                  getUnqualifiedType())) {
1406    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1407    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1408      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1409    return true;
1410  }
1411
1412  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1413    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1414      << FromClass << ToClass << QualType(VBase, 0)
1415      << From->getSourceRange();
1416    return true;
1417  }
1418
1419  if (!IgnoreBaseAccess)
1420    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1421                         Paths.front(),
1422                         diag::err_downcast_from_inaccessible_base);
1423
1424  // Must be a base to derived member conversion.
1425  Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1426  return false;
1427}
1428
1429/// IsQualificationConversion - Determines whether the conversion from
1430/// an rvalue of type FromType to ToType is a qualification conversion
1431/// (C++ 4.4).
1432bool
1433Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
1434  FromType = Context.getCanonicalType(FromType);
1435  ToType = Context.getCanonicalType(ToType);
1436
1437  // If FromType and ToType are the same type, this is not a
1438  // qualification conversion.
1439  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
1440    return false;
1441
1442  // (C++ 4.4p4):
1443  //   A conversion can add cv-qualifiers at levels other than the first
1444  //   in multi-level pointers, subject to the following rules: [...]
1445  bool PreviousToQualsIncludeConst = true;
1446  bool UnwrappedAnyPointer = false;
1447  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1448    // Within each iteration of the loop, we check the qualifiers to
1449    // determine if this still looks like a qualification
1450    // conversion. Then, if all is well, we unwrap one more level of
1451    // pointers or pointers-to-members and do it all again
1452    // until there are no more pointers or pointers-to-members left to
1453    // unwrap.
1454    UnwrappedAnyPointer = true;
1455
1456    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1457    //      2,j, and similarly for volatile.
1458    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1459      return false;
1460
1461    //   -- if the cv 1,j and cv 2,j are different, then const is in
1462    //      every cv for 0 < k < j.
1463    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1464        && !PreviousToQualsIncludeConst)
1465      return false;
1466
1467    // Keep track of whether all prior cv-qualifiers in the "to" type
1468    // include const.
1469    PreviousToQualsIncludeConst
1470      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1471  }
1472
1473  // We are left with FromType and ToType being the pointee types
1474  // after unwrapping the original FromType and ToType the same number
1475  // of types. If we unwrapped any pointers, and if FromType and
1476  // ToType have the same unqualified type (since we checked
1477  // qualifiers above), then this is a qualification conversion.
1478  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
1479}
1480
1481/// Determines whether there is a user-defined conversion sequence
1482/// (C++ [over.ics.user]) that converts expression From to the type
1483/// ToType. If such a conversion exists, User will contain the
1484/// user-defined conversion sequence that performs such a conversion
1485/// and this routine will return true. Otherwise, this routine returns
1486/// false and User is unspecified.
1487///
1488/// \param AllowConversionFunctions true if the conversion should
1489/// consider conversion functions at all. If false, only constructors
1490/// will be considered.
1491///
1492/// \param AllowExplicit  true if the conversion should consider C++0x
1493/// "explicit" conversion functions as well as non-explicit conversion
1494/// functions (C++0x [class.conv.fct]p2).
1495///
1496/// \param UserCast true if looking for user defined conversion for a static
1497/// cast.
1498OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1499                                          UserDefinedConversionSequence& User,
1500                                            OverloadCandidateSet& CandidateSet,
1501                                                bool AllowConversionFunctions,
1502                                                bool AllowExplicit,
1503                                                bool UserCast) {
1504  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1505    if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1506      // We're not going to find any constructors.
1507    } else if (CXXRecordDecl *ToRecordDecl
1508                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1509      // C++ [over.match.ctor]p1:
1510      //   When objects of class type are direct-initialized (8.5), or
1511      //   copy-initialized from an expression of the same or a
1512      //   derived class type (8.5), overload resolution selects the
1513      //   constructor. [...] For copy-initialization, the candidate
1514      //   functions are all the converting constructors (12.3.1) of
1515      //   that class. The argument list is the expression-list within
1516      //   the parentheses of the initializer.
1517      bool SuppressUserConversions = !UserCast;
1518      if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1519          IsDerivedFrom(From->getType(), ToType)) {
1520        SuppressUserConversions = false;
1521        AllowConversionFunctions = false;
1522      }
1523
1524      DeclarationName ConstructorName
1525        = Context.DeclarationNames.getCXXConstructorName(
1526                          Context.getCanonicalType(ToType).getUnqualifiedType());
1527      DeclContext::lookup_iterator Con, ConEnd;
1528      for (llvm::tie(Con, ConEnd)
1529             = ToRecordDecl->lookup(ConstructorName);
1530           Con != ConEnd; ++Con) {
1531        NamedDecl *D = *Con;
1532        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1533
1534        // Find the constructor (which may be a template).
1535        CXXConstructorDecl *Constructor = 0;
1536        FunctionTemplateDecl *ConstructorTmpl
1537          = dyn_cast<FunctionTemplateDecl>(D);
1538        if (ConstructorTmpl)
1539          Constructor
1540            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1541        else
1542          Constructor = cast<CXXConstructorDecl>(D);
1543
1544        if (!Constructor->isInvalidDecl() &&
1545            Constructor->isConvertingConstructor(AllowExplicit)) {
1546          if (ConstructorTmpl)
1547            AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
1548                                         /*ExplicitArgs*/ 0,
1549                                         &From, 1, CandidateSet,
1550                                         SuppressUserConversions);
1551          else
1552            // Allow one user-defined conversion when user specifies a
1553            // From->ToType conversion via an static cast (c-style, etc).
1554            AddOverloadCandidate(Constructor, FoundDecl,
1555                                 &From, 1, CandidateSet,
1556                                 SuppressUserConversions);
1557        }
1558      }
1559    }
1560  }
1561
1562  if (!AllowConversionFunctions) {
1563    // Don't allow any conversion functions to enter the overload set.
1564  } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1565                                 PDiag(0)
1566                                   << From->getSourceRange())) {
1567    // No conversion functions from incomplete types.
1568  } else if (const RecordType *FromRecordType
1569               = From->getType()->getAs<RecordType>()) {
1570    if (CXXRecordDecl *FromRecordDecl
1571         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1572      // Add all of the conversion functions as candidates.
1573      const UnresolvedSetImpl *Conversions
1574        = FromRecordDecl->getVisibleConversionFunctions();
1575      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1576             E = Conversions->end(); I != E; ++I) {
1577        DeclAccessPair FoundDecl = I.getPair();
1578        NamedDecl *D = FoundDecl.getDecl();
1579        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1580        if (isa<UsingShadowDecl>(D))
1581          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1582
1583        CXXConversionDecl *Conv;
1584        FunctionTemplateDecl *ConvTemplate;
1585        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1586          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1587        else
1588          Conv = cast<CXXConversionDecl>(D);
1589
1590        if (AllowExplicit || !Conv->isExplicit()) {
1591          if (ConvTemplate)
1592            AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
1593                                           ActingContext, From, ToType,
1594                                           CandidateSet);
1595          else
1596            AddConversionCandidate(Conv, FoundDecl, ActingContext,
1597                                   From, ToType, CandidateSet);
1598        }
1599      }
1600    }
1601  }
1602
1603  OverloadCandidateSet::iterator Best;
1604  switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1605    case OR_Success:
1606      // Record the standard conversion we used and the conversion function.
1607      if (CXXConstructorDecl *Constructor
1608            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1609        // C++ [over.ics.user]p1:
1610        //   If the user-defined conversion is specified by a
1611        //   constructor (12.3.1), the initial standard conversion
1612        //   sequence converts the source type to the type required by
1613        //   the argument of the constructor.
1614        //
1615        QualType ThisType = Constructor->getThisType(Context);
1616        if (Best->Conversions[0].isEllipsis())
1617          User.EllipsisConversion = true;
1618        else {
1619          User.Before = Best->Conversions[0].Standard;
1620          User.EllipsisConversion = false;
1621        }
1622        User.ConversionFunction = Constructor;
1623        User.After.setAsIdentityConversion();
1624        User.After.setFromType(
1625          ThisType->getAs<PointerType>()->getPointeeType());
1626        User.After.setAllToTypes(ToType);
1627        return OR_Success;
1628      } else if (CXXConversionDecl *Conversion
1629                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1630        // C++ [over.ics.user]p1:
1631        //
1632        //   [...] If the user-defined conversion is specified by a
1633        //   conversion function (12.3.2), the initial standard
1634        //   conversion sequence converts the source type to the
1635        //   implicit object parameter of the conversion function.
1636        User.Before = Best->Conversions[0].Standard;
1637        User.ConversionFunction = Conversion;
1638        User.EllipsisConversion = false;
1639
1640        // C++ [over.ics.user]p2:
1641        //   The second standard conversion sequence converts the
1642        //   result of the user-defined conversion to the target type
1643        //   for the sequence. Since an implicit conversion sequence
1644        //   is an initialization, the special rules for
1645        //   initialization by user-defined conversion apply when
1646        //   selecting the best user-defined conversion for a
1647        //   user-defined conversion sequence (see 13.3.3 and
1648        //   13.3.3.1).
1649        User.After = Best->FinalConversion;
1650        return OR_Success;
1651      } else {
1652        assert(false && "Not a constructor or conversion function?");
1653        return OR_No_Viable_Function;
1654      }
1655
1656    case OR_No_Viable_Function:
1657      return OR_No_Viable_Function;
1658    case OR_Deleted:
1659      // No conversion here! We're done.
1660      return OR_Deleted;
1661
1662    case OR_Ambiguous:
1663      return OR_Ambiguous;
1664    }
1665
1666  return OR_No_Viable_Function;
1667}
1668
1669bool
1670Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
1671  ImplicitConversionSequence ICS;
1672  OverloadCandidateSet CandidateSet(From->getExprLoc());
1673  OverloadingResult OvResult =
1674    IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1675                            CandidateSet, true, false, false);
1676  if (OvResult == OR_Ambiguous)
1677    Diag(From->getSourceRange().getBegin(),
1678         diag::err_typecheck_ambiguous_condition)
1679          << From->getType() << ToType << From->getSourceRange();
1680  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1681    Diag(From->getSourceRange().getBegin(),
1682         diag::err_typecheck_nonviable_condition)
1683    << From->getType() << ToType << From->getSourceRange();
1684  else
1685    return false;
1686  PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
1687  return true;
1688}
1689
1690/// CompareImplicitConversionSequences - Compare two implicit
1691/// conversion sequences to determine whether one is better than the
1692/// other or if they are indistinguishable (C++ 13.3.3.2).
1693ImplicitConversionSequence::CompareKind
1694Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1695                                         const ImplicitConversionSequence& ICS2)
1696{
1697  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1698  // conversion sequences (as defined in 13.3.3.1)
1699  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1700  //      conversion sequence than a user-defined conversion sequence or
1701  //      an ellipsis conversion sequence, and
1702  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1703  //      conversion sequence than an ellipsis conversion sequence
1704  //      (13.3.3.1.3).
1705  //
1706  // C++0x [over.best.ics]p10:
1707  //   For the purpose of ranking implicit conversion sequences as
1708  //   described in 13.3.3.2, the ambiguous conversion sequence is
1709  //   treated as a user-defined sequence that is indistinguishable
1710  //   from any other user-defined conversion sequence.
1711  if (ICS1.getKind() < ICS2.getKind()) {
1712    if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1713      return ImplicitConversionSequence::Better;
1714  } else if (ICS2.getKind() < ICS1.getKind()) {
1715    if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1716      return ImplicitConversionSequence::Worse;
1717  }
1718
1719  if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1720    return ImplicitConversionSequence::Indistinguishable;
1721
1722  // Two implicit conversion sequences of the same form are
1723  // indistinguishable conversion sequences unless one of the
1724  // following rules apply: (C++ 13.3.3.2p3):
1725  if (ICS1.isStandard())
1726    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1727  else if (ICS1.isUserDefined()) {
1728    // User-defined conversion sequence U1 is a better conversion
1729    // sequence than another user-defined conversion sequence U2 if
1730    // they contain the same user-defined conversion function or
1731    // constructor and if the second standard conversion sequence of
1732    // U1 is better than the second standard conversion sequence of
1733    // U2 (C++ 13.3.3.2p3).
1734    if (ICS1.UserDefined.ConversionFunction ==
1735          ICS2.UserDefined.ConversionFunction)
1736      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1737                                                ICS2.UserDefined.After);
1738  }
1739
1740  return ImplicitConversionSequence::Indistinguishable;
1741}
1742
1743// Per 13.3.3.2p3, compare the given standard conversion sequences to
1744// determine if one is a proper subset of the other.
1745static ImplicitConversionSequence::CompareKind
1746compareStandardConversionSubsets(ASTContext &Context,
1747                                 const StandardConversionSequence& SCS1,
1748                                 const StandardConversionSequence& SCS2) {
1749  ImplicitConversionSequence::CompareKind Result
1750    = ImplicitConversionSequence::Indistinguishable;
1751
1752  if (SCS1.Second != SCS2.Second) {
1753    if (SCS1.Second == ICK_Identity)
1754      Result = ImplicitConversionSequence::Better;
1755    else if (SCS2.Second == ICK_Identity)
1756      Result = ImplicitConversionSequence::Worse;
1757    else
1758      return ImplicitConversionSequence::Indistinguishable;
1759  } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1760    return ImplicitConversionSequence::Indistinguishable;
1761
1762  if (SCS1.Third == SCS2.Third) {
1763    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1764                             : ImplicitConversionSequence::Indistinguishable;
1765  }
1766
1767  if (SCS1.Third == ICK_Identity)
1768    return Result == ImplicitConversionSequence::Worse
1769             ? ImplicitConversionSequence::Indistinguishable
1770             : ImplicitConversionSequence::Better;
1771
1772  if (SCS2.Third == ICK_Identity)
1773    return Result == ImplicitConversionSequence::Better
1774             ? ImplicitConversionSequence::Indistinguishable
1775             : ImplicitConversionSequence::Worse;
1776
1777  return ImplicitConversionSequence::Indistinguishable;
1778}
1779
1780/// CompareStandardConversionSequences - Compare two standard
1781/// conversion sequences to determine whether one is better than the
1782/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1783ImplicitConversionSequence::CompareKind
1784Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1785                                         const StandardConversionSequence& SCS2)
1786{
1787  // Standard conversion sequence S1 is a better conversion sequence
1788  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1789
1790  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1791  //     sequences in the canonical form defined by 13.3.3.1.1,
1792  //     excluding any Lvalue Transformation; the identity conversion
1793  //     sequence is considered to be a subsequence of any
1794  //     non-identity conversion sequence) or, if not that,
1795  if (ImplicitConversionSequence::CompareKind CK
1796        = compareStandardConversionSubsets(Context, SCS1, SCS2))
1797    return CK;
1798
1799  //  -- the rank of S1 is better than the rank of S2 (by the rules
1800  //     defined below), or, if not that,
1801  ImplicitConversionRank Rank1 = SCS1.getRank();
1802  ImplicitConversionRank Rank2 = SCS2.getRank();
1803  if (Rank1 < Rank2)
1804    return ImplicitConversionSequence::Better;
1805  else if (Rank2 < Rank1)
1806    return ImplicitConversionSequence::Worse;
1807
1808  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1809  // are indistinguishable unless one of the following rules
1810  // applies:
1811
1812  //   A conversion that is not a conversion of a pointer, or
1813  //   pointer to member, to bool is better than another conversion
1814  //   that is such a conversion.
1815  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1816    return SCS2.isPointerConversionToBool()
1817             ? ImplicitConversionSequence::Better
1818             : ImplicitConversionSequence::Worse;
1819
1820  // C++ [over.ics.rank]p4b2:
1821  //
1822  //   If class B is derived directly or indirectly from class A,
1823  //   conversion of B* to A* is better than conversion of B* to
1824  //   void*, and conversion of A* to void* is better than conversion
1825  //   of B* to void*.
1826  bool SCS1ConvertsToVoid
1827    = SCS1.isPointerConversionToVoidPointer(Context);
1828  bool SCS2ConvertsToVoid
1829    = SCS2.isPointerConversionToVoidPointer(Context);
1830  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1831    // Exactly one of the conversion sequences is a conversion to
1832    // a void pointer; it's the worse conversion.
1833    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1834                              : ImplicitConversionSequence::Worse;
1835  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1836    // Neither conversion sequence converts to a void pointer; compare
1837    // their derived-to-base conversions.
1838    if (ImplicitConversionSequence::CompareKind DerivedCK
1839          = CompareDerivedToBaseConversions(SCS1, SCS2))
1840      return DerivedCK;
1841  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1842    // Both conversion sequences are conversions to void
1843    // pointers. Compare the source types to determine if there's an
1844    // inheritance relationship in their sources.
1845    QualType FromType1 = SCS1.getFromType();
1846    QualType FromType2 = SCS2.getFromType();
1847
1848    // Adjust the types we're converting from via the array-to-pointer
1849    // conversion, if we need to.
1850    if (SCS1.First == ICK_Array_To_Pointer)
1851      FromType1 = Context.getArrayDecayedType(FromType1);
1852    if (SCS2.First == ICK_Array_To_Pointer)
1853      FromType2 = Context.getArrayDecayedType(FromType2);
1854
1855    QualType FromPointee1
1856      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1857    QualType FromPointee2
1858      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1859
1860    if (IsDerivedFrom(FromPointee2, FromPointee1))
1861      return ImplicitConversionSequence::Better;
1862    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1863      return ImplicitConversionSequence::Worse;
1864
1865    // Objective-C++: If one interface is more specific than the
1866    // other, it is the better one.
1867    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1868    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1869    if (FromIface1 && FromIface1) {
1870      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1871        return ImplicitConversionSequence::Better;
1872      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1873        return ImplicitConversionSequence::Worse;
1874    }
1875  }
1876
1877  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1878  // bullet 3).
1879  if (ImplicitConversionSequence::CompareKind QualCK
1880        = CompareQualificationConversions(SCS1, SCS2))
1881    return QualCK;
1882
1883  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1884    // C++0x [over.ics.rank]p3b4:
1885    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1886    //      implicit object parameter of a non-static member function declared
1887    //      without a ref-qualifier, and S1 binds an rvalue reference to an
1888    //      rvalue and S2 binds an lvalue reference.
1889    // FIXME: We don't know if we're dealing with the implicit object parameter,
1890    // or if the member function in this case has a ref qualifier.
1891    // (Of course, we don't have ref qualifiers yet.)
1892    if (SCS1.RRefBinding != SCS2.RRefBinding)
1893      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1894                              : ImplicitConversionSequence::Worse;
1895
1896    // C++ [over.ics.rank]p3b4:
1897    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1898    //      which the references refer are the same type except for
1899    //      top-level cv-qualifiers, and the type to which the reference
1900    //      initialized by S2 refers is more cv-qualified than the type
1901    //      to which the reference initialized by S1 refers.
1902    QualType T1 = SCS1.getToType(2);
1903    QualType T2 = SCS2.getToType(2);
1904    T1 = Context.getCanonicalType(T1);
1905    T2 = Context.getCanonicalType(T2);
1906    Qualifiers T1Quals, T2Quals;
1907    QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1908    QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1909    if (UnqualT1 == UnqualT2) {
1910      // If the type is an array type, promote the element qualifiers to the type
1911      // for comparison.
1912      if (isa<ArrayType>(T1) && T1Quals)
1913        T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1914      if (isa<ArrayType>(T2) && T2Quals)
1915        T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1916      if (T2.isMoreQualifiedThan(T1))
1917        return ImplicitConversionSequence::Better;
1918      else if (T1.isMoreQualifiedThan(T2))
1919        return ImplicitConversionSequence::Worse;
1920    }
1921  }
1922
1923  return ImplicitConversionSequence::Indistinguishable;
1924}
1925
1926/// CompareQualificationConversions - Compares two standard conversion
1927/// sequences to determine whether they can be ranked based on their
1928/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1929ImplicitConversionSequence::CompareKind
1930Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1931                                      const StandardConversionSequence& SCS2) {
1932  // C++ 13.3.3.2p3:
1933  //  -- S1 and S2 differ only in their qualification conversion and
1934  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1935  //     cv-qualification signature of type T1 is a proper subset of
1936  //     the cv-qualification signature of type T2, and S1 is not the
1937  //     deprecated string literal array-to-pointer conversion (4.2).
1938  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1939      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1940    return ImplicitConversionSequence::Indistinguishable;
1941
1942  // FIXME: the example in the standard doesn't use a qualification
1943  // conversion (!)
1944  QualType T1 = SCS1.getToType(2);
1945  QualType T2 = SCS2.getToType(2);
1946  T1 = Context.getCanonicalType(T1);
1947  T2 = Context.getCanonicalType(T2);
1948  Qualifiers T1Quals, T2Quals;
1949  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1950  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1951
1952  // If the types are the same, we won't learn anything by unwrapped
1953  // them.
1954  if (UnqualT1 == UnqualT2)
1955    return ImplicitConversionSequence::Indistinguishable;
1956
1957  // If the type is an array type, promote the element qualifiers to the type
1958  // for comparison.
1959  if (isa<ArrayType>(T1) && T1Quals)
1960    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1961  if (isa<ArrayType>(T2) && T2Quals)
1962    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1963
1964  ImplicitConversionSequence::CompareKind Result
1965    = ImplicitConversionSequence::Indistinguishable;
1966  while (UnwrapSimilarPointerTypes(T1, T2)) {
1967    // Within each iteration of the loop, we check the qualifiers to
1968    // determine if this still looks like a qualification
1969    // conversion. Then, if all is well, we unwrap one more level of
1970    // pointers or pointers-to-members and do it all again
1971    // until there are no more pointers or pointers-to-members left
1972    // to unwrap. This essentially mimics what
1973    // IsQualificationConversion does, but here we're checking for a
1974    // strict subset of qualifiers.
1975    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1976      // The qualifiers are the same, so this doesn't tell us anything
1977      // about how the sequences rank.
1978      ;
1979    else if (T2.isMoreQualifiedThan(T1)) {
1980      // T1 has fewer qualifiers, so it could be the better sequence.
1981      if (Result == ImplicitConversionSequence::Worse)
1982        // Neither has qualifiers that are a subset of the other's
1983        // qualifiers.
1984        return ImplicitConversionSequence::Indistinguishable;
1985
1986      Result = ImplicitConversionSequence::Better;
1987    } else if (T1.isMoreQualifiedThan(T2)) {
1988      // T2 has fewer qualifiers, so it could be the better sequence.
1989      if (Result == ImplicitConversionSequence::Better)
1990        // Neither has qualifiers that are a subset of the other's
1991        // qualifiers.
1992        return ImplicitConversionSequence::Indistinguishable;
1993
1994      Result = ImplicitConversionSequence::Worse;
1995    } else {
1996      // Qualifiers are disjoint.
1997      return ImplicitConversionSequence::Indistinguishable;
1998    }
1999
2000    // If the types after this point are equivalent, we're done.
2001    if (Context.hasSameUnqualifiedType(T1, T2))
2002      break;
2003  }
2004
2005  // Check that the winning standard conversion sequence isn't using
2006  // the deprecated string literal array to pointer conversion.
2007  switch (Result) {
2008  case ImplicitConversionSequence::Better:
2009    if (SCS1.DeprecatedStringLiteralToCharPtr)
2010      Result = ImplicitConversionSequence::Indistinguishable;
2011    break;
2012
2013  case ImplicitConversionSequence::Indistinguishable:
2014    break;
2015
2016  case ImplicitConversionSequence::Worse:
2017    if (SCS2.DeprecatedStringLiteralToCharPtr)
2018      Result = ImplicitConversionSequence::Indistinguishable;
2019    break;
2020  }
2021
2022  return Result;
2023}
2024
2025/// CompareDerivedToBaseConversions - Compares two standard conversion
2026/// sequences to determine whether they can be ranked based on their
2027/// various kinds of derived-to-base conversions (C++
2028/// [over.ics.rank]p4b3).  As part of these checks, we also look at
2029/// conversions between Objective-C interface types.
2030ImplicitConversionSequence::CompareKind
2031Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2032                                      const StandardConversionSequence& SCS2) {
2033  QualType FromType1 = SCS1.getFromType();
2034  QualType ToType1 = SCS1.getToType(1);
2035  QualType FromType2 = SCS2.getFromType();
2036  QualType ToType2 = SCS2.getToType(1);
2037
2038  // Adjust the types we're converting from via the array-to-pointer
2039  // conversion, if we need to.
2040  if (SCS1.First == ICK_Array_To_Pointer)
2041    FromType1 = Context.getArrayDecayedType(FromType1);
2042  if (SCS2.First == ICK_Array_To_Pointer)
2043    FromType2 = Context.getArrayDecayedType(FromType2);
2044
2045  // Canonicalize all of the types.
2046  FromType1 = Context.getCanonicalType(FromType1);
2047  ToType1 = Context.getCanonicalType(ToType1);
2048  FromType2 = Context.getCanonicalType(FromType2);
2049  ToType2 = Context.getCanonicalType(ToType2);
2050
2051  // C++ [over.ics.rank]p4b3:
2052  //
2053  //   If class B is derived directly or indirectly from class A and
2054  //   class C is derived directly or indirectly from B,
2055  //
2056  // For Objective-C, we let A, B, and C also be Objective-C
2057  // interfaces.
2058
2059  // Compare based on pointer conversions.
2060  if (SCS1.Second == ICK_Pointer_Conversion &&
2061      SCS2.Second == ICK_Pointer_Conversion &&
2062      /*FIXME: Remove if Objective-C id conversions get their own rank*/
2063      FromType1->isPointerType() && FromType2->isPointerType() &&
2064      ToType1->isPointerType() && ToType2->isPointerType()) {
2065    QualType FromPointee1
2066      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2067    QualType ToPointee1
2068      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2069    QualType FromPointee2
2070      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2071    QualType ToPointee2
2072      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2073
2074    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2075    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2076    const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2077    const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
2078
2079    //   -- conversion of C* to B* is better than conversion of C* to A*,
2080    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2081      if (IsDerivedFrom(ToPointee1, ToPointee2))
2082        return ImplicitConversionSequence::Better;
2083      else if (IsDerivedFrom(ToPointee2, ToPointee1))
2084        return ImplicitConversionSequence::Worse;
2085
2086      if (ToIface1 && ToIface2) {
2087        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2088          return ImplicitConversionSequence::Better;
2089        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2090          return ImplicitConversionSequence::Worse;
2091      }
2092    }
2093
2094    //   -- conversion of B* to A* is better than conversion of C* to A*,
2095    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2096      if (IsDerivedFrom(FromPointee2, FromPointee1))
2097        return ImplicitConversionSequence::Better;
2098      else if (IsDerivedFrom(FromPointee1, FromPointee2))
2099        return ImplicitConversionSequence::Worse;
2100
2101      if (FromIface1 && FromIface2) {
2102        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2103          return ImplicitConversionSequence::Better;
2104        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2105          return ImplicitConversionSequence::Worse;
2106      }
2107    }
2108  }
2109
2110  // Ranking of member-pointer types.
2111  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2112      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2113      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2114    const MemberPointerType * FromMemPointer1 =
2115                                        FromType1->getAs<MemberPointerType>();
2116    const MemberPointerType * ToMemPointer1 =
2117                                          ToType1->getAs<MemberPointerType>();
2118    const MemberPointerType * FromMemPointer2 =
2119                                          FromType2->getAs<MemberPointerType>();
2120    const MemberPointerType * ToMemPointer2 =
2121                                          ToType2->getAs<MemberPointerType>();
2122    const Type *FromPointeeType1 = FromMemPointer1->getClass();
2123    const Type *ToPointeeType1 = ToMemPointer1->getClass();
2124    const Type *FromPointeeType2 = FromMemPointer2->getClass();
2125    const Type *ToPointeeType2 = ToMemPointer2->getClass();
2126    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2127    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2128    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2129    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
2130    // conversion of A::* to B::* is better than conversion of A::* to C::*,
2131    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2132      if (IsDerivedFrom(ToPointee1, ToPointee2))
2133        return ImplicitConversionSequence::Worse;
2134      else if (IsDerivedFrom(ToPointee2, ToPointee1))
2135        return ImplicitConversionSequence::Better;
2136    }
2137    // conversion of B::* to C::* is better than conversion of A::* to C::*
2138    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2139      if (IsDerivedFrom(FromPointee1, FromPointee2))
2140        return ImplicitConversionSequence::Better;
2141      else if (IsDerivedFrom(FromPointee2, FromPointee1))
2142        return ImplicitConversionSequence::Worse;
2143    }
2144  }
2145
2146  if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2147      (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
2148      SCS1.Second == ICK_Derived_To_Base) {
2149    //   -- conversion of C to B is better than conversion of C to A,
2150    //   -- binding of an expression of type C to a reference of type
2151    //      B& is better than binding an expression of type C to a
2152    //      reference of type A&,
2153    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2154        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2155      if (IsDerivedFrom(ToType1, ToType2))
2156        return ImplicitConversionSequence::Better;
2157      else if (IsDerivedFrom(ToType2, ToType1))
2158        return ImplicitConversionSequence::Worse;
2159    }
2160
2161    //   -- conversion of B to A is better than conversion of C to A.
2162    //   -- binding of an expression of type B to a reference of type
2163    //      A& is better than binding an expression of type C to a
2164    //      reference of type A&,
2165    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2166        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2167      if (IsDerivedFrom(FromType2, FromType1))
2168        return ImplicitConversionSequence::Better;
2169      else if (IsDerivedFrom(FromType1, FromType2))
2170        return ImplicitConversionSequence::Worse;
2171    }
2172  }
2173
2174  return ImplicitConversionSequence::Indistinguishable;
2175}
2176
2177/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2178/// determine whether they are reference-related,
2179/// reference-compatible, reference-compatible with added
2180/// qualification, or incompatible, for use in C++ initialization by
2181/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2182/// type, and the first type (T1) is the pointee type of the reference
2183/// type being initialized.
2184Sema::ReferenceCompareResult
2185Sema::CompareReferenceRelationship(SourceLocation Loc,
2186                                   QualType OrigT1, QualType OrigT2,
2187                                   bool& DerivedToBase) {
2188  assert(!OrigT1->isReferenceType() &&
2189    "T1 must be the pointee type of the reference type");
2190  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2191
2192  QualType T1 = Context.getCanonicalType(OrigT1);
2193  QualType T2 = Context.getCanonicalType(OrigT2);
2194  Qualifiers T1Quals, T2Quals;
2195  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2196  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2197
2198  // C++ [dcl.init.ref]p4:
2199  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2200  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
2201  //   T1 is a base class of T2.
2202  if (UnqualT1 == UnqualT2)
2203    DerivedToBase = false;
2204  else if (!RequireCompleteType(Loc, OrigT1, PDiag()) &&
2205           !RequireCompleteType(Loc, OrigT2, PDiag()) &&
2206           IsDerivedFrom(UnqualT2, UnqualT1))
2207    DerivedToBase = true;
2208  else
2209    return Ref_Incompatible;
2210
2211  // At this point, we know that T1 and T2 are reference-related (at
2212  // least).
2213
2214  // If the type is an array type, promote the element qualifiers to the type
2215  // for comparison.
2216  if (isa<ArrayType>(T1) && T1Quals)
2217    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2218  if (isa<ArrayType>(T2) && T2Quals)
2219    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2220
2221  // C++ [dcl.init.ref]p4:
2222  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2223  //   reference-related to T2 and cv1 is the same cv-qualification
2224  //   as, or greater cv-qualification than, cv2. For purposes of
2225  //   overload resolution, cases for which cv1 is greater
2226  //   cv-qualification than cv2 are identified as
2227  //   reference-compatible with added qualification (see 13.3.3.2).
2228  if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2229    return Ref_Compatible;
2230  else if (T1.isMoreQualifiedThan(T2))
2231    return Ref_Compatible_With_Added_Qualification;
2232  else
2233    return Ref_Related;
2234}
2235
2236/// \brief Compute an implicit conversion sequence for reference
2237/// initialization.
2238static ImplicitConversionSequence
2239TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2240                 SourceLocation DeclLoc,
2241                 bool SuppressUserConversions,
2242                 bool AllowExplicit) {
2243  assert(DeclType->isReferenceType() && "Reference init needs a reference");
2244
2245  // Most paths end in a failed conversion.
2246  ImplicitConversionSequence ICS;
2247  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2248
2249  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2250  QualType T2 = Init->getType();
2251
2252  // If the initializer is the address of an overloaded function, try
2253  // to resolve the overloaded function. If all goes well, T2 is the
2254  // type of the resulting function.
2255  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2256    DeclAccessPair Found;
2257    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2258                                                                false, Found))
2259      T2 = Fn->getType();
2260  }
2261
2262  // Compute some basic properties of the types and the initializer.
2263  bool isRValRef = DeclType->isRValueReferenceType();
2264  bool DerivedToBase = false;
2265  Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
2266  Sema::ReferenceCompareResult RefRelationship
2267    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2268
2269  // C++ [dcl.init.ref]p5:
2270  //   A reference to type "cv1 T1" is initialized by an expression
2271  //   of type "cv2 T2" as follows:
2272
2273  //     -- If the initializer expression
2274
2275  // C++ [over.ics.ref]p3:
2276  //   Except for an implicit object parameter, for which see 13.3.1,
2277  //   a standard conversion sequence cannot be formed if it requires
2278  //   binding an lvalue reference to non-const to an rvalue or
2279  //   binding an rvalue reference to an lvalue.
2280  if (isRValRef && InitLvalue == Expr::LV_Valid)
2281    return ICS;
2282
2283  //       -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2284  //          reference-compatible with "cv2 T2," or
2285  //
2286  // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2287  if (InitLvalue == Expr::LV_Valid &&
2288      RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2289    // C++ [over.ics.ref]p1:
2290    //   When a parameter of reference type binds directly (8.5.3)
2291    //   to an argument expression, the implicit conversion sequence
2292    //   is the identity conversion, unless the argument expression
2293    //   has a type that is a derived class of the parameter type,
2294    //   in which case the implicit conversion sequence is a
2295    //   derived-to-base Conversion (13.3.3.1).
2296    ICS.setStandard();
2297    ICS.Standard.First = ICK_Identity;
2298    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2299    ICS.Standard.Third = ICK_Identity;
2300    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2301    ICS.Standard.setToType(0, T2);
2302    ICS.Standard.setToType(1, T1);
2303    ICS.Standard.setToType(2, T1);
2304    ICS.Standard.ReferenceBinding = true;
2305    ICS.Standard.DirectBinding = true;
2306    ICS.Standard.RRefBinding = false;
2307    ICS.Standard.CopyConstructor = 0;
2308
2309    // Nothing more to do: the inaccessibility/ambiguity check for
2310    // derived-to-base conversions is suppressed when we're
2311    // computing the implicit conversion sequence (C++
2312    // [over.best.ics]p2).
2313    return ICS;
2314  }
2315
2316  //       -- has a class type (i.e., T2 is a class type), where T1 is
2317  //          not reference-related to T2, and can be implicitly
2318  //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
2319  //          is reference-compatible with "cv3 T3" 92) (this
2320  //          conversion is selected by enumerating the applicable
2321  //          conversion functions (13.3.1.6) and choosing the best
2322  //          one through overload resolution (13.3)),
2323  if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2324      !S.RequireCompleteType(DeclLoc, T2, 0) &&
2325      RefRelationship == Sema::Ref_Incompatible) {
2326    CXXRecordDecl *T2RecordDecl
2327      = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2328
2329    OverloadCandidateSet CandidateSet(DeclLoc);
2330    const UnresolvedSetImpl *Conversions
2331      = T2RecordDecl->getVisibleConversionFunctions();
2332    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2333           E = Conversions->end(); I != E; ++I) {
2334      NamedDecl *D = *I;
2335      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2336      if (isa<UsingShadowDecl>(D))
2337        D = cast<UsingShadowDecl>(D)->getTargetDecl();
2338
2339      FunctionTemplateDecl *ConvTemplate
2340        = dyn_cast<FunctionTemplateDecl>(D);
2341      CXXConversionDecl *Conv;
2342      if (ConvTemplate)
2343        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2344      else
2345        Conv = cast<CXXConversionDecl>(D);
2346
2347      // If the conversion function doesn't return a reference type,
2348      // it can't be considered for this conversion.
2349      if (Conv->getConversionType()->isLValueReferenceType() &&
2350          (AllowExplicit || !Conv->isExplicit())) {
2351        if (ConvTemplate)
2352          S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2353                                         Init, DeclType, CandidateSet);
2354        else
2355          S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2356                                 DeclType, CandidateSet);
2357      }
2358    }
2359
2360    OverloadCandidateSet::iterator Best;
2361    switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2362    case OR_Success:
2363      // C++ [over.ics.ref]p1:
2364      //
2365      //   [...] If the parameter binds directly to the result of
2366      //   applying a conversion function to the argument
2367      //   expression, the implicit conversion sequence is a
2368      //   user-defined conversion sequence (13.3.3.1.2), with the
2369      //   second standard conversion sequence either an identity
2370      //   conversion or, if the conversion function returns an
2371      //   entity of a type that is a derived class of the parameter
2372      //   type, a derived-to-base Conversion.
2373      if (!Best->FinalConversion.DirectBinding)
2374        break;
2375
2376      ICS.setUserDefined();
2377      ICS.UserDefined.Before = Best->Conversions[0].Standard;
2378      ICS.UserDefined.After = Best->FinalConversion;
2379      ICS.UserDefined.ConversionFunction = Best->Function;
2380      ICS.UserDefined.EllipsisConversion = false;
2381      assert(ICS.UserDefined.After.ReferenceBinding &&
2382             ICS.UserDefined.After.DirectBinding &&
2383             "Expected a direct reference binding!");
2384      return ICS;
2385
2386    case OR_Ambiguous:
2387      ICS.setAmbiguous();
2388      for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2389           Cand != CandidateSet.end(); ++Cand)
2390        if (Cand->Viable)
2391          ICS.Ambiguous.addConversion(Cand->Function);
2392      return ICS;
2393
2394    case OR_No_Viable_Function:
2395    case OR_Deleted:
2396      // There was no suitable conversion, or we found a deleted
2397      // conversion; continue with other checks.
2398      break;
2399    }
2400  }
2401
2402  //     -- Otherwise, the reference shall be to a non-volatile const
2403  //        type (i.e., cv1 shall be const), or the reference shall be an
2404  //        rvalue reference and the initializer expression shall be an rvalue.
2405  if (!isRValRef && T1.getCVRQualifiers() != Qualifiers::Const)
2406    return ICS;
2407
2408  //       -- If the initializer expression is an rvalue, with T2 a
2409  //          class type, and "cv1 T1" is reference-compatible with
2410  //          "cv2 T2," the reference is bound in one of the
2411  //          following ways (the choice is implementation-defined):
2412  //
2413  //          -- The reference is bound to the object represented by
2414  //             the rvalue (see 3.10) or to a sub-object within that
2415  //             object.
2416  //
2417  //          -- A temporary of type "cv1 T2" [sic] is created, and
2418  //             a constructor is called to copy the entire rvalue
2419  //             object into the temporary. The reference is bound to
2420  //             the temporary or to a sub-object within the
2421  //             temporary.
2422  //
2423  //          The constructor that would be used to make the copy
2424  //          shall be callable whether or not the copy is actually
2425  //          done.
2426  //
2427  // Note that C++0x [dcl.init.ref]p5 takes away this implementation
2428  // freedom, so we will always take the first option and never build
2429  // a temporary in this case.
2430  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2431      RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2432    ICS.setStandard();
2433    ICS.Standard.First = ICK_Identity;
2434    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2435    ICS.Standard.Third = ICK_Identity;
2436    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2437    ICS.Standard.setToType(0, T2);
2438    ICS.Standard.setToType(1, T1);
2439    ICS.Standard.setToType(2, T1);
2440    ICS.Standard.ReferenceBinding = true;
2441    ICS.Standard.DirectBinding = false;
2442    ICS.Standard.RRefBinding = isRValRef;
2443    ICS.Standard.CopyConstructor = 0;
2444    return ICS;
2445  }
2446
2447  //       -- Otherwise, a temporary of type "cv1 T1" is created and
2448  //          initialized from the initializer expression using the
2449  //          rules for a non-reference copy initialization (8.5). The
2450  //          reference is then bound to the temporary. If T1 is
2451  //          reference-related to T2, cv1 must be the same
2452  //          cv-qualification as, or greater cv-qualification than,
2453  //          cv2; otherwise, the program is ill-formed.
2454  if (RefRelationship == Sema::Ref_Related) {
2455    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2456    // we would be reference-compatible or reference-compatible with
2457    // added qualification. But that wasn't the case, so the reference
2458    // initialization fails.
2459    return ICS;
2460  }
2461
2462  // If at least one of the types is a class type, the types are not
2463  // related, and we aren't allowed any user conversions, the
2464  // reference binding fails. This case is important for breaking
2465  // recursion, since TryImplicitConversion below will attempt to
2466  // create a temporary through the use of a copy constructor.
2467  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2468      (T1->isRecordType() || T2->isRecordType()))
2469    return ICS;
2470
2471  // C++ [over.ics.ref]p2:
2472  //
2473  //   When a parameter of reference type is not bound directly to
2474  //   an argument expression, the conversion sequence is the one
2475  //   required to convert the argument expression to the
2476  //   underlying type of the reference according to
2477  //   13.3.3.1. Conceptually, this conversion sequence corresponds
2478  //   to copy-initializing a temporary of the underlying type with
2479  //   the argument expression. Any difference in top-level
2480  //   cv-qualification is subsumed by the initialization itself
2481  //   and does not constitute a conversion.
2482  ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2483                                /*AllowExplicit=*/false,
2484                                /*InOverloadResolution=*/false);
2485
2486  // Of course, that's still a reference binding.
2487  if (ICS.isStandard()) {
2488    ICS.Standard.ReferenceBinding = true;
2489    ICS.Standard.RRefBinding = isRValRef;
2490  } else if (ICS.isUserDefined()) {
2491    ICS.UserDefined.After.ReferenceBinding = true;
2492    ICS.UserDefined.After.RRefBinding = isRValRef;
2493  }
2494  return ICS;
2495}
2496
2497/// TryCopyInitialization - Try to copy-initialize a value of type
2498/// ToType from the expression From. Return the implicit conversion
2499/// sequence required to pass this argument, which may be a bad
2500/// conversion sequence (meaning that the argument cannot be passed to
2501/// a parameter of this type). If @p SuppressUserConversions, then we
2502/// do not permit any user-defined conversion sequences.
2503static ImplicitConversionSequence
2504TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
2505                      bool SuppressUserConversions,
2506                      bool InOverloadResolution) {
2507  if (ToType->isReferenceType())
2508    return TryReferenceInit(S, From, ToType,
2509                            /*FIXME:*/From->getLocStart(),
2510                            SuppressUserConversions,
2511                            /*AllowExplicit=*/false);
2512
2513  return S.TryImplicitConversion(From, ToType,
2514                                 SuppressUserConversions,
2515                                 /*AllowExplicit=*/false,
2516                                 InOverloadResolution);
2517}
2518
2519/// TryObjectArgumentInitialization - Try to initialize the object
2520/// parameter of the given member function (@c Method) from the
2521/// expression @p From.
2522ImplicitConversionSequence
2523Sema::TryObjectArgumentInitialization(QualType OrigFromType,
2524                                      CXXMethodDecl *Method,
2525                                      CXXRecordDecl *ActingContext) {
2526  QualType ClassType = Context.getTypeDeclType(ActingContext);
2527  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2528  //                 const volatile object.
2529  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2530    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2531  QualType ImplicitParamType =  Context.getCVRQualifiedType(ClassType, Quals);
2532
2533  // Set up the conversion sequence as a "bad" conversion, to allow us
2534  // to exit early.
2535  ImplicitConversionSequence ICS;
2536
2537  // We need to have an object of class type.
2538  QualType FromType = OrigFromType;
2539  if (const PointerType *PT = FromType->getAs<PointerType>())
2540    FromType = PT->getPointeeType();
2541
2542  assert(FromType->isRecordType());
2543
2544  // The implicit object parameter is has the type "reference to cv X",
2545  // where X is the class of which the function is a member
2546  // (C++ [over.match.funcs]p4). However, when finding an implicit
2547  // conversion sequence for the argument, we are not allowed to
2548  // create temporaries or perform user-defined conversions
2549  // (C++ [over.match.funcs]p5). We perform a simplified version of
2550  // reference binding here, that allows class rvalues to bind to
2551  // non-constant references.
2552
2553  // First check the qualifiers. We don't care about lvalue-vs-rvalue
2554  // with the implicit object parameter (C++ [over.match.funcs]p5).
2555  QualType FromTypeCanon = Context.getCanonicalType(FromType);
2556  if (ImplicitParamType.getCVRQualifiers()
2557                                    != FromTypeCanon.getLocalCVRQualifiers() &&
2558      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
2559    ICS.setBad(BadConversionSequence::bad_qualifiers,
2560               OrigFromType, ImplicitParamType);
2561    return ICS;
2562  }
2563
2564  // Check that we have either the same type or a derived type. It
2565  // affects the conversion rank.
2566  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2567  ImplicitConversionKind SecondKind;
2568  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2569    SecondKind = ICK_Identity;
2570  } else if (IsDerivedFrom(FromType, ClassType))
2571    SecondKind = ICK_Derived_To_Base;
2572  else {
2573    ICS.setBad(BadConversionSequence::unrelated_class,
2574               FromType, ImplicitParamType);
2575    return ICS;
2576  }
2577
2578  // Success. Mark this as a reference binding.
2579  ICS.setStandard();
2580  ICS.Standard.setAsIdentityConversion();
2581  ICS.Standard.Second = SecondKind;
2582  ICS.Standard.setFromType(FromType);
2583  ICS.Standard.setAllToTypes(ImplicitParamType);
2584  ICS.Standard.ReferenceBinding = true;
2585  ICS.Standard.DirectBinding = true;
2586  ICS.Standard.RRefBinding = false;
2587  return ICS;
2588}
2589
2590/// PerformObjectArgumentInitialization - Perform initialization of
2591/// the implicit object parameter for the given Method with the given
2592/// expression.
2593bool
2594Sema::PerformObjectArgumentInitialization(Expr *&From,
2595                                          NestedNameSpecifier *Qualifier,
2596                                          NamedDecl *FoundDecl,
2597                                          CXXMethodDecl *Method) {
2598  QualType FromRecordType, DestType;
2599  QualType ImplicitParamRecordType  =
2600    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2601
2602  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
2603    FromRecordType = PT->getPointeeType();
2604    DestType = Method->getThisType(Context);
2605  } else {
2606    FromRecordType = From->getType();
2607    DestType = ImplicitParamRecordType;
2608  }
2609
2610  // Note that we always use the true parent context when performing
2611  // the actual argument initialization.
2612  ImplicitConversionSequence ICS
2613    = TryObjectArgumentInitialization(From->getType(), Method,
2614                                      Method->getParent());
2615  if (ICS.isBad())
2616    return Diag(From->getSourceRange().getBegin(),
2617                diag::err_implicit_object_parameter_init)
2618       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2619
2620  if (ICS.Standard.Second == ICK_Derived_To_Base)
2621    return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
2622
2623  if (!Context.hasSameType(From->getType(), DestType))
2624    ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2625                      /*isLvalue=*/!From->getType()->getAs<PointerType>());
2626  return false;
2627}
2628
2629/// TryContextuallyConvertToBool - Attempt to contextually convert the
2630/// expression From to bool (C++0x [conv]p3).
2631ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2632  return TryImplicitConversion(From, Context.BoolTy,
2633                               // FIXME: Are these flags correct?
2634                               /*SuppressUserConversions=*/false,
2635                               /*AllowExplicit=*/true,
2636                               /*InOverloadResolution=*/false);
2637}
2638
2639/// PerformContextuallyConvertToBool - Perform a contextual conversion
2640/// of the expression From to bool (C++0x [conv]p3).
2641bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2642  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2643  if (!ICS.isBad())
2644    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
2645
2646  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
2647    return  Diag(From->getSourceRange().getBegin(),
2648                 diag::err_typecheck_bool_condition)
2649                  << From->getType() << From->getSourceRange();
2650  return true;
2651}
2652
2653/// AddOverloadCandidate - Adds the given function to the set of
2654/// candidate functions, using the given function call arguments.  If
2655/// @p SuppressUserConversions, then don't allow user-defined
2656/// conversions via constructors or conversion operators.
2657///
2658/// \para PartialOverloading true if we are performing "partial" overloading
2659/// based on an incomplete set of function arguments. This feature is used by
2660/// code completion.
2661void
2662Sema::AddOverloadCandidate(FunctionDecl *Function,
2663                           DeclAccessPair FoundDecl,
2664                           Expr **Args, unsigned NumArgs,
2665                           OverloadCandidateSet& CandidateSet,
2666                           bool SuppressUserConversions,
2667                           bool PartialOverloading) {
2668  const FunctionProtoType* Proto
2669    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
2670  assert(Proto && "Functions without a prototype cannot be overloaded");
2671  assert(!Function->getDescribedFunctionTemplate() &&
2672         "Use AddTemplateOverloadCandidate for function templates");
2673
2674  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2675    if (!isa<CXXConstructorDecl>(Method)) {
2676      // If we get here, it's because we're calling a member function
2677      // that is named without a member access expression (e.g.,
2678      // "this->f") that was either written explicitly or created
2679      // implicitly. This can happen with a qualified call to a member
2680      // function, e.g., X::f(). We use an empty type for the implied
2681      // object argument (C++ [over.call.func]p3), and the acting context
2682      // is irrelevant.
2683      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
2684                         QualType(), Args, NumArgs, CandidateSet,
2685                         SuppressUserConversions);
2686      return;
2687    }
2688    // We treat a constructor like a non-member function, since its object
2689    // argument doesn't participate in overload resolution.
2690  }
2691
2692  if (!CandidateSet.isNewCandidate(Function))
2693    return;
2694
2695  // Overload resolution is always an unevaluated context.
2696  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2697
2698  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2699    // C++ [class.copy]p3:
2700    //   A member function template is never instantiated to perform the copy
2701    //   of a class object to an object of its class type.
2702    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2703    if (NumArgs == 1 &&
2704        Constructor->isCopyConstructorLikeSpecialization() &&
2705        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2706         IsDerivedFrom(Args[0]->getType(), ClassType)))
2707      return;
2708  }
2709
2710  // Add this candidate
2711  CandidateSet.push_back(OverloadCandidate());
2712  OverloadCandidate& Candidate = CandidateSet.back();
2713  Candidate.FoundDecl = FoundDecl;
2714  Candidate.Function = Function;
2715  Candidate.Viable = true;
2716  Candidate.IsSurrogate = false;
2717  Candidate.IgnoreObjectArgument = false;
2718
2719  unsigned NumArgsInProto = Proto->getNumArgs();
2720
2721  // (C++ 13.3.2p2): A candidate function having fewer than m
2722  // parameters is viable only if it has an ellipsis in its parameter
2723  // list (8.3.5).
2724  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2725      !Proto->isVariadic()) {
2726    Candidate.Viable = false;
2727    Candidate.FailureKind = ovl_fail_too_many_arguments;
2728    return;
2729  }
2730
2731  // (C++ 13.3.2p2): A candidate function having more than m parameters
2732  // is viable only if the (m+1)st parameter has a default argument
2733  // (8.3.6). For the purposes of overload resolution, the
2734  // parameter list is truncated on the right, so that there are
2735  // exactly m parameters.
2736  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2737  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
2738    // Not enough arguments.
2739    Candidate.Viable = false;
2740    Candidate.FailureKind = ovl_fail_too_few_arguments;
2741    return;
2742  }
2743
2744  // Determine the implicit conversion sequences for each of the
2745  // arguments.
2746  Candidate.Conversions.resize(NumArgs);
2747  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2748    if (ArgIdx < NumArgsInProto) {
2749      // (C++ 13.3.2p3): for F to be a viable function, there shall
2750      // exist for each argument an implicit conversion sequence
2751      // (13.3.3.1) that converts that argument to the corresponding
2752      // parameter of F.
2753      QualType ParamType = Proto->getArgType(ArgIdx);
2754      Candidate.Conversions[ArgIdx]
2755        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
2756                                SuppressUserConversions,
2757                                /*InOverloadResolution=*/true);
2758      if (Candidate.Conversions[ArgIdx].isBad()) {
2759        Candidate.Viable = false;
2760        Candidate.FailureKind = ovl_fail_bad_conversion;
2761        break;
2762      }
2763    } else {
2764      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2765      // argument for which there is no corresponding parameter is
2766      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2767      Candidate.Conversions[ArgIdx].setEllipsis();
2768    }
2769  }
2770}
2771
2772/// \brief Add all of the function declarations in the given function set to
2773/// the overload canddiate set.
2774void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
2775                                 Expr **Args, unsigned NumArgs,
2776                                 OverloadCandidateSet& CandidateSet,
2777                                 bool SuppressUserConversions) {
2778  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
2779    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
2780    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2781      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2782        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
2783                           cast<CXXMethodDecl>(FD)->getParent(),
2784                           Args[0]->getType(), Args + 1, NumArgs - 1,
2785                           CandidateSet, SuppressUserConversions);
2786      else
2787        AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
2788                             SuppressUserConversions);
2789    } else {
2790      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
2791      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2792          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2793        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
2794                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
2795                                   /*FIXME: explicit args */ 0,
2796                                   Args[0]->getType(), Args + 1, NumArgs - 1,
2797                                   CandidateSet,
2798                                   SuppressUserConversions);
2799      else
2800        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
2801                                     /*FIXME: explicit args */ 0,
2802                                     Args, NumArgs, CandidateSet,
2803                                     SuppressUserConversions);
2804    }
2805  }
2806}
2807
2808/// AddMethodCandidate - Adds a named decl (which is some kind of
2809/// method) as a method candidate to the given overload set.
2810void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
2811                              QualType ObjectType,
2812                              Expr **Args, unsigned NumArgs,
2813                              OverloadCandidateSet& CandidateSet,
2814                              bool SuppressUserConversions) {
2815  NamedDecl *Decl = FoundDecl.getDecl();
2816  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
2817
2818  if (isa<UsingShadowDecl>(Decl))
2819    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2820
2821  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2822    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2823           "Expected a member function template");
2824    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
2825                               /*ExplicitArgs*/ 0,
2826                               ObjectType, Args, NumArgs,
2827                               CandidateSet,
2828                               SuppressUserConversions);
2829  } else {
2830    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
2831                       ObjectType, Args, NumArgs,
2832                       CandidateSet, SuppressUserConversions);
2833  }
2834}
2835
2836/// AddMethodCandidate - Adds the given C++ member function to the set
2837/// of candidate functions, using the given function call arguments
2838/// and the object argument (@c Object). For example, in a call
2839/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2840/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2841/// allow user-defined conversions via constructors or conversion
2842/// operators.
2843void
2844Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
2845                         CXXRecordDecl *ActingContext, QualType ObjectType,
2846                         Expr **Args, unsigned NumArgs,
2847                         OverloadCandidateSet& CandidateSet,
2848                         bool SuppressUserConversions) {
2849  const FunctionProtoType* Proto
2850    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
2851  assert(Proto && "Methods without a prototype cannot be overloaded");
2852  assert(!isa<CXXConstructorDecl>(Method) &&
2853         "Use AddOverloadCandidate for constructors");
2854
2855  if (!CandidateSet.isNewCandidate(Method))
2856    return;
2857
2858  // Overload resolution is always an unevaluated context.
2859  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2860
2861  // Add this candidate
2862  CandidateSet.push_back(OverloadCandidate());
2863  OverloadCandidate& Candidate = CandidateSet.back();
2864  Candidate.FoundDecl = FoundDecl;
2865  Candidate.Function = Method;
2866  Candidate.IsSurrogate = false;
2867  Candidate.IgnoreObjectArgument = false;
2868
2869  unsigned NumArgsInProto = Proto->getNumArgs();
2870
2871  // (C++ 13.3.2p2): A candidate function having fewer than m
2872  // parameters is viable only if it has an ellipsis in its parameter
2873  // list (8.3.5).
2874  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2875    Candidate.Viable = false;
2876    Candidate.FailureKind = ovl_fail_too_many_arguments;
2877    return;
2878  }
2879
2880  // (C++ 13.3.2p2): A candidate function having more than m parameters
2881  // is viable only if the (m+1)st parameter has a default argument
2882  // (8.3.6). For the purposes of overload resolution, the
2883  // parameter list is truncated on the right, so that there are
2884  // exactly m parameters.
2885  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2886  if (NumArgs < MinRequiredArgs) {
2887    // Not enough arguments.
2888    Candidate.Viable = false;
2889    Candidate.FailureKind = ovl_fail_too_few_arguments;
2890    return;
2891  }
2892
2893  Candidate.Viable = true;
2894  Candidate.Conversions.resize(NumArgs + 1);
2895
2896  if (Method->isStatic() || ObjectType.isNull())
2897    // The implicit object argument is ignored.
2898    Candidate.IgnoreObjectArgument = true;
2899  else {
2900    // Determine the implicit conversion sequence for the object
2901    // parameter.
2902    Candidate.Conversions[0]
2903      = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
2904    if (Candidate.Conversions[0].isBad()) {
2905      Candidate.Viable = false;
2906      Candidate.FailureKind = ovl_fail_bad_conversion;
2907      return;
2908    }
2909  }
2910
2911  // Determine the implicit conversion sequences for each of the
2912  // arguments.
2913  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2914    if (ArgIdx < NumArgsInProto) {
2915      // (C++ 13.3.2p3): for F to be a viable function, there shall
2916      // exist for each argument an implicit conversion sequence
2917      // (13.3.3.1) that converts that argument to the corresponding
2918      // parameter of F.
2919      QualType ParamType = Proto->getArgType(ArgIdx);
2920      Candidate.Conversions[ArgIdx + 1]
2921        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
2922                                SuppressUserConversions,
2923                                /*InOverloadResolution=*/true);
2924      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
2925        Candidate.Viable = false;
2926        Candidate.FailureKind = ovl_fail_bad_conversion;
2927        break;
2928      }
2929    } else {
2930      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2931      // argument for which there is no corresponding parameter is
2932      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2933      Candidate.Conversions[ArgIdx + 1].setEllipsis();
2934    }
2935  }
2936}
2937
2938/// \brief Add a C++ member function template as a candidate to the candidate
2939/// set, using template argument deduction to produce an appropriate member
2940/// function template specialization.
2941void
2942Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2943                                 DeclAccessPair FoundDecl,
2944                                 CXXRecordDecl *ActingContext,
2945                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
2946                                 QualType ObjectType,
2947                                 Expr **Args, unsigned NumArgs,
2948                                 OverloadCandidateSet& CandidateSet,
2949                                 bool SuppressUserConversions) {
2950  if (!CandidateSet.isNewCandidate(MethodTmpl))
2951    return;
2952
2953  // C++ [over.match.funcs]p7:
2954  //   In each case where a candidate is a function template, candidate
2955  //   function template specializations are generated using template argument
2956  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2957  //   candidate functions in the usual way.113) A given name can refer to one
2958  //   or more function templates and also to a set of overloaded non-template
2959  //   functions. In such a case, the candidate functions generated from each
2960  //   function template are combined with the set of non-template candidate
2961  //   functions.
2962  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
2963  FunctionDecl *Specialization = 0;
2964  if (TemplateDeductionResult Result
2965      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
2966                                Args, NumArgs, Specialization, Info)) {
2967        // FIXME: Record what happened with template argument deduction, so
2968        // that we can give the user a beautiful diagnostic.
2969        (void)Result;
2970        return;
2971      }
2972
2973  // Add the function template specialization produced by template argument
2974  // deduction as a candidate.
2975  assert(Specialization && "Missing member function template specialization?");
2976  assert(isa<CXXMethodDecl>(Specialization) &&
2977         "Specialization is not a member function?");
2978  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
2979                     ActingContext, ObjectType, Args, NumArgs,
2980                     CandidateSet, SuppressUserConversions);
2981}
2982
2983/// \brief Add a C++ function template specialization as a candidate
2984/// in the candidate set, using template argument deduction to produce
2985/// an appropriate function template specialization.
2986void
2987Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2988                                   DeclAccessPair FoundDecl,
2989                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
2990                                   Expr **Args, unsigned NumArgs,
2991                                   OverloadCandidateSet& CandidateSet,
2992                                   bool SuppressUserConversions) {
2993  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2994    return;
2995
2996  // C++ [over.match.funcs]p7:
2997  //   In each case where a candidate is a function template, candidate
2998  //   function template specializations are generated using template argument
2999  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
3000  //   candidate functions in the usual way.113) A given name can refer to one
3001  //   or more function templates and also to a set of overloaded non-template
3002  //   functions. In such a case, the candidate functions generated from each
3003  //   function template are combined with the set of non-template candidate
3004  //   functions.
3005  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
3006  FunctionDecl *Specialization = 0;
3007  if (TemplateDeductionResult Result
3008        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3009                                  Args, NumArgs, Specialization, Info)) {
3010    CandidateSet.push_back(OverloadCandidate());
3011    OverloadCandidate &Candidate = CandidateSet.back();
3012    Candidate.FoundDecl = FoundDecl;
3013    Candidate.Function = FunctionTemplate->getTemplatedDecl();
3014    Candidate.Viable = false;
3015    Candidate.FailureKind = ovl_fail_bad_deduction;
3016    Candidate.IsSurrogate = false;
3017    Candidate.IgnoreObjectArgument = false;
3018
3019    // TODO: record more information about failed template arguments
3020    Candidate.DeductionFailure.Result = Result;
3021    Candidate.DeductionFailure.TemplateParameter = Info.Param.getOpaqueValue();
3022    return;
3023  }
3024
3025  // Add the function template specialization produced by template argument
3026  // deduction as a candidate.
3027  assert(Specialization && "Missing function template specialization?");
3028  AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
3029                       SuppressUserConversions);
3030}
3031
3032/// AddConversionCandidate - Add a C++ conversion function as a
3033/// candidate in the candidate set (C++ [over.match.conv],
3034/// C++ [over.match.copy]). From is the expression we're converting from,
3035/// and ToType is the type that we're eventually trying to convert to
3036/// (which may or may not be the same type as the type that the
3037/// conversion function produces).
3038void
3039Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
3040                             DeclAccessPair FoundDecl,
3041                             CXXRecordDecl *ActingContext,
3042                             Expr *From, QualType ToType,
3043                             OverloadCandidateSet& CandidateSet) {
3044  assert(!Conversion->getDescribedFunctionTemplate() &&
3045         "Conversion function templates use AddTemplateConversionCandidate");
3046
3047  if (!CandidateSet.isNewCandidate(Conversion))
3048    return;
3049
3050  // Overload resolution is always an unevaluated context.
3051  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3052
3053  // Add this candidate
3054  CandidateSet.push_back(OverloadCandidate());
3055  OverloadCandidate& Candidate = CandidateSet.back();
3056  Candidate.FoundDecl = FoundDecl;
3057  Candidate.Function = Conversion;
3058  Candidate.IsSurrogate = false;
3059  Candidate.IgnoreObjectArgument = false;
3060  Candidate.FinalConversion.setAsIdentityConversion();
3061  Candidate.FinalConversion.setFromType(Conversion->getConversionType());
3062  Candidate.FinalConversion.setAllToTypes(ToType);
3063
3064  // Determine the implicit conversion sequence for the implicit
3065  // object parameter.
3066  Candidate.Viable = true;
3067  Candidate.Conversions.resize(1);
3068  Candidate.Conversions[0]
3069    = TryObjectArgumentInitialization(From->getType(), Conversion,
3070                                      ActingContext);
3071  // Conversion functions to a different type in the base class is visible in
3072  // the derived class.  So, a derived to base conversion should not participate
3073  // in overload resolution.
3074  if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3075    Candidate.Conversions[0].Standard.Second = ICK_Identity;
3076  if (Candidate.Conversions[0].isBad()) {
3077    Candidate.Viable = false;
3078    Candidate.FailureKind = ovl_fail_bad_conversion;
3079    return;
3080  }
3081
3082  // We won't go through a user-define type conversion function to convert a
3083  // derived to base as such conversions are given Conversion Rank. They only
3084  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3085  QualType FromCanon
3086    = Context.getCanonicalType(From->getType().getUnqualifiedType());
3087  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3088  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3089    Candidate.Viable = false;
3090    Candidate.FailureKind = ovl_fail_trivial_conversion;
3091    return;
3092  }
3093
3094
3095  // To determine what the conversion from the result of calling the
3096  // conversion function to the type we're eventually trying to
3097  // convert to (ToType), we need to synthesize a call to the
3098  // conversion function and attempt copy initialization from it. This
3099  // makes sure that we get the right semantics with respect to
3100  // lvalues/rvalues and the type. Fortunately, we can allocate this
3101  // call on the stack and we don't need its arguments to be
3102  // well-formed.
3103  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
3104                            From->getLocStart());
3105  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
3106                                CastExpr::CK_FunctionToPointerDecay,
3107                                &ConversionRef, false);
3108
3109  // Note that it is safe to allocate CallExpr on the stack here because
3110  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3111  // allocator).
3112  CallExpr Call(Context, &ConversionFn, 0, 0,
3113                Conversion->getConversionType().getNonReferenceType(),
3114                From->getLocStart());
3115  ImplicitConversionSequence ICS =
3116    TryCopyInitialization(*this, &Call, ToType,
3117                          /*SuppressUserConversions=*/true,
3118                          /*InOverloadResolution=*/false);
3119
3120  switch (ICS.getKind()) {
3121  case ImplicitConversionSequence::StandardConversion:
3122    Candidate.FinalConversion = ICS.Standard;
3123
3124    // C++ [over.ics.user]p3:
3125    //   If the user-defined conversion is specified by a specialization of a
3126    //   conversion function template, the second standard conversion sequence
3127    //   shall have exact match rank.
3128    if (Conversion->getPrimaryTemplate() &&
3129        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3130      Candidate.Viable = false;
3131      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3132    }
3133
3134    break;
3135
3136  case ImplicitConversionSequence::BadConversion:
3137    Candidate.Viable = false;
3138    Candidate.FailureKind = ovl_fail_bad_final_conversion;
3139    break;
3140
3141  default:
3142    assert(false &&
3143           "Can only end up with a standard conversion sequence or failure");
3144  }
3145}
3146
3147/// \brief Adds a conversion function template specialization
3148/// candidate to the overload set, using template argument deduction
3149/// to deduce the template arguments of the conversion function
3150/// template from the type that we are converting to (C++
3151/// [temp.deduct.conv]).
3152void
3153Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
3154                                     DeclAccessPair FoundDecl,
3155                                     CXXRecordDecl *ActingDC,
3156                                     Expr *From, QualType ToType,
3157                                     OverloadCandidateSet &CandidateSet) {
3158  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3159         "Only conversion function templates permitted here");
3160
3161  if (!CandidateSet.isNewCandidate(FunctionTemplate))
3162    return;
3163
3164  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
3165  CXXConversionDecl *Specialization = 0;
3166  if (TemplateDeductionResult Result
3167        = DeduceTemplateArguments(FunctionTemplate, ToType,
3168                                  Specialization, Info)) {
3169    // FIXME: Record what happened with template argument deduction, so
3170    // that we can give the user a beautiful diagnostic.
3171    (void)Result;
3172    return;
3173  }
3174
3175  // Add the conversion function template specialization produced by
3176  // template argument deduction as a candidate.
3177  assert(Specialization && "Missing function template specialization?");
3178  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
3179                         CandidateSet);
3180}
3181
3182/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3183/// converts the given @c Object to a function pointer via the
3184/// conversion function @c Conversion, and then attempts to call it
3185/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3186/// the type of function that we'll eventually be calling.
3187void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
3188                                 DeclAccessPair FoundDecl,
3189                                 CXXRecordDecl *ActingContext,
3190                                 const FunctionProtoType *Proto,
3191                                 QualType ObjectType,
3192                                 Expr **Args, unsigned NumArgs,
3193                                 OverloadCandidateSet& CandidateSet) {
3194  if (!CandidateSet.isNewCandidate(Conversion))
3195    return;
3196
3197  // Overload resolution is always an unevaluated context.
3198  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3199
3200  CandidateSet.push_back(OverloadCandidate());
3201  OverloadCandidate& Candidate = CandidateSet.back();
3202  Candidate.FoundDecl = FoundDecl;
3203  Candidate.Function = 0;
3204  Candidate.Surrogate = Conversion;
3205  Candidate.Viable = true;
3206  Candidate.IsSurrogate = true;
3207  Candidate.IgnoreObjectArgument = false;
3208  Candidate.Conversions.resize(NumArgs + 1);
3209
3210  // Determine the implicit conversion sequence for the implicit
3211  // object parameter.
3212  ImplicitConversionSequence ObjectInit
3213    = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
3214  if (ObjectInit.isBad()) {
3215    Candidate.Viable = false;
3216    Candidate.FailureKind = ovl_fail_bad_conversion;
3217    Candidate.Conversions[0] = ObjectInit;
3218    return;
3219  }
3220
3221  // The first conversion is actually a user-defined conversion whose
3222  // first conversion is ObjectInit's standard conversion (which is
3223  // effectively a reference binding). Record it as such.
3224  Candidate.Conversions[0].setUserDefined();
3225  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
3226  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
3227  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
3228  Candidate.Conversions[0].UserDefined.After
3229    = Candidate.Conversions[0].UserDefined.Before;
3230  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3231
3232  // Find the
3233  unsigned NumArgsInProto = Proto->getNumArgs();
3234
3235  // (C++ 13.3.2p2): A candidate function having fewer than m
3236  // parameters is viable only if it has an ellipsis in its parameter
3237  // list (8.3.5).
3238  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3239    Candidate.Viable = false;
3240    Candidate.FailureKind = ovl_fail_too_many_arguments;
3241    return;
3242  }
3243
3244  // Function types don't have any default arguments, so just check if
3245  // we have enough arguments.
3246  if (NumArgs < NumArgsInProto) {
3247    // Not enough arguments.
3248    Candidate.Viable = false;
3249    Candidate.FailureKind = ovl_fail_too_few_arguments;
3250    return;
3251  }
3252
3253  // Determine the implicit conversion sequences for each of the
3254  // arguments.
3255  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3256    if (ArgIdx < NumArgsInProto) {
3257      // (C++ 13.3.2p3): for F to be a viable function, there shall
3258      // exist for each argument an implicit conversion sequence
3259      // (13.3.3.1) that converts that argument to the corresponding
3260      // parameter of F.
3261      QualType ParamType = Proto->getArgType(ArgIdx);
3262      Candidate.Conversions[ArgIdx + 1]
3263        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
3264                                /*SuppressUserConversions=*/false,
3265                                /*InOverloadResolution=*/false);
3266      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
3267        Candidate.Viable = false;
3268        Candidate.FailureKind = ovl_fail_bad_conversion;
3269        break;
3270      }
3271    } else {
3272      // (C++ 13.3.2p2): For the purposes of overload resolution, any
3273      // argument for which there is no corresponding parameter is
3274      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
3275      Candidate.Conversions[ArgIdx + 1].setEllipsis();
3276    }
3277  }
3278}
3279
3280// FIXME: This will eventually be removed, once we've migrated all of the
3281// operator overloading logic over to the scheme used by binary operators, which
3282// works for template instantiation.
3283void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
3284                                 SourceLocation OpLoc,
3285                                 Expr **Args, unsigned NumArgs,
3286                                 OverloadCandidateSet& CandidateSet,
3287                                 SourceRange OpRange) {
3288  UnresolvedSet<16> Fns;
3289
3290  QualType T1 = Args[0]->getType();
3291  QualType T2;
3292  if (NumArgs > 1)
3293    T2 = Args[1]->getType();
3294
3295  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3296  if (S)
3297    LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
3298  AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
3299  AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3300                                       CandidateSet);
3301  AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
3302  AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
3303}
3304
3305/// \brief Add overload candidates for overloaded operators that are
3306/// member functions.
3307///
3308/// Add the overloaded operator candidates that are member functions
3309/// for the operator Op that was used in an operator expression such
3310/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3311/// CandidateSet will store the added overload candidates. (C++
3312/// [over.match.oper]).
3313void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3314                                       SourceLocation OpLoc,
3315                                       Expr **Args, unsigned NumArgs,
3316                                       OverloadCandidateSet& CandidateSet,
3317                                       SourceRange OpRange) {
3318  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3319
3320  // C++ [over.match.oper]p3:
3321  //   For a unary operator @ with an operand of a type whose
3322  //   cv-unqualified version is T1, and for a binary operator @ with
3323  //   a left operand of a type whose cv-unqualified version is T1 and
3324  //   a right operand of a type whose cv-unqualified version is T2,
3325  //   three sets of candidate functions, designated member
3326  //   candidates, non-member candidates and built-in candidates, are
3327  //   constructed as follows:
3328  QualType T1 = Args[0]->getType();
3329  QualType T2;
3330  if (NumArgs > 1)
3331    T2 = Args[1]->getType();
3332
3333  //     -- If T1 is a class type, the set of member candidates is the
3334  //        result of the qualified lookup of T1::operator@
3335  //        (13.3.1.1.1); otherwise, the set of member candidates is
3336  //        empty.
3337  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
3338    // Complete the type if it can be completed. Otherwise, we're done.
3339    if (RequireCompleteType(OpLoc, T1, PDiag()))
3340      return;
3341
3342    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3343    LookupQualifiedName(Operators, T1Rec->getDecl());
3344    Operators.suppressDiagnostics();
3345
3346    for (LookupResult::iterator Oper = Operators.begin(),
3347                             OperEnd = Operators.end();
3348         Oper != OperEnd;
3349         ++Oper)
3350      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
3351                         Args + 1, NumArgs - 1, CandidateSet,
3352                         /* SuppressUserConversions = */ false);
3353  }
3354}
3355
3356/// AddBuiltinCandidate - Add a candidate for a built-in
3357/// operator. ResultTy and ParamTys are the result and parameter types
3358/// of the built-in candidate, respectively. Args and NumArgs are the
3359/// arguments being passed to the candidate. IsAssignmentOperator
3360/// should be true when this built-in candidate is an assignment
3361/// operator. NumContextualBoolArguments is the number of arguments
3362/// (at the beginning of the argument list) that will be contextually
3363/// converted to bool.
3364void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
3365                               Expr **Args, unsigned NumArgs,
3366                               OverloadCandidateSet& CandidateSet,
3367                               bool IsAssignmentOperator,
3368                               unsigned NumContextualBoolArguments) {
3369  // Overload resolution is always an unevaluated context.
3370  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3371
3372  // Add this candidate
3373  CandidateSet.push_back(OverloadCandidate());
3374  OverloadCandidate& Candidate = CandidateSet.back();
3375  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
3376  Candidate.Function = 0;
3377  Candidate.IsSurrogate = false;
3378  Candidate.IgnoreObjectArgument = false;
3379  Candidate.BuiltinTypes.ResultTy = ResultTy;
3380  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3381    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3382
3383  // Determine the implicit conversion sequences for each of the
3384  // arguments.
3385  Candidate.Viable = true;
3386  Candidate.Conversions.resize(NumArgs);
3387  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3388    // C++ [over.match.oper]p4:
3389    //   For the built-in assignment operators, conversions of the
3390    //   left operand are restricted as follows:
3391    //     -- no temporaries are introduced to hold the left operand, and
3392    //     -- no user-defined conversions are applied to the left
3393    //        operand to achieve a type match with the left-most
3394    //        parameter of a built-in candidate.
3395    //
3396    // We block these conversions by turning off user-defined
3397    // conversions, since that is the only way that initialization of
3398    // a reference to a non-class type can occur from something that
3399    // is not of the same type.
3400    if (ArgIdx < NumContextualBoolArguments) {
3401      assert(ParamTys[ArgIdx] == Context.BoolTy &&
3402             "Contextual conversion to bool requires bool type");
3403      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3404    } else {
3405      Candidate.Conversions[ArgIdx]
3406        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
3407                                ArgIdx == 0 && IsAssignmentOperator,
3408                                /*InOverloadResolution=*/false);
3409    }
3410    if (Candidate.Conversions[ArgIdx].isBad()) {
3411      Candidate.Viable = false;
3412      Candidate.FailureKind = ovl_fail_bad_conversion;
3413      break;
3414    }
3415  }
3416}
3417
3418/// BuiltinCandidateTypeSet - A set of types that will be used for the
3419/// candidate operator functions for built-in operators (C++
3420/// [over.built]). The types are separated into pointer types and
3421/// enumeration types.
3422class BuiltinCandidateTypeSet  {
3423  /// TypeSet - A set of types.
3424  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
3425
3426  /// PointerTypes - The set of pointer types that will be used in the
3427  /// built-in candidates.
3428  TypeSet PointerTypes;
3429
3430  /// MemberPointerTypes - The set of member pointer types that will be
3431  /// used in the built-in candidates.
3432  TypeSet MemberPointerTypes;
3433
3434  /// EnumerationTypes - The set of enumeration types that will be
3435  /// used in the built-in candidates.
3436  TypeSet EnumerationTypes;
3437
3438  /// Sema - The semantic analysis instance where we are building the
3439  /// candidate type set.
3440  Sema &SemaRef;
3441
3442  /// Context - The AST context in which we will build the type sets.
3443  ASTContext &Context;
3444
3445  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3446                                               const Qualifiers &VisibleQuals);
3447  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
3448
3449public:
3450  /// iterator - Iterates through the types that are part of the set.
3451  typedef TypeSet::iterator iterator;
3452
3453  BuiltinCandidateTypeSet(Sema &SemaRef)
3454    : SemaRef(SemaRef), Context(SemaRef.Context) { }
3455
3456  void AddTypesConvertedFrom(QualType Ty,
3457                             SourceLocation Loc,
3458                             bool AllowUserConversions,
3459                             bool AllowExplicitConversions,
3460                             const Qualifiers &VisibleTypeConversionsQuals);
3461
3462  /// pointer_begin - First pointer type found;
3463  iterator pointer_begin() { return PointerTypes.begin(); }
3464
3465  /// pointer_end - Past the last pointer type found;
3466  iterator pointer_end() { return PointerTypes.end(); }
3467
3468  /// member_pointer_begin - First member pointer type found;
3469  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3470
3471  /// member_pointer_end - Past the last member pointer type found;
3472  iterator member_pointer_end() { return MemberPointerTypes.end(); }
3473
3474  /// enumeration_begin - First enumeration type found;
3475  iterator enumeration_begin() { return EnumerationTypes.begin(); }
3476
3477  /// enumeration_end - Past the last enumeration type found;
3478  iterator enumeration_end() { return EnumerationTypes.end(); }
3479};
3480
3481/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
3482/// the set of pointer types along with any more-qualified variants of
3483/// that type. For example, if @p Ty is "int const *", this routine
3484/// will add "int const *", "int const volatile *", "int const
3485/// restrict *", and "int const volatile restrict *" to the set of
3486/// pointer types. Returns true if the add of @p Ty itself succeeded,
3487/// false otherwise.
3488///
3489/// FIXME: what to do about extended qualifiers?
3490bool
3491BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3492                                             const Qualifiers &VisibleQuals) {
3493
3494  // Insert this type.
3495  if (!PointerTypes.insert(Ty))
3496    return false;
3497
3498  const PointerType *PointerTy = Ty->getAs<PointerType>();
3499  assert(PointerTy && "type was not a pointer type!");
3500
3501  QualType PointeeTy = PointerTy->getPointeeType();
3502  // Don't add qualified variants of arrays. For one, they're not allowed
3503  // (the qualifier would sink to the element type), and for another, the
3504  // only overload situation where it matters is subscript or pointer +- int,
3505  // and those shouldn't have qualifier variants anyway.
3506  if (PointeeTy->isArrayType())
3507    return true;
3508  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3509  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
3510    BaseCVR = Array->getElementType().getCVRQualifiers();
3511  bool hasVolatile = VisibleQuals.hasVolatile();
3512  bool hasRestrict = VisibleQuals.hasRestrict();
3513
3514  // Iterate through all strict supersets of BaseCVR.
3515  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3516    if ((CVR | BaseCVR) != CVR) continue;
3517    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3518    // in the types.
3519    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3520    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
3521    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3522    PointerTypes.insert(Context.getPointerType(QPointeeTy));
3523  }
3524
3525  return true;
3526}
3527
3528/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3529/// to the set of pointer types along with any more-qualified variants of
3530/// that type. For example, if @p Ty is "int const *", this routine
3531/// will add "int const *", "int const volatile *", "int const
3532/// restrict *", and "int const volatile restrict *" to the set of
3533/// pointer types. Returns true if the add of @p Ty itself succeeded,
3534/// false otherwise.
3535///
3536/// FIXME: what to do about extended qualifiers?
3537bool
3538BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3539    QualType Ty) {
3540  // Insert this type.
3541  if (!MemberPointerTypes.insert(Ty))
3542    return false;
3543
3544  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3545  assert(PointerTy && "type was not a member pointer type!");
3546
3547  QualType PointeeTy = PointerTy->getPointeeType();
3548  // Don't add qualified variants of arrays. For one, they're not allowed
3549  // (the qualifier would sink to the element type), and for another, the
3550  // only overload situation where it matters is subscript or pointer +- int,
3551  // and those shouldn't have qualifier variants anyway.
3552  if (PointeeTy->isArrayType())
3553    return true;
3554  const Type *ClassTy = PointerTy->getClass();
3555
3556  // Iterate through all strict supersets of the pointee type's CVR
3557  // qualifiers.
3558  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3559  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3560    if ((CVR | BaseCVR) != CVR) continue;
3561
3562    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3563    MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
3564  }
3565
3566  return true;
3567}
3568
3569/// AddTypesConvertedFrom - Add each of the types to which the type @p
3570/// Ty can be implicit converted to the given set of @p Types. We're
3571/// primarily interested in pointer types and enumeration types. We also
3572/// take member pointer types, for the conditional operator.
3573/// AllowUserConversions is true if we should look at the conversion
3574/// functions of a class type, and AllowExplicitConversions if we
3575/// should also include the explicit conversion functions of a class
3576/// type.
3577void
3578BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
3579                                               SourceLocation Loc,
3580                                               bool AllowUserConversions,
3581                                               bool AllowExplicitConversions,
3582                                               const Qualifiers &VisibleQuals) {
3583  // Only deal with canonical types.
3584  Ty = Context.getCanonicalType(Ty);
3585
3586  // Look through reference types; they aren't part of the type of an
3587  // expression for the purposes of conversions.
3588  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
3589    Ty = RefTy->getPointeeType();
3590
3591  // We don't care about qualifiers on the type.
3592  Ty = Ty.getLocalUnqualifiedType();
3593
3594  // If we're dealing with an array type, decay to the pointer.
3595  if (Ty->isArrayType())
3596    Ty = SemaRef.Context.getArrayDecayedType(Ty);
3597
3598  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
3599    QualType PointeeTy = PointerTy->getPointeeType();
3600
3601    // Insert our type, and its more-qualified variants, into the set
3602    // of types.
3603    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
3604      return;
3605  } else if (Ty->isMemberPointerType()) {
3606    // Member pointers are far easier, since the pointee can't be converted.
3607    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3608      return;
3609  } else if (Ty->isEnumeralType()) {
3610    EnumerationTypes.insert(Ty);
3611  } else if (AllowUserConversions) {
3612    if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
3613      if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
3614        // No conversion functions in incomplete types.
3615        return;
3616      }
3617
3618      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3619      const UnresolvedSetImpl *Conversions
3620        = ClassDecl->getVisibleConversionFunctions();
3621      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3622             E = Conversions->end(); I != E; ++I) {
3623        NamedDecl *D = I.getDecl();
3624        if (isa<UsingShadowDecl>(D))
3625          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3626
3627        // Skip conversion function templates; they don't tell us anything
3628        // about which builtin types we can convert to.
3629        if (isa<FunctionTemplateDecl>(D))
3630          continue;
3631
3632        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
3633        if (AllowExplicitConversions || !Conv->isExplicit()) {
3634          AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
3635                                VisibleQuals);
3636        }
3637      }
3638    }
3639  }
3640}
3641
3642/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3643/// the volatile- and non-volatile-qualified assignment operators for the
3644/// given type to the candidate set.
3645static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3646                                                   QualType T,
3647                                                   Expr **Args,
3648                                                   unsigned NumArgs,
3649                                    OverloadCandidateSet &CandidateSet) {
3650  QualType ParamTypes[2];
3651
3652  // T& operator=(T&, T)
3653  ParamTypes[0] = S.Context.getLValueReferenceType(T);
3654  ParamTypes[1] = T;
3655  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3656                        /*IsAssignmentOperator=*/true);
3657
3658  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3659    // volatile T& operator=(volatile T&, T)
3660    ParamTypes[0]
3661      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
3662    ParamTypes[1] = T;
3663    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3664                          /*IsAssignmentOperator=*/true);
3665  }
3666}
3667
3668/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3669/// if any, found in visible type conversion functions found in ArgExpr's type.
3670static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3671    Qualifiers VRQuals;
3672    const RecordType *TyRec;
3673    if (const MemberPointerType *RHSMPType =
3674        ArgExpr->getType()->getAs<MemberPointerType>())
3675      TyRec = cast<RecordType>(RHSMPType->getClass());
3676    else
3677      TyRec = ArgExpr->getType()->getAs<RecordType>();
3678    if (!TyRec) {
3679      // Just to be safe, assume the worst case.
3680      VRQuals.addVolatile();
3681      VRQuals.addRestrict();
3682      return VRQuals;
3683    }
3684
3685    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3686    if (!ClassDecl->hasDefinition())
3687      return VRQuals;
3688
3689    const UnresolvedSetImpl *Conversions =
3690      ClassDecl->getVisibleConversionFunctions();
3691
3692    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3693           E = Conversions->end(); I != E; ++I) {
3694      NamedDecl *D = I.getDecl();
3695      if (isa<UsingShadowDecl>(D))
3696        D = cast<UsingShadowDecl>(D)->getTargetDecl();
3697      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
3698        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3699        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3700          CanTy = ResTypeRef->getPointeeType();
3701        // Need to go down the pointer/mempointer chain and add qualifiers
3702        // as see them.
3703        bool done = false;
3704        while (!done) {
3705          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3706            CanTy = ResTypePtr->getPointeeType();
3707          else if (const MemberPointerType *ResTypeMPtr =
3708                CanTy->getAs<MemberPointerType>())
3709            CanTy = ResTypeMPtr->getPointeeType();
3710          else
3711            done = true;
3712          if (CanTy.isVolatileQualified())
3713            VRQuals.addVolatile();
3714          if (CanTy.isRestrictQualified())
3715            VRQuals.addRestrict();
3716          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3717            return VRQuals;
3718        }
3719      }
3720    }
3721    return VRQuals;
3722}
3723
3724/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3725/// operator overloads to the candidate set (C++ [over.built]), based
3726/// on the operator @p Op and the arguments given. For example, if the
3727/// operator is a binary '+', this routine might add "int
3728/// operator+(int, int)" to cover integer addition.
3729void
3730Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3731                                   SourceLocation OpLoc,
3732                                   Expr **Args, unsigned NumArgs,
3733                                   OverloadCandidateSet& CandidateSet) {
3734  // The set of "promoted arithmetic types", which are the arithmetic
3735  // types are that preserved by promotion (C++ [over.built]p2). Note
3736  // that the first few of these types are the promoted integral
3737  // types; these types need to be first.
3738  // FIXME: What about complex?
3739  const unsigned FirstIntegralType = 0;
3740  const unsigned LastIntegralType = 13;
3741  const unsigned FirstPromotedIntegralType = 7,
3742                 LastPromotedIntegralType = 13;
3743  const unsigned FirstPromotedArithmeticType = 7,
3744                 LastPromotedArithmeticType = 16;
3745  const unsigned NumArithmeticTypes = 16;
3746  QualType ArithmeticTypes[NumArithmeticTypes] = {
3747    Context.BoolTy, Context.CharTy, Context.WCharTy,
3748// FIXME:   Context.Char16Ty, Context.Char32Ty,
3749    Context.SignedCharTy, Context.ShortTy,
3750    Context.UnsignedCharTy, Context.UnsignedShortTy,
3751    Context.IntTy, Context.LongTy, Context.LongLongTy,
3752    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3753    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3754  };
3755  assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3756         "Invalid first promoted integral type");
3757  assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3758           == Context.UnsignedLongLongTy &&
3759         "Invalid last promoted integral type");
3760  assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3761         "Invalid first promoted arithmetic type");
3762  assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3763            == Context.LongDoubleTy &&
3764         "Invalid last promoted arithmetic type");
3765
3766  // Find all of the types that the arguments can convert to, but only
3767  // if the operator we're looking at has built-in operator candidates
3768  // that make use of these types.
3769  Qualifiers VisibleTypeConversionsQuals;
3770  VisibleTypeConversionsQuals.addConst();
3771  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3772    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3773
3774  BuiltinCandidateTypeSet CandidateTypes(*this);
3775  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3776      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3777      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3778      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3779      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3780      (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3781    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3782      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3783                                           OpLoc,
3784                                           true,
3785                                           (Op == OO_Exclaim ||
3786                                            Op == OO_AmpAmp ||
3787                                            Op == OO_PipePipe),
3788                                           VisibleTypeConversionsQuals);
3789  }
3790
3791  bool isComparison = false;
3792  switch (Op) {
3793  case OO_None:
3794  case NUM_OVERLOADED_OPERATORS:
3795    assert(false && "Expected an overloaded operator");
3796    break;
3797
3798  case OO_Star: // '*' is either unary or binary
3799    if (NumArgs == 1)
3800      goto UnaryStar;
3801    else
3802      goto BinaryStar;
3803    break;
3804
3805  case OO_Plus: // '+' is either unary or binary
3806    if (NumArgs == 1)
3807      goto UnaryPlus;
3808    else
3809      goto BinaryPlus;
3810    break;
3811
3812  case OO_Minus: // '-' is either unary or binary
3813    if (NumArgs == 1)
3814      goto UnaryMinus;
3815    else
3816      goto BinaryMinus;
3817    break;
3818
3819  case OO_Amp: // '&' is either unary or binary
3820    if (NumArgs == 1)
3821      goto UnaryAmp;
3822    else
3823      goto BinaryAmp;
3824
3825  case OO_PlusPlus:
3826  case OO_MinusMinus:
3827    // C++ [over.built]p3:
3828    //
3829    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
3830    //   is either volatile or empty, there exist candidate operator
3831    //   functions of the form
3832    //
3833    //       VQ T&      operator++(VQ T&);
3834    //       T          operator++(VQ T&, int);
3835    //
3836    // C++ [over.built]p4:
3837    //
3838    //   For every pair (T, VQ), where T is an arithmetic type other
3839    //   than bool, and VQ is either volatile or empty, there exist
3840    //   candidate operator functions of the form
3841    //
3842    //       VQ T&      operator--(VQ T&);
3843    //       T          operator--(VQ T&, int);
3844    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3845         Arith < NumArithmeticTypes; ++Arith) {
3846      QualType ArithTy = ArithmeticTypes[Arith];
3847      QualType ParamTypes[2]
3848        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3849
3850      // Non-volatile version.
3851      if (NumArgs == 1)
3852        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3853      else
3854        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3855      // heuristic to reduce number of builtin candidates in the set.
3856      // Add volatile version only if there are conversions to a volatile type.
3857      if (VisibleTypeConversionsQuals.hasVolatile()) {
3858        // Volatile version
3859        ParamTypes[0]
3860          = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3861        if (NumArgs == 1)
3862          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3863        else
3864          AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3865      }
3866    }
3867
3868    // C++ [over.built]p5:
3869    //
3870    //   For every pair (T, VQ), where T is a cv-qualified or
3871    //   cv-unqualified object type, and VQ is either volatile or
3872    //   empty, there exist candidate operator functions of the form
3873    //
3874    //       T*VQ&      operator++(T*VQ&);
3875    //       T*VQ&      operator--(T*VQ&);
3876    //       T*         operator++(T*VQ&, int);
3877    //       T*         operator--(T*VQ&, int);
3878    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3879         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3880      // Skip pointer types that aren't pointers to object types.
3881      if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3882        continue;
3883
3884      QualType ParamTypes[2] = {
3885        Context.getLValueReferenceType(*Ptr), Context.IntTy
3886      };
3887
3888      // Without volatile
3889      if (NumArgs == 1)
3890        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3891      else
3892        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3893
3894      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3895          VisibleTypeConversionsQuals.hasVolatile()) {
3896        // With volatile
3897        ParamTypes[0]
3898          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3899        if (NumArgs == 1)
3900          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3901        else
3902          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3903      }
3904    }
3905    break;
3906
3907  UnaryStar:
3908    // C++ [over.built]p6:
3909    //   For every cv-qualified or cv-unqualified object type T, there
3910    //   exist candidate operator functions of the form
3911    //
3912    //       T&         operator*(T*);
3913    //
3914    // C++ [over.built]p7:
3915    //   For every function type T, there exist candidate operator
3916    //   functions of the form
3917    //       T&         operator*(T*);
3918    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3919         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3920      QualType ParamTy = *Ptr;
3921      QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3922      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3923                          &ParamTy, Args, 1, CandidateSet);
3924    }
3925    break;
3926
3927  UnaryPlus:
3928    // C++ [over.built]p8:
3929    //   For every type T, there exist candidate operator functions of
3930    //   the form
3931    //
3932    //       T*         operator+(T*);
3933    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3934         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3935      QualType ParamTy = *Ptr;
3936      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3937    }
3938
3939    // Fall through
3940
3941  UnaryMinus:
3942    // C++ [over.built]p9:
3943    //  For every promoted arithmetic type T, there exist candidate
3944    //  operator functions of the form
3945    //
3946    //       T         operator+(T);
3947    //       T         operator-(T);
3948    for (unsigned Arith = FirstPromotedArithmeticType;
3949         Arith < LastPromotedArithmeticType; ++Arith) {
3950      QualType ArithTy = ArithmeticTypes[Arith];
3951      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3952    }
3953    break;
3954
3955  case OO_Tilde:
3956    // C++ [over.built]p10:
3957    //   For every promoted integral type T, there exist candidate
3958    //   operator functions of the form
3959    //
3960    //        T         operator~(T);
3961    for (unsigned Int = FirstPromotedIntegralType;
3962         Int < LastPromotedIntegralType; ++Int) {
3963      QualType IntTy = ArithmeticTypes[Int];
3964      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3965    }
3966    break;
3967
3968  case OO_New:
3969  case OO_Delete:
3970  case OO_Array_New:
3971  case OO_Array_Delete:
3972  case OO_Call:
3973    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3974    break;
3975
3976  case OO_Comma:
3977  UnaryAmp:
3978  case OO_Arrow:
3979    // C++ [over.match.oper]p3:
3980    //   -- For the operator ',', the unary operator '&', or the
3981    //      operator '->', the built-in candidates set is empty.
3982    break;
3983
3984  case OO_EqualEqual:
3985  case OO_ExclaimEqual:
3986    // C++ [over.match.oper]p16:
3987    //   For every pointer to member type T, there exist candidate operator
3988    //   functions of the form
3989    //
3990    //        bool operator==(T,T);
3991    //        bool operator!=(T,T);
3992    for (BuiltinCandidateTypeSet::iterator
3993           MemPtr = CandidateTypes.member_pointer_begin(),
3994           MemPtrEnd = CandidateTypes.member_pointer_end();
3995         MemPtr != MemPtrEnd;
3996         ++MemPtr) {
3997      QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3998      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3999    }
4000
4001    // Fall through
4002
4003  case OO_Less:
4004  case OO_Greater:
4005  case OO_LessEqual:
4006  case OO_GreaterEqual:
4007    // C++ [over.built]p15:
4008    //
4009    //   For every pointer or enumeration type T, there exist
4010    //   candidate operator functions of the form
4011    //
4012    //        bool       operator<(T, T);
4013    //        bool       operator>(T, T);
4014    //        bool       operator<=(T, T);
4015    //        bool       operator>=(T, T);
4016    //        bool       operator==(T, T);
4017    //        bool       operator!=(T, T);
4018    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4019         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4020      QualType ParamTypes[2] = { *Ptr, *Ptr };
4021      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4022    }
4023    for (BuiltinCandidateTypeSet::iterator Enum
4024           = CandidateTypes.enumeration_begin();
4025         Enum != CandidateTypes.enumeration_end(); ++Enum) {
4026      QualType ParamTypes[2] = { *Enum, *Enum };
4027      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4028    }
4029
4030    // Fall through.
4031    isComparison = true;
4032
4033  BinaryPlus:
4034  BinaryMinus:
4035    if (!isComparison) {
4036      // We didn't fall through, so we must have OO_Plus or OO_Minus.
4037
4038      // C++ [over.built]p13:
4039      //
4040      //   For every cv-qualified or cv-unqualified object type T
4041      //   there exist candidate operator functions of the form
4042      //
4043      //      T*         operator+(T*, ptrdiff_t);
4044      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
4045      //      T*         operator-(T*, ptrdiff_t);
4046      //      T*         operator+(ptrdiff_t, T*);
4047      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
4048      //
4049      // C++ [over.built]p14:
4050      //
4051      //   For every T, where T is a pointer to object type, there
4052      //   exist candidate operator functions of the form
4053      //
4054      //      ptrdiff_t  operator-(T, T);
4055      for (BuiltinCandidateTypeSet::iterator Ptr
4056             = CandidateTypes.pointer_begin();
4057           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4058        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4059
4060        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4061        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4062
4063        if (Op == OO_Plus) {
4064          // T* operator+(ptrdiff_t, T*);
4065          ParamTypes[0] = ParamTypes[1];
4066          ParamTypes[1] = *Ptr;
4067          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4068        } else {
4069          // ptrdiff_t operator-(T, T);
4070          ParamTypes[1] = *Ptr;
4071          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4072                              Args, 2, CandidateSet);
4073        }
4074      }
4075    }
4076    // Fall through
4077
4078  case OO_Slash:
4079  BinaryStar:
4080  Conditional:
4081    // C++ [over.built]p12:
4082    //
4083    //   For every pair of promoted arithmetic types L and R, there
4084    //   exist candidate operator functions of the form
4085    //
4086    //        LR         operator*(L, R);
4087    //        LR         operator/(L, R);
4088    //        LR         operator+(L, R);
4089    //        LR         operator-(L, R);
4090    //        bool       operator<(L, R);
4091    //        bool       operator>(L, R);
4092    //        bool       operator<=(L, R);
4093    //        bool       operator>=(L, R);
4094    //        bool       operator==(L, R);
4095    //        bool       operator!=(L, R);
4096    //
4097    //   where LR is the result of the usual arithmetic conversions
4098    //   between types L and R.
4099    //
4100    // C++ [over.built]p24:
4101    //
4102    //   For every pair of promoted arithmetic types L and R, there exist
4103    //   candidate operator functions of the form
4104    //
4105    //        LR       operator?(bool, L, R);
4106    //
4107    //   where LR is the result of the usual arithmetic conversions
4108    //   between types L and R.
4109    // Our candidates ignore the first parameter.
4110    for (unsigned Left = FirstPromotedArithmeticType;
4111         Left < LastPromotedArithmeticType; ++Left) {
4112      for (unsigned Right = FirstPromotedArithmeticType;
4113           Right < LastPromotedArithmeticType; ++Right) {
4114        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4115        QualType Result
4116          = isComparison
4117          ? Context.BoolTy
4118          : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
4119        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4120      }
4121    }
4122    break;
4123
4124  case OO_Percent:
4125  BinaryAmp:
4126  case OO_Caret:
4127  case OO_Pipe:
4128  case OO_LessLess:
4129  case OO_GreaterGreater:
4130    // C++ [over.built]p17:
4131    //
4132    //   For every pair of promoted integral types L and R, there
4133    //   exist candidate operator functions of the form
4134    //
4135    //      LR         operator%(L, R);
4136    //      LR         operator&(L, R);
4137    //      LR         operator^(L, R);
4138    //      LR         operator|(L, R);
4139    //      L          operator<<(L, R);
4140    //      L          operator>>(L, R);
4141    //
4142    //   where LR is the result of the usual arithmetic conversions
4143    //   between types L and R.
4144    for (unsigned Left = FirstPromotedIntegralType;
4145         Left < LastPromotedIntegralType; ++Left) {
4146      for (unsigned Right = FirstPromotedIntegralType;
4147           Right < LastPromotedIntegralType; ++Right) {
4148        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4149        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4150            ? LandR[0]
4151            : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
4152        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4153      }
4154    }
4155    break;
4156
4157  case OO_Equal:
4158    // C++ [over.built]p20:
4159    //
4160    //   For every pair (T, VQ), where T is an enumeration or
4161    //   pointer to member type and VQ is either volatile or
4162    //   empty, there exist candidate operator functions of the form
4163    //
4164    //        VQ T&      operator=(VQ T&, T);
4165    for (BuiltinCandidateTypeSet::iterator
4166           Enum = CandidateTypes.enumeration_begin(),
4167           EnumEnd = CandidateTypes.enumeration_end();
4168         Enum != EnumEnd; ++Enum)
4169      AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
4170                                             CandidateSet);
4171    for (BuiltinCandidateTypeSet::iterator
4172           MemPtr = CandidateTypes.member_pointer_begin(),
4173         MemPtrEnd = CandidateTypes.member_pointer_end();
4174         MemPtr != MemPtrEnd; ++MemPtr)
4175      AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
4176                                             CandidateSet);
4177      // Fall through.
4178
4179  case OO_PlusEqual:
4180  case OO_MinusEqual:
4181    // C++ [over.built]p19:
4182    //
4183    //   For every pair (T, VQ), where T is any type and VQ is either
4184    //   volatile or empty, there exist candidate operator functions
4185    //   of the form
4186    //
4187    //        T*VQ&      operator=(T*VQ&, T*);
4188    //
4189    // C++ [over.built]p21:
4190    //
4191    //   For every pair (T, VQ), where T is a cv-qualified or
4192    //   cv-unqualified object type and VQ is either volatile or
4193    //   empty, there exist candidate operator functions of the form
4194    //
4195    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
4196    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
4197    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4198         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4199      QualType ParamTypes[2];
4200      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4201
4202      // non-volatile version
4203      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
4204      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4205                          /*IsAssigmentOperator=*/Op == OO_Equal);
4206
4207      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4208          VisibleTypeConversionsQuals.hasVolatile()) {
4209        // volatile version
4210        ParamTypes[0]
4211          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
4212        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4213                            /*IsAssigmentOperator=*/Op == OO_Equal);
4214      }
4215    }
4216    // Fall through.
4217
4218  case OO_StarEqual:
4219  case OO_SlashEqual:
4220    // C++ [over.built]p18:
4221    //
4222    //   For every triple (L, VQ, R), where L is an arithmetic type,
4223    //   VQ is either volatile or empty, and R is a promoted
4224    //   arithmetic type, there exist candidate operator functions of
4225    //   the form
4226    //
4227    //        VQ L&      operator=(VQ L&, R);
4228    //        VQ L&      operator*=(VQ L&, R);
4229    //        VQ L&      operator/=(VQ L&, R);
4230    //        VQ L&      operator+=(VQ L&, R);
4231    //        VQ L&      operator-=(VQ L&, R);
4232    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
4233      for (unsigned Right = FirstPromotedArithmeticType;
4234           Right < LastPromotedArithmeticType; ++Right) {
4235        QualType ParamTypes[2];
4236        ParamTypes[1] = ArithmeticTypes[Right];
4237
4238        // Add this built-in operator as a candidate (VQ is empty).
4239        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
4240        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4241                            /*IsAssigmentOperator=*/Op == OO_Equal);
4242
4243        // Add this built-in operator as a candidate (VQ is 'volatile').
4244        if (VisibleTypeConversionsQuals.hasVolatile()) {
4245          ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4246          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4247          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4248                              /*IsAssigmentOperator=*/Op == OO_Equal);
4249        }
4250      }
4251    }
4252    break;
4253
4254  case OO_PercentEqual:
4255  case OO_LessLessEqual:
4256  case OO_GreaterGreaterEqual:
4257  case OO_AmpEqual:
4258  case OO_CaretEqual:
4259  case OO_PipeEqual:
4260    // C++ [over.built]p22:
4261    //
4262    //   For every triple (L, VQ, R), where L is an integral type, VQ
4263    //   is either volatile or empty, and R is a promoted integral
4264    //   type, there exist candidate operator functions of the form
4265    //
4266    //        VQ L&       operator%=(VQ L&, R);
4267    //        VQ L&       operator<<=(VQ L&, R);
4268    //        VQ L&       operator>>=(VQ L&, R);
4269    //        VQ L&       operator&=(VQ L&, R);
4270    //        VQ L&       operator^=(VQ L&, R);
4271    //        VQ L&       operator|=(VQ L&, R);
4272    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
4273      for (unsigned Right = FirstPromotedIntegralType;
4274           Right < LastPromotedIntegralType; ++Right) {
4275        QualType ParamTypes[2];
4276        ParamTypes[1] = ArithmeticTypes[Right];
4277
4278        // Add this built-in operator as a candidate (VQ is empty).
4279        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
4280        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4281        if (VisibleTypeConversionsQuals.hasVolatile()) {
4282          // Add this built-in operator as a candidate (VQ is 'volatile').
4283          ParamTypes[0] = ArithmeticTypes[Left];
4284          ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4285          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4286          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4287        }
4288      }
4289    }
4290    break;
4291
4292  case OO_Exclaim: {
4293    // C++ [over.operator]p23:
4294    //
4295    //   There also exist candidate operator functions of the form
4296    //
4297    //        bool        operator!(bool);
4298    //        bool        operator&&(bool, bool);     [BELOW]
4299    //        bool        operator||(bool, bool);     [BELOW]
4300    QualType ParamTy = Context.BoolTy;
4301    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4302                        /*IsAssignmentOperator=*/false,
4303                        /*NumContextualBoolArguments=*/1);
4304    break;
4305  }
4306
4307  case OO_AmpAmp:
4308  case OO_PipePipe: {
4309    // C++ [over.operator]p23:
4310    //
4311    //   There also exist candidate operator functions of the form
4312    //
4313    //        bool        operator!(bool);            [ABOVE]
4314    //        bool        operator&&(bool, bool);
4315    //        bool        operator||(bool, bool);
4316    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
4317    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4318                        /*IsAssignmentOperator=*/false,
4319                        /*NumContextualBoolArguments=*/2);
4320    break;
4321  }
4322
4323  case OO_Subscript:
4324    // C++ [over.built]p13:
4325    //
4326    //   For every cv-qualified or cv-unqualified object type T there
4327    //   exist candidate operator functions of the form
4328    //
4329    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
4330    //        T&         operator[](T*, ptrdiff_t);
4331    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
4332    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
4333    //        T&         operator[](ptrdiff_t, T*);
4334    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4335         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4336      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4337      QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
4338      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
4339
4340      // T& operator[](T*, ptrdiff_t)
4341      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4342
4343      // T& operator[](ptrdiff_t, T*);
4344      ParamTypes[0] = ParamTypes[1];
4345      ParamTypes[1] = *Ptr;
4346      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4347    }
4348    break;
4349
4350  case OO_ArrowStar:
4351    // C++ [over.built]p11:
4352    //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4353    //    C1 is the same type as C2 or is a derived class of C2, T is an object
4354    //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4355    //    there exist candidate operator functions of the form
4356    //    CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4357    //    where CV12 is the union of CV1 and CV2.
4358    {
4359      for (BuiltinCandidateTypeSet::iterator Ptr =
4360             CandidateTypes.pointer_begin();
4361           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4362        QualType C1Ty = (*Ptr);
4363        QualType C1;
4364        QualifierCollector Q1;
4365        if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
4366          C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
4367          if (!isa<RecordType>(C1))
4368            continue;
4369          // heuristic to reduce number of builtin candidates in the set.
4370          // Add volatile/restrict version only if there are conversions to a
4371          // volatile/restrict type.
4372          if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4373            continue;
4374          if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4375            continue;
4376        }
4377        for (BuiltinCandidateTypeSet::iterator
4378             MemPtr = CandidateTypes.member_pointer_begin(),
4379             MemPtrEnd = CandidateTypes.member_pointer_end();
4380             MemPtr != MemPtrEnd; ++MemPtr) {
4381          const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4382          QualType C2 = QualType(mptr->getClass(), 0);
4383          C2 = C2.getUnqualifiedType();
4384          if (C1 != C2 && !IsDerivedFrom(C1, C2))
4385            break;
4386          QualType ParamTypes[2] = { *Ptr, *MemPtr };
4387          // build CV12 T&
4388          QualType T = mptr->getPointeeType();
4389          if (!VisibleTypeConversionsQuals.hasVolatile() &&
4390              T.isVolatileQualified())
4391            continue;
4392          if (!VisibleTypeConversionsQuals.hasRestrict() &&
4393              T.isRestrictQualified())
4394            continue;
4395          T = Q1.apply(T);
4396          QualType ResultTy = Context.getLValueReferenceType(T);
4397          AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4398        }
4399      }
4400    }
4401    break;
4402
4403  case OO_Conditional:
4404    // Note that we don't consider the first argument, since it has been
4405    // contextually converted to bool long ago. The candidates below are
4406    // therefore added as binary.
4407    //
4408    // C++ [over.built]p24:
4409    //   For every type T, where T is a pointer or pointer-to-member type,
4410    //   there exist candidate operator functions of the form
4411    //
4412    //        T        operator?(bool, T, T);
4413    //
4414    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4415         E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4416      QualType ParamTypes[2] = { *Ptr, *Ptr };
4417      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4418    }
4419    for (BuiltinCandidateTypeSet::iterator Ptr =
4420           CandidateTypes.member_pointer_begin(),
4421         E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4422      QualType ParamTypes[2] = { *Ptr, *Ptr };
4423      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4424    }
4425    goto Conditional;
4426  }
4427}
4428
4429/// \brief Add function candidates found via argument-dependent lookup
4430/// to the set of overloading candidates.
4431///
4432/// This routine performs argument-dependent name lookup based on the
4433/// given function name (which may also be an operator name) and adds
4434/// all of the overload candidates found by ADL to the overload
4435/// candidate set (C++ [basic.lookup.argdep]).
4436void
4437Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4438                                           bool Operator,
4439                                           Expr **Args, unsigned NumArgs,
4440                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4441                                           OverloadCandidateSet& CandidateSet,
4442                                           bool PartialOverloading) {
4443  ADLResult Fns;
4444
4445  // FIXME: This approach for uniquing ADL results (and removing
4446  // redundant candidates from the set) relies on pointer-equality,
4447  // which means we need to key off the canonical decl.  However,
4448  // always going back to the canonical decl might not get us the
4449  // right set of default arguments.  What default arguments are
4450  // we supposed to consider on ADL candidates, anyway?
4451
4452  // FIXME: Pass in the explicit template arguments?
4453  ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
4454
4455  // Erase all of the candidates we already knew about.
4456  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4457                                   CandEnd = CandidateSet.end();
4458       Cand != CandEnd; ++Cand)
4459    if (Cand->Function) {
4460      Fns.erase(Cand->Function);
4461      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4462        Fns.erase(FunTmpl);
4463    }
4464
4465  // For each of the ADL candidates we found, add it to the overload
4466  // set.
4467  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
4468    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
4469    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
4470      if (ExplicitTemplateArgs)
4471        continue;
4472
4473      AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
4474                           false, PartialOverloading);
4475    } else
4476      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
4477                                   FoundDecl, ExplicitTemplateArgs,
4478                                   Args, NumArgs, CandidateSet);
4479  }
4480}
4481
4482/// isBetterOverloadCandidate - Determines whether the first overload
4483/// candidate is a better candidate than the second (C++ 13.3.3p1).
4484bool
4485Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
4486                                const OverloadCandidate& Cand2,
4487                                SourceLocation Loc) {
4488  // Define viable functions to be better candidates than non-viable
4489  // functions.
4490  if (!Cand2.Viable)
4491    return Cand1.Viable;
4492  else if (!Cand1.Viable)
4493    return false;
4494
4495  // C++ [over.match.best]p1:
4496  //
4497  //   -- if F is a static member function, ICS1(F) is defined such
4498  //      that ICS1(F) is neither better nor worse than ICS1(G) for
4499  //      any function G, and, symmetrically, ICS1(G) is neither
4500  //      better nor worse than ICS1(F).
4501  unsigned StartArg = 0;
4502  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4503    StartArg = 1;
4504
4505  // C++ [over.match.best]p1:
4506  //   A viable function F1 is defined to be a better function than another
4507  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
4508  //   conversion sequence than ICSi(F2), and then...
4509  unsigned NumArgs = Cand1.Conversions.size();
4510  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4511  bool HasBetterConversion = false;
4512  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
4513    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4514                                               Cand2.Conversions[ArgIdx])) {
4515    case ImplicitConversionSequence::Better:
4516      // Cand1 has a better conversion sequence.
4517      HasBetterConversion = true;
4518      break;
4519
4520    case ImplicitConversionSequence::Worse:
4521      // Cand1 can't be better than Cand2.
4522      return false;
4523
4524    case ImplicitConversionSequence::Indistinguishable:
4525      // Do nothing.
4526      break;
4527    }
4528  }
4529
4530  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
4531  //       ICSj(F2), or, if not that,
4532  if (HasBetterConversion)
4533    return true;
4534
4535  //     - F1 is a non-template function and F2 is a function template
4536  //       specialization, or, if not that,
4537  if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4538      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4539    return true;
4540
4541  //   -- F1 and F2 are function template specializations, and the function
4542  //      template for F1 is more specialized than the template for F2
4543  //      according to the partial ordering rules described in 14.5.5.2, or,
4544  //      if not that,
4545  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4546      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4547    if (FunctionTemplateDecl *BetterTemplate
4548          = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4549                                       Cand2.Function->getPrimaryTemplate(),
4550                                       Loc,
4551                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4552                                                             : TPOC_Call))
4553      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
4554
4555  //   -- the context is an initialization by user-defined conversion
4556  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
4557  //      from the return type of F1 to the destination type (i.e.,
4558  //      the type of the entity being initialized) is a better
4559  //      conversion sequence than the standard conversion sequence
4560  //      from the return type of F2 to the destination type.
4561  if (Cand1.Function && Cand2.Function &&
4562      isa<CXXConversionDecl>(Cand1.Function) &&
4563      isa<CXXConversionDecl>(Cand2.Function)) {
4564    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4565                                               Cand2.FinalConversion)) {
4566    case ImplicitConversionSequence::Better:
4567      // Cand1 has a better conversion sequence.
4568      return true;
4569
4570    case ImplicitConversionSequence::Worse:
4571      // Cand1 can't be better than Cand2.
4572      return false;
4573
4574    case ImplicitConversionSequence::Indistinguishable:
4575      // Do nothing
4576      break;
4577    }
4578  }
4579
4580  return false;
4581}
4582
4583/// \brief Computes the best viable function (C++ 13.3.3)
4584/// within an overload candidate set.
4585///
4586/// \param CandidateSet the set of candidate functions.
4587///
4588/// \param Loc the location of the function name (or operator symbol) for
4589/// which overload resolution occurs.
4590///
4591/// \param Best f overload resolution was successful or found a deleted
4592/// function, Best points to the candidate function found.
4593///
4594/// \returns The result of overload resolution.
4595OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4596                                           SourceLocation Loc,
4597                                        OverloadCandidateSet::iterator& Best) {
4598  // Find the best viable function.
4599  Best = CandidateSet.end();
4600  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4601       Cand != CandidateSet.end(); ++Cand) {
4602    if (Cand->Viable) {
4603      if (Best == CandidateSet.end() ||
4604          isBetterOverloadCandidate(*Cand, *Best, Loc))
4605        Best = Cand;
4606    }
4607  }
4608
4609  // If we didn't find any viable functions, abort.
4610  if (Best == CandidateSet.end())
4611    return OR_No_Viable_Function;
4612
4613  // Make sure that this function is better than every other viable
4614  // function. If not, we have an ambiguity.
4615  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4616       Cand != CandidateSet.end(); ++Cand) {
4617    if (Cand->Viable &&
4618        Cand != Best &&
4619        !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
4620      Best = CandidateSet.end();
4621      return OR_Ambiguous;
4622    }
4623  }
4624
4625  // Best is the best viable function.
4626  if (Best->Function &&
4627      (Best->Function->isDeleted() ||
4628       Best->Function->getAttr<UnavailableAttr>()))
4629    return OR_Deleted;
4630
4631  // C++ [basic.def.odr]p2:
4632  //   An overloaded function is used if it is selected by overload resolution
4633  //   when referred to from a potentially-evaluated expression. [Note: this
4634  //   covers calls to named functions (5.2.2), operator overloading
4635  //   (clause 13), user-defined conversions (12.3.2), allocation function for
4636  //   placement new (5.3.4), as well as non-default initialization (8.5).
4637  if (Best->Function)
4638    MarkDeclarationReferenced(Loc, Best->Function);
4639  return OR_Success;
4640}
4641
4642namespace {
4643
4644enum OverloadCandidateKind {
4645  oc_function,
4646  oc_method,
4647  oc_constructor,
4648  oc_function_template,
4649  oc_method_template,
4650  oc_constructor_template,
4651  oc_implicit_default_constructor,
4652  oc_implicit_copy_constructor,
4653  oc_implicit_copy_assignment
4654};
4655
4656OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4657                                                FunctionDecl *Fn,
4658                                                std::string &Description) {
4659  bool isTemplate = false;
4660
4661  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4662    isTemplate = true;
4663    Description = S.getTemplateArgumentBindingsText(
4664      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4665  }
4666
4667  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
4668    if (!Ctor->isImplicit())
4669      return isTemplate ? oc_constructor_template : oc_constructor;
4670
4671    return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4672                                     : oc_implicit_default_constructor;
4673  }
4674
4675  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4676    // This actually gets spelled 'candidate function' for now, but
4677    // it doesn't hurt to split it out.
4678    if (!Meth->isImplicit())
4679      return isTemplate ? oc_method_template : oc_method;
4680
4681    assert(Meth->isCopyAssignment()
4682           && "implicit method is not copy assignment operator?");
4683    return oc_implicit_copy_assignment;
4684  }
4685
4686  return isTemplate ? oc_function_template : oc_function;
4687}
4688
4689} // end anonymous namespace
4690
4691// Notes the location of an overload candidate.
4692void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
4693  std::string FnDesc;
4694  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4695  Diag(Fn->getLocation(), diag::note_ovl_candidate)
4696    << (unsigned) K << FnDesc;
4697}
4698
4699/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
4700/// "lead" diagnostic; it will be given two arguments, the source and
4701/// target types of the conversion.
4702void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4703                                       SourceLocation CaretLoc,
4704                                       const PartialDiagnostic &PDiag) {
4705  Diag(CaretLoc, PDiag)
4706    << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4707  for (AmbiguousConversionSequence::const_iterator
4708         I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4709    NoteOverloadCandidate(*I);
4710  }
4711}
4712
4713namespace {
4714
4715void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4716  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4717  assert(Conv.isBad());
4718  assert(Cand->Function && "for now, candidate must be a function");
4719  FunctionDecl *Fn = Cand->Function;
4720
4721  // There's a conversion slot for the object argument if this is a
4722  // non-constructor method.  Note that 'I' corresponds the
4723  // conversion-slot index.
4724  bool isObjectArgument = false;
4725  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
4726    if (I == 0)
4727      isObjectArgument = true;
4728    else
4729      I--;
4730  }
4731
4732  std::string FnDesc;
4733  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4734
4735  Expr *FromExpr = Conv.Bad.FromExpr;
4736  QualType FromTy = Conv.Bad.getFromType();
4737  QualType ToTy = Conv.Bad.getToType();
4738
4739  if (FromTy == S.Context.OverloadTy) {
4740    assert(FromExpr && "overload set argument came from implicit argument?");
4741    Expr *E = FromExpr->IgnoreParens();
4742    if (isa<UnaryOperator>(E))
4743      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
4744    DeclarationName Name = cast<OverloadExpr>(E)->getName();
4745
4746    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4747      << (unsigned) FnKind << FnDesc
4748      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4749      << ToTy << Name << I+1;
4750    return;
4751  }
4752
4753  // Do some hand-waving analysis to see if the non-viability is due
4754  // to a qualifier mismatch.
4755  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4756  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4757  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4758    CToTy = RT->getPointeeType();
4759  else {
4760    // TODO: detect and diagnose the full richness of const mismatches.
4761    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4762      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4763        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4764  }
4765
4766  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4767      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4768    // It is dumb that we have to do this here.
4769    while (isa<ArrayType>(CFromTy))
4770      CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4771    while (isa<ArrayType>(CToTy))
4772      CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4773
4774    Qualifiers FromQs = CFromTy.getQualifiers();
4775    Qualifiers ToQs = CToTy.getQualifiers();
4776
4777    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4778      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4779        << (unsigned) FnKind << FnDesc
4780        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4781        << FromTy
4782        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4783        << (unsigned) isObjectArgument << I+1;
4784      return;
4785    }
4786
4787    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4788    assert(CVR && "unexpected qualifiers mismatch");
4789
4790    if (isObjectArgument) {
4791      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4792        << (unsigned) FnKind << FnDesc
4793        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4794        << FromTy << (CVR - 1);
4795    } else {
4796      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4797        << (unsigned) FnKind << FnDesc
4798        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4799        << FromTy << (CVR - 1) << I+1;
4800    }
4801    return;
4802  }
4803
4804  // Diagnose references or pointers to incomplete types differently,
4805  // since it's far from impossible that the incompleteness triggered
4806  // the failure.
4807  QualType TempFromTy = FromTy.getNonReferenceType();
4808  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4809    TempFromTy = PTy->getPointeeType();
4810  if (TempFromTy->isIncompleteType()) {
4811    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4812      << (unsigned) FnKind << FnDesc
4813      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4814      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4815    return;
4816  }
4817
4818  // TODO: specialize more based on the kind of mismatch
4819  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4820    << (unsigned) FnKind << FnDesc
4821    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4822    << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4823}
4824
4825void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4826                           unsigned NumFormalArgs) {
4827  // TODO: treat calls to a missing default constructor as a special case
4828
4829  FunctionDecl *Fn = Cand->Function;
4830  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4831
4832  unsigned MinParams = Fn->getMinRequiredArguments();
4833
4834  // at least / at most / exactly
4835  unsigned mode, modeCount;
4836  if (NumFormalArgs < MinParams) {
4837    assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4838    if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4839      mode = 0; // "at least"
4840    else
4841      mode = 2; // "exactly"
4842    modeCount = MinParams;
4843  } else {
4844    assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4845    if (MinParams != FnTy->getNumArgs())
4846      mode = 1; // "at most"
4847    else
4848      mode = 2; // "exactly"
4849    modeCount = FnTy->getNumArgs();
4850  }
4851
4852  std::string Description;
4853  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4854
4855  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4856    << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
4857}
4858
4859/// Diagnose a failed template-argument deduction.
4860void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4861                          Expr **Args, unsigned NumArgs) {
4862  FunctionDecl *Fn = Cand->Function; // pattern
4863
4864  TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4865                                   Cand->DeductionFailure.TemplateParameter);
4866
4867  switch (Cand->DeductionFailure.Result) {
4868  case Sema::TDK_Success:
4869    llvm_unreachable("TDK_success while diagnosing bad deduction");
4870
4871  case Sema::TDK_Incomplete: {
4872    NamedDecl *ParamD;
4873    (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4874    (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4875    (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4876    assert(ParamD && "no parameter found for incomplete deduction result");
4877    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4878      << ParamD->getDeclName();
4879    return;
4880  }
4881
4882  // TODO: diagnose these individually, then kill off
4883  // note_ovl_candidate_bad_deduction, which is uselessly vague.
4884  case Sema::TDK_InstantiationDepth:
4885  case Sema::TDK_Inconsistent:
4886  case Sema::TDK_InconsistentQuals:
4887  case Sema::TDK_SubstitutionFailure:
4888  case Sema::TDK_NonDeducedMismatch:
4889  case Sema::TDK_TooManyArguments:
4890  case Sema::TDK_TooFewArguments:
4891  case Sema::TDK_InvalidExplicitArguments:
4892  case Sema::TDK_FailedOverloadResolution:
4893    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4894    return;
4895  }
4896}
4897
4898/// Generates a 'note' diagnostic for an overload candidate.  We've
4899/// already generated a primary error at the call site.
4900///
4901/// It really does need to be a single diagnostic with its caret
4902/// pointed at the candidate declaration.  Yes, this creates some
4903/// major challenges of technical writing.  Yes, this makes pointing
4904/// out problems with specific arguments quite awkward.  It's still
4905/// better than generating twenty screens of text for every failed
4906/// overload.
4907///
4908/// It would be great to be able to express per-candidate problems
4909/// more richly for those diagnostic clients that cared, but we'd
4910/// still have to be just as careful with the default diagnostics.
4911void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4912                           Expr **Args, unsigned NumArgs) {
4913  FunctionDecl *Fn = Cand->Function;
4914
4915  // Note deleted candidates, but only if they're viable.
4916  if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
4917    std::string FnDesc;
4918    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4919
4920    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
4921      << FnKind << FnDesc << Fn->isDeleted();
4922    return;
4923  }
4924
4925  // We don't really have anything else to say about viable candidates.
4926  if (Cand->Viable) {
4927    S.NoteOverloadCandidate(Fn);
4928    return;
4929  }
4930
4931  switch (Cand->FailureKind) {
4932  case ovl_fail_too_many_arguments:
4933  case ovl_fail_too_few_arguments:
4934    return DiagnoseArityMismatch(S, Cand, NumArgs);
4935
4936  case ovl_fail_bad_deduction:
4937    return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4938
4939  case ovl_fail_trivial_conversion:
4940  case ovl_fail_bad_final_conversion:
4941  case ovl_fail_final_conversion_not_exact:
4942    return S.NoteOverloadCandidate(Fn);
4943
4944  case ovl_fail_bad_conversion: {
4945    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4946    for (unsigned N = Cand->Conversions.size(); I != N; ++I)
4947      if (Cand->Conversions[I].isBad())
4948        return DiagnoseBadConversion(S, Cand, I);
4949
4950    // FIXME: this currently happens when we're called from SemaInit
4951    // when user-conversion overload fails.  Figure out how to handle
4952    // those conditions and diagnose them well.
4953    return S.NoteOverloadCandidate(Fn);
4954  }
4955  }
4956}
4957
4958void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4959  // Desugar the type of the surrogate down to a function type,
4960  // retaining as many typedefs as possible while still showing
4961  // the function type (and, therefore, its parameter types).
4962  QualType FnType = Cand->Surrogate->getConversionType();
4963  bool isLValueReference = false;
4964  bool isRValueReference = false;
4965  bool isPointer = false;
4966  if (const LValueReferenceType *FnTypeRef =
4967        FnType->getAs<LValueReferenceType>()) {
4968    FnType = FnTypeRef->getPointeeType();
4969    isLValueReference = true;
4970  } else if (const RValueReferenceType *FnTypeRef =
4971               FnType->getAs<RValueReferenceType>()) {
4972    FnType = FnTypeRef->getPointeeType();
4973    isRValueReference = true;
4974  }
4975  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4976    FnType = FnTypePtr->getPointeeType();
4977    isPointer = true;
4978  }
4979  // Desugar down to a function type.
4980  FnType = QualType(FnType->getAs<FunctionType>(), 0);
4981  // Reconstruct the pointer/reference as appropriate.
4982  if (isPointer) FnType = S.Context.getPointerType(FnType);
4983  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4984  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4985
4986  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4987    << FnType;
4988}
4989
4990void NoteBuiltinOperatorCandidate(Sema &S,
4991                                  const char *Opc,
4992                                  SourceLocation OpLoc,
4993                                  OverloadCandidate *Cand) {
4994  assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4995  std::string TypeStr("operator");
4996  TypeStr += Opc;
4997  TypeStr += "(";
4998  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4999  if (Cand->Conversions.size() == 1) {
5000    TypeStr += ")";
5001    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5002  } else {
5003    TypeStr += ", ";
5004    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5005    TypeStr += ")";
5006    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5007  }
5008}
5009
5010void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5011                                  OverloadCandidate *Cand) {
5012  unsigned NoOperands = Cand->Conversions.size();
5013  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5014    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
5015    if (ICS.isBad()) break; // all meaningless after first invalid
5016    if (!ICS.isAmbiguous()) continue;
5017
5018    S.DiagnoseAmbiguousConversion(ICS, OpLoc,
5019                              S.PDiag(diag::note_ambiguous_type_conversion));
5020  }
5021}
5022
5023SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5024  if (Cand->Function)
5025    return Cand->Function->getLocation();
5026  if (Cand->IsSurrogate)
5027    return Cand->Surrogate->getLocation();
5028  return SourceLocation();
5029}
5030
5031struct CompareOverloadCandidatesForDisplay {
5032  Sema &S;
5033  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
5034
5035  bool operator()(const OverloadCandidate *L,
5036                  const OverloadCandidate *R) {
5037    // Fast-path this check.
5038    if (L == R) return false;
5039
5040    // Order first by viability.
5041    if (L->Viable) {
5042      if (!R->Viable) return true;
5043
5044      // TODO: introduce a tri-valued comparison for overload
5045      // candidates.  Would be more worthwhile if we had a sort
5046      // that could exploit it.
5047      if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5048      if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
5049    } else if (R->Viable)
5050      return false;
5051
5052    assert(L->Viable == R->Viable);
5053
5054    // Criteria by which we can sort non-viable candidates:
5055    if (!L->Viable) {
5056      // 1. Arity mismatches come after other candidates.
5057      if (L->FailureKind == ovl_fail_too_many_arguments ||
5058          L->FailureKind == ovl_fail_too_few_arguments)
5059        return false;
5060      if (R->FailureKind == ovl_fail_too_many_arguments ||
5061          R->FailureKind == ovl_fail_too_few_arguments)
5062        return true;
5063
5064      // 2. Bad conversions come first and are ordered by the number
5065      // of bad conversions and quality of good conversions.
5066      if (L->FailureKind == ovl_fail_bad_conversion) {
5067        if (R->FailureKind != ovl_fail_bad_conversion)
5068          return true;
5069
5070        // If there's any ordering between the defined conversions...
5071        // FIXME: this might not be transitive.
5072        assert(L->Conversions.size() == R->Conversions.size());
5073
5074        int leftBetter = 0;
5075        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5076        for (unsigned E = L->Conversions.size(); I != E; ++I) {
5077          switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5078                                                       R->Conversions[I])) {
5079          case ImplicitConversionSequence::Better:
5080            leftBetter++;
5081            break;
5082
5083          case ImplicitConversionSequence::Worse:
5084            leftBetter--;
5085            break;
5086
5087          case ImplicitConversionSequence::Indistinguishable:
5088            break;
5089          }
5090        }
5091        if (leftBetter > 0) return true;
5092        if (leftBetter < 0) return false;
5093
5094      } else if (R->FailureKind == ovl_fail_bad_conversion)
5095        return false;
5096
5097      // TODO: others?
5098    }
5099
5100    // Sort everything else by location.
5101    SourceLocation LLoc = GetLocationForCandidate(L);
5102    SourceLocation RLoc = GetLocationForCandidate(R);
5103
5104    // Put candidates without locations (e.g. builtins) at the end.
5105    if (LLoc.isInvalid()) return false;
5106    if (RLoc.isInvalid()) return true;
5107
5108    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
5109  }
5110};
5111
5112/// CompleteNonViableCandidate - Normally, overload resolution only
5113/// computes up to the first
5114void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5115                                Expr **Args, unsigned NumArgs) {
5116  assert(!Cand->Viable);
5117
5118  // Don't do anything on failures other than bad conversion.
5119  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5120
5121  // Skip forward to the first bad conversion.
5122  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
5123  unsigned ConvCount = Cand->Conversions.size();
5124  while (true) {
5125    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5126    ConvIdx++;
5127    if (Cand->Conversions[ConvIdx - 1].isBad())
5128      break;
5129  }
5130
5131  if (ConvIdx == ConvCount)
5132    return;
5133
5134  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5135         "remaining conversion is initialized?");
5136
5137  // FIXME: this should probably be preserved from the overload
5138  // operation somehow.
5139  bool SuppressUserConversions = false;
5140
5141  const FunctionProtoType* Proto;
5142  unsigned ArgIdx = ConvIdx;
5143
5144  if (Cand->IsSurrogate) {
5145    QualType ConvType
5146      = Cand->Surrogate->getConversionType().getNonReferenceType();
5147    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5148      ConvType = ConvPtrType->getPointeeType();
5149    Proto = ConvType->getAs<FunctionProtoType>();
5150    ArgIdx--;
5151  } else if (Cand->Function) {
5152    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5153    if (isa<CXXMethodDecl>(Cand->Function) &&
5154        !isa<CXXConstructorDecl>(Cand->Function))
5155      ArgIdx--;
5156  } else {
5157    // Builtin binary operator with a bad first conversion.
5158    assert(ConvCount <= 3);
5159    for (; ConvIdx != ConvCount; ++ConvIdx)
5160      Cand->Conversions[ConvIdx]
5161        = TryCopyInitialization(S, Args[ConvIdx],
5162                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
5163                                SuppressUserConversions,
5164                                /*InOverloadResolution*/ true);
5165    return;
5166  }
5167
5168  // Fill in the rest of the conversions.
5169  unsigned NumArgsInProto = Proto->getNumArgs();
5170  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5171    if (ArgIdx < NumArgsInProto)
5172      Cand->Conversions[ConvIdx]
5173        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5174                                SuppressUserConversions,
5175                                /*InOverloadResolution=*/true);
5176    else
5177      Cand->Conversions[ConvIdx].setEllipsis();
5178  }
5179}
5180
5181} // end anonymous namespace
5182
5183/// PrintOverloadCandidates - When overload resolution fails, prints
5184/// diagnostic messages containing the candidates in the candidate
5185/// set.
5186void
5187Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
5188                              OverloadCandidateDisplayKind OCD,
5189                              Expr **Args, unsigned NumArgs,
5190                              const char *Opc,
5191                              SourceLocation OpLoc) {
5192  // Sort the candidates by viability and position.  Sorting directly would
5193  // be prohibitive, so we make a set of pointers and sort those.
5194  llvm::SmallVector<OverloadCandidate*, 32> Cands;
5195  if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5196  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5197                                  LastCand = CandidateSet.end();
5198       Cand != LastCand; ++Cand) {
5199    if (Cand->Viable)
5200      Cands.push_back(Cand);
5201    else if (OCD == OCD_AllCandidates) {
5202      CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5203      Cands.push_back(Cand);
5204    }
5205  }
5206
5207  std::sort(Cands.begin(), Cands.end(),
5208            CompareOverloadCandidatesForDisplay(*this));
5209
5210  bool ReportedAmbiguousConversions = false;
5211
5212  llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5213  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5214    OverloadCandidate *Cand = *I;
5215
5216    if (Cand->Function)
5217      NoteFunctionCandidate(*this, Cand, Args, NumArgs);
5218    else if (Cand->IsSurrogate)
5219      NoteSurrogateCandidate(*this, Cand);
5220
5221    // This a builtin candidate.  We do not, in general, want to list
5222    // every possible builtin candidate.
5223    else if (Cand->Viable) {
5224      // Generally we only see ambiguities including viable builtin
5225      // operators if overload resolution got screwed up by an
5226      // ambiguous user-defined conversion.
5227      //
5228      // FIXME: It's quite possible for different conversions to see
5229      // different ambiguities, though.
5230      if (!ReportedAmbiguousConversions) {
5231        NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5232        ReportedAmbiguousConversions = true;
5233      }
5234
5235      // If this is a viable builtin, print it.
5236      NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
5237    }
5238  }
5239}
5240
5241static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
5242  if (isa<UnresolvedLookupExpr>(E))
5243    return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
5244
5245  return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
5246}
5247
5248/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5249/// an overloaded function (C++ [over.over]), where @p From is an
5250/// expression with overloaded function type and @p ToType is the type
5251/// we're trying to resolve to. For example:
5252///
5253/// @code
5254/// int f(double);
5255/// int f(int);
5256///
5257/// int (*pfd)(double) = f; // selects f(double)
5258/// @endcode
5259///
5260/// This routine returns the resulting FunctionDecl if it could be
5261/// resolved, and NULL otherwise. When @p Complain is true, this
5262/// routine will emit diagnostics if there is an error.
5263FunctionDecl *
5264Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
5265                                         bool Complain,
5266                                         DeclAccessPair &FoundResult) {
5267  QualType FunctionType = ToType;
5268  bool IsMember = false;
5269  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
5270    FunctionType = ToTypePtr->getPointeeType();
5271  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
5272    FunctionType = ToTypeRef->getPointeeType();
5273  else if (const MemberPointerType *MemTypePtr =
5274                    ToType->getAs<MemberPointerType>()) {
5275    FunctionType = MemTypePtr->getPointeeType();
5276    IsMember = true;
5277  }
5278
5279  // C++ [over.over]p1:
5280  //   [...] [Note: any redundant set of parentheses surrounding the
5281  //   overloaded function name is ignored (5.1). ]
5282  // C++ [over.over]p1:
5283  //   [...] The overloaded function name can be preceded by the &
5284  //   operator.
5285  OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5286  TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5287  if (OvlExpr->hasExplicitTemplateArgs()) {
5288    OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5289    ExplicitTemplateArgs = &ETABuffer;
5290  }
5291
5292  // We expect a pointer or reference to function, or a function pointer.
5293  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5294  if (!FunctionType->isFunctionType()) {
5295    if (Complain)
5296      Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5297        << OvlExpr->getName() << ToType;
5298
5299    return 0;
5300  }
5301
5302  assert(From->getType() == Context.OverloadTy);
5303
5304  // Look through all of the overloaded functions, searching for one
5305  // whose type matches exactly.
5306  llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
5307  llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5308
5309  bool FoundNonTemplateFunction = false;
5310  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5311         E = OvlExpr->decls_end(); I != E; ++I) {
5312    // Look through any using declarations to find the underlying function.
5313    NamedDecl *Fn = (*I)->getUnderlyingDecl();
5314
5315    // C++ [over.over]p3:
5316    //   Non-member functions and static member functions match
5317    //   targets of type "pointer-to-function" or "reference-to-function."
5318    //   Nonstatic member functions match targets of
5319    //   type "pointer-to-member-function."
5320    // Note that according to DR 247, the containing class does not matter.
5321
5322    if (FunctionTemplateDecl *FunctionTemplate
5323          = dyn_cast<FunctionTemplateDecl>(Fn)) {
5324      if (CXXMethodDecl *Method
5325            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
5326        // Skip non-static function templates when converting to pointer, and
5327        // static when converting to member pointer.
5328        if (Method->isStatic() == IsMember)
5329          continue;
5330      } else if (IsMember)
5331        continue;
5332
5333      // C++ [over.over]p2:
5334      //   If the name is a function template, template argument deduction is
5335      //   done (14.8.2.2), and if the argument deduction succeeds, the
5336      //   resulting template argument list is used to generate a single
5337      //   function template specialization, which is added to the set of
5338      //   overloaded functions considered.
5339      // FIXME: We don't really want to build the specialization here, do we?
5340      FunctionDecl *Specialization = 0;
5341      TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
5342      if (TemplateDeductionResult Result
5343            = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5344                                      FunctionType, Specialization, Info)) {
5345        // FIXME: make a note of the failed deduction for diagnostics.
5346        (void)Result;
5347      } else {
5348        // FIXME: If the match isn't exact, shouldn't we just drop this as
5349        // a candidate? Find a testcase before changing the code.
5350        assert(FunctionType
5351                 == Context.getCanonicalType(Specialization->getType()));
5352        Matches.push_back(std::make_pair(I.getPair(),
5353                    cast<FunctionDecl>(Specialization->getCanonicalDecl())));
5354      }
5355
5356      continue;
5357    }
5358
5359    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5360      // Skip non-static functions when converting to pointer, and static
5361      // when converting to member pointer.
5362      if (Method->isStatic() == IsMember)
5363        continue;
5364
5365      // If we have explicit template arguments, skip non-templates.
5366      if (OvlExpr->hasExplicitTemplateArgs())
5367        continue;
5368    } else if (IsMember)
5369      continue;
5370
5371    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
5372      QualType ResultTy;
5373      if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5374          IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5375                               ResultTy)) {
5376        Matches.push_back(std::make_pair(I.getPair(),
5377                           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
5378        FoundNonTemplateFunction = true;
5379      }
5380    }
5381  }
5382
5383  // If there were 0 or 1 matches, we're done.
5384  if (Matches.empty()) {
5385    if (Complain) {
5386      Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5387        << OvlExpr->getName() << FunctionType;
5388      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5389                                 E = OvlExpr->decls_end();
5390           I != E; ++I)
5391        if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5392          NoteOverloadCandidate(F);
5393    }
5394
5395    return 0;
5396  } else if (Matches.size() == 1) {
5397    FunctionDecl *Result = Matches[0].second;
5398    FoundResult = Matches[0].first;
5399    MarkDeclarationReferenced(From->getLocStart(), Result);
5400    if (Complain)
5401      CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
5402    return Result;
5403  }
5404
5405  // C++ [over.over]p4:
5406  //   If more than one function is selected, [...]
5407  if (!FoundNonTemplateFunction) {
5408    //   [...] and any given function template specialization F1 is
5409    //   eliminated if the set contains a second function template
5410    //   specialization whose function template is more specialized
5411    //   than the function template of F1 according to the partial
5412    //   ordering rules of 14.5.5.2.
5413
5414    // The algorithm specified above is quadratic. We instead use a
5415    // two-pass algorithm (similar to the one used to identify the
5416    // best viable function in an overload set) that identifies the
5417    // best function template (if it exists).
5418
5419    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5420    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5421      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
5422
5423    UnresolvedSetIterator Result =
5424        getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
5425                           TPOC_Other, From->getLocStart(),
5426                           PDiag(),
5427                           PDiag(diag::err_addr_ovl_ambiguous)
5428                               << Matches[0].second->getDeclName(),
5429                           PDiag(diag::note_ovl_candidate)
5430                               << (unsigned) oc_function_template);
5431    assert(Result != MatchesCopy.end() && "no most-specialized template");
5432    MarkDeclarationReferenced(From->getLocStart(), *Result);
5433    FoundResult = Matches[Result - MatchesCopy.begin()].first;
5434    if (Complain)
5435      CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
5436    return cast<FunctionDecl>(*Result);
5437  }
5438
5439  //   [...] any function template specializations in the set are
5440  //   eliminated if the set also contains a non-template function, [...]
5441  for (unsigned I = 0, N = Matches.size(); I != N; ) {
5442    if (Matches[I].second->getPrimaryTemplate() == 0)
5443      ++I;
5444    else {
5445      Matches[I] = Matches[--N];
5446      Matches.set_size(N);
5447    }
5448  }
5449
5450  // [...] After such eliminations, if any, there shall remain exactly one
5451  // selected function.
5452  if (Matches.size() == 1) {
5453    MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
5454    FoundResult = Matches[0].first;
5455    if (Complain)
5456      CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5457    return cast<FunctionDecl>(Matches[0].second);
5458  }
5459
5460  // FIXME: We should probably return the same thing that BestViableFunction
5461  // returns (even if we issue the diagnostics here).
5462  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
5463    << Matches[0].second->getDeclName();
5464  for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5465    NoteOverloadCandidate(Matches[I].second);
5466  return 0;
5467}
5468
5469/// \brief Given an expression that refers to an overloaded function, try to
5470/// resolve that overloaded function expression down to a single function.
5471///
5472/// This routine can only resolve template-ids that refer to a single function
5473/// template, where that template-id refers to a single template whose template
5474/// arguments are either provided by the template-id or have defaults,
5475/// as described in C++0x [temp.arg.explicit]p3.
5476FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5477  // C++ [over.over]p1:
5478  //   [...] [Note: any redundant set of parentheses surrounding the
5479  //   overloaded function name is ignored (5.1). ]
5480  // C++ [over.over]p1:
5481  //   [...] The overloaded function name can be preceded by the &
5482  //   operator.
5483
5484  if (From->getType() != Context.OverloadTy)
5485    return 0;
5486
5487  OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5488
5489  // If we didn't actually find any template-ids, we're done.
5490  if (!OvlExpr->hasExplicitTemplateArgs())
5491    return 0;
5492
5493  TemplateArgumentListInfo ExplicitTemplateArgs;
5494  OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
5495
5496  // Look through all of the overloaded functions, searching for one
5497  // whose type matches exactly.
5498  FunctionDecl *Matched = 0;
5499  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5500         E = OvlExpr->decls_end(); I != E; ++I) {
5501    // C++0x [temp.arg.explicit]p3:
5502    //   [...] In contexts where deduction is done and fails, or in contexts
5503    //   where deduction is not done, if a template argument list is
5504    //   specified and it, along with any default template arguments,
5505    //   identifies a single function template specialization, then the
5506    //   template-id is an lvalue for the function template specialization.
5507    FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5508
5509    // C++ [over.over]p2:
5510    //   If the name is a function template, template argument deduction is
5511    //   done (14.8.2.2), and if the argument deduction succeeds, the
5512    //   resulting template argument list is used to generate a single
5513    //   function template specialization, which is added to the set of
5514    //   overloaded functions considered.
5515    FunctionDecl *Specialization = 0;
5516    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
5517    if (TemplateDeductionResult Result
5518          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5519                                    Specialization, Info)) {
5520      // FIXME: make a note of the failed deduction for diagnostics.
5521      (void)Result;
5522      continue;
5523    }
5524
5525    // Multiple matches; we can't resolve to a single declaration.
5526    if (Matched)
5527      return 0;
5528
5529    Matched = Specialization;
5530  }
5531
5532  return Matched;
5533}
5534
5535/// \brief Add a single candidate to the overload set.
5536static void AddOverloadedCallCandidate(Sema &S,
5537                                       DeclAccessPair FoundDecl,
5538                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
5539                                       Expr **Args, unsigned NumArgs,
5540                                       OverloadCandidateSet &CandidateSet,
5541                                       bool PartialOverloading) {
5542  NamedDecl *Callee = FoundDecl.getDecl();
5543  if (isa<UsingShadowDecl>(Callee))
5544    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5545
5546  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
5547    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
5548    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
5549                           false, PartialOverloading);
5550    return;
5551  }
5552
5553  if (FunctionTemplateDecl *FuncTemplate
5554      = dyn_cast<FunctionTemplateDecl>(Callee)) {
5555    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5556                                   ExplicitTemplateArgs,
5557                                   Args, NumArgs, CandidateSet);
5558    return;
5559  }
5560
5561  assert(false && "unhandled case in overloaded call candidate");
5562
5563  // do nothing?
5564}
5565
5566/// \brief Add the overload candidates named by callee and/or found by argument
5567/// dependent lookup to the given overload set.
5568void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
5569                                       Expr **Args, unsigned NumArgs,
5570                                       OverloadCandidateSet &CandidateSet,
5571                                       bool PartialOverloading) {
5572
5573#ifndef NDEBUG
5574  // Verify that ArgumentDependentLookup is consistent with the rules
5575  // in C++0x [basic.lookup.argdep]p3:
5576  //
5577  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
5578  //   and let Y be the lookup set produced by argument dependent
5579  //   lookup (defined as follows). If X contains
5580  //
5581  //     -- a declaration of a class member, or
5582  //
5583  //     -- a block-scope function declaration that is not a
5584  //        using-declaration, or
5585  //
5586  //     -- a declaration that is neither a function or a function
5587  //        template
5588  //
5589  //   then Y is empty.
5590
5591  if (ULE->requiresADL()) {
5592    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5593           E = ULE->decls_end(); I != E; ++I) {
5594      assert(!(*I)->getDeclContext()->isRecord());
5595      assert(isa<UsingShadowDecl>(*I) ||
5596             !(*I)->getDeclContext()->isFunctionOrMethod());
5597      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
5598    }
5599  }
5600#endif
5601
5602  // It would be nice to avoid this copy.
5603  TemplateArgumentListInfo TABuffer;
5604  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5605  if (ULE->hasExplicitTemplateArgs()) {
5606    ULE->copyTemplateArgumentsInto(TABuffer);
5607    ExplicitTemplateArgs = &TABuffer;
5608  }
5609
5610  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5611         E = ULE->decls_end(); I != E; ++I)
5612    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
5613                               Args, NumArgs, CandidateSet,
5614                               PartialOverloading);
5615
5616  if (ULE->requiresADL())
5617    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5618                                         Args, NumArgs,
5619                                         ExplicitTemplateArgs,
5620                                         CandidateSet,
5621                                         PartialOverloading);
5622}
5623
5624static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5625                                      Expr **Args, unsigned NumArgs) {
5626  Fn->Destroy(SemaRef.Context);
5627  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5628    Args[Arg]->Destroy(SemaRef.Context);
5629  return SemaRef.ExprError();
5630}
5631
5632/// Attempts to recover from a call where no functions were found.
5633///
5634/// Returns true if new candidates were found.
5635static Sema::OwningExprResult
5636BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
5637                      UnresolvedLookupExpr *ULE,
5638                      SourceLocation LParenLoc,
5639                      Expr **Args, unsigned NumArgs,
5640                      SourceLocation *CommaLocs,
5641                      SourceLocation RParenLoc) {
5642
5643  CXXScopeSpec SS;
5644  if (ULE->getQualifier()) {
5645    SS.setScopeRep(ULE->getQualifier());
5646    SS.setRange(ULE->getQualifierRange());
5647  }
5648
5649  TemplateArgumentListInfo TABuffer;
5650  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5651  if (ULE->hasExplicitTemplateArgs()) {
5652    ULE->copyTemplateArgumentsInto(TABuffer);
5653    ExplicitTemplateArgs = &TABuffer;
5654  }
5655
5656  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5657                 Sema::LookupOrdinaryName);
5658  if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
5659    return Destroy(SemaRef, Fn, Args, NumArgs);
5660
5661  assert(!R.empty() && "lookup results empty despite recovery");
5662
5663  // Build an implicit member call if appropriate.  Just drop the
5664  // casts and such from the call, we don't really care.
5665  Sema::OwningExprResult NewFn = SemaRef.ExprError();
5666  if ((*R.begin())->isCXXClassMember())
5667    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5668  else if (ExplicitTemplateArgs)
5669    NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5670  else
5671    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5672
5673  if (NewFn.isInvalid())
5674    return Destroy(SemaRef, Fn, Args, NumArgs);
5675
5676  Fn->Destroy(SemaRef.Context);
5677
5678  // This shouldn't cause an infinite loop because we're giving it
5679  // an expression with non-empty lookup results, which should never
5680  // end up here.
5681  return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5682                         Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5683                               CommaLocs, RParenLoc);
5684}
5685
5686/// ResolveOverloadedCallFn - Given the call expression that calls Fn
5687/// (which eventually refers to the declaration Func) and the call
5688/// arguments Args/NumArgs, attempt to resolve the function call down
5689/// to a specific function. If overload resolution succeeds, returns
5690/// the function declaration produced by overload
5691/// resolution. Otherwise, emits diagnostics, deletes all of the
5692/// arguments and Fn, and returns NULL.
5693Sema::OwningExprResult
5694Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
5695                              SourceLocation LParenLoc,
5696                              Expr **Args, unsigned NumArgs,
5697                              SourceLocation *CommaLocs,
5698                              SourceLocation RParenLoc) {
5699#ifndef NDEBUG
5700  if (ULE->requiresADL()) {
5701    // To do ADL, we must have found an unqualified name.
5702    assert(!ULE->getQualifier() && "qualified name with ADL");
5703
5704    // We don't perform ADL for implicit declarations of builtins.
5705    // Verify that this was correctly set up.
5706    FunctionDecl *F;
5707    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5708        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5709        F->getBuiltinID() && F->isImplicit())
5710      assert(0 && "performing ADL for builtin");
5711
5712    // We don't perform ADL in C.
5713    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5714  }
5715#endif
5716
5717  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
5718
5719  // Add the functions denoted by the callee to the set of candidate
5720  // functions, including those from argument-dependent lookup.
5721  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
5722
5723  // If we found nothing, try to recover.
5724  // AddRecoveryCallCandidates diagnoses the error itself, so we just
5725  // bailout out if it fails.
5726  if (CandidateSet.empty())
5727    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
5728                                 CommaLocs, RParenLoc);
5729
5730  OverloadCandidateSet::iterator Best;
5731  switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
5732  case OR_Success: {
5733    FunctionDecl *FDecl = Best->Function;
5734    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
5735    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
5736    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5737  }
5738
5739  case OR_No_Viable_Function:
5740    Diag(Fn->getSourceRange().getBegin(),
5741         diag::err_ovl_no_viable_function_in_call)
5742      << ULE->getName() << Fn->getSourceRange();
5743    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
5744    break;
5745
5746  case OR_Ambiguous:
5747    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
5748      << ULE->getName() << Fn->getSourceRange();
5749    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
5750    break;
5751
5752  case OR_Deleted:
5753    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5754      << Best->Function->isDeleted()
5755      << ULE->getName()
5756      << Fn->getSourceRange();
5757    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
5758    break;
5759  }
5760
5761  // Overload resolution failed. Destroy all of the subexpressions and
5762  // return NULL.
5763  Fn->Destroy(Context);
5764  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5765    Args[Arg]->Destroy(Context);
5766  return ExprError();
5767}
5768
5769static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
5770  return Functions.size() > 1 ||
5771    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5772}
5773
5774/// \brief Create a unary operation that may resolve to an overloaded
5775/// operator.
5776///
5777/// \param OpLoc The location of the operator itself (e.g., '*').
5778///
5779/// \param OpcIn The UnaryOperator::Opcode that describes this
5780/// operator.
5781///
5782/// \param Functions The set of non-member functions that will be
5783/// considered by overload resolution. The caller needs to build this
5784/// set based on the context using, e.g.,
5785/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5786/// set should not contain any member functions; those will be added
5787/// by CreateOverloadedUnaryOp().
5788///
5789/// \param input The input argument.
5790Sema::OwningExprResult
5791Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5792                              const UnresolvedSetImpl &Fns,
5793                              ExprArg input) {
5794  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5795  Expr *Input = (Expr *)input.get();
5796
5797  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5798  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5799  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5800
5801  Expr *Args[2] = { Input, 0 };
5802  unsigned NumArgs = 1;
5803
5804  // For post-increment and post-decrement, add the implicit '0' as
5805  // the second argument, so that we know this is a post-increment or
5806  // post-decrement.
5807  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5808    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
5809    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
5810                                           SourceLocation());
5811    NumArgs = 2;
5812  }
5813
5814  if (Input->isTypeDependent()) {
5815    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
5816    UnresolvedLookupExpr *Fn
5817      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
5818                                     0, SourceRange(), OpName, OpLoc,
5819                                     /*ADL*/ true, IsOverloaded(Fns));
5820    Fn->addDecls(Fns.begin(), Fns.end());
5821
5822    input.release();
5823    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5824                                                   &Args[0], NumArgs,
5825                                                   Context.DependentTy,
5826                                                   OpLoc));
5827  }
5828
5829  // Build an empty overload set.
5830  OverloadCandidateSet CandidateSet(OpLoc);
5831
5832  // Add the candidates from the given function set.
5833  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
5834
5835  // Add operator candidates that are member functions.
5836  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5837
5838  // Add candidates from ADL.
5839  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5840                                       Args, NumArgs,
5841                                       /*ExplicitTemplateArgs*/ 0,
5842                                       CandidateSet);
5843
5844  // Add builtin operator candidates.
5845  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5846
5847  // Perform overload resolution.
5848  OverloadCandidateSet::iterator Best;
5849  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5850  case OR_Success: {
5851    // We found a built-in operator or an overloaded operator.
5852    FunctionDecl *FnDecl = Best->Function;
5853
5854    if (FnDecl) {
5855      // We matched an overloaded operator. Build a call to that
5856      // operator.
5857
5858      // Convert the arguments.
5859      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5860        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
5861
5862        if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5863                                                Best->FoundDecl, Method))
5864          return ExprError();
5865      } else {
5866        // Convert the arguments.
5867        OwningExprResult InputInit
5868          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5869                                                      FnDecl->getParamDecl(0)),
5870                                      SourceLocation(),
5871                                      move(input));
5872        if (InputInit.isInvalid())
5873          return ExprError();
5874
5875        input = move(InputInit);
5876        Input = (Expr *)input.get();
5877      }
5878
5879      // Determine the result type
5880      QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
5881
5882      // Build the actual expression node.
5883      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5884                                               SourceLocation());
5885      UsualUnaryConversions(FnExpr);
5886
5887      input.release();
5888      Args[0] = Input;
5889      ExprOwningPtr<CallExpr> TheCall(this,
5890        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5891                                          Args, NumArgs, ResultTy, OpLoc));
5892
5893      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5894                              FnDecl))
5895        return ExprError();
5896
5897      return MaybeBindToTemporary(TheCall.release());
5898    } else {
5899      // We matched a built-in operator. Convert the arguments, then
5900      // break out so that we will build the appropriate built-in
5901      // operator node.
5902        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
5903                                      Best->Conversions[0], AA_Passing))
5904          return ExprError();
5905
5906        break;
5907      }
5908    }
5909
5910    case OR_No_Viable_Function:
5911      // No viable function; fall through to handling this as a
5912      // built-in operator, which will produce an error message for us.
5913      break;
5914
5915    case OR_Ambiguous:
5916      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5917          << UnaryOperator::getOpcodeStr(Opc)
5918          << Input->getSourceRange();
5919      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
5920                              UnaryOperator::getOpcodeStr(Opc), OpLoc);
5921      return ExprError();
5922
5923    case OR_Deleted:
5924      Diag(OpLoc, diag::err_ovl_deleted_oper)
5925        << Best->Function->isDeleted()
5926        << UnaryOperator::getOpcodeStr(Opc)
5927        << Input->getSourceRange();
5928      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
5929      return ExprError();
5930    }
5931
5932  // Either we found no viable overloaded operator or we matched a
5933  // built-in operator. In either case, fall through to trying to
5934  // build a built-in operation.
5935  input.release();
5936  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5937}
5938
5939/// \brief Create a binary operation that may resolve to an overloaded
5940/// operator.
5941///
5942/// \param OpLoc The location of the operator itself (e.g., '+').
5943///
5944/// \param OpcIn The BinaryOperator::Opcode that describes this
5945/// operator.
5946///
5947/// \param Functions The set of non-member functions that will be
5948/// considered by overload resolution. The caller needs to build this
5949/// set based on the context using, e.g.,
5950/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5951/// set should not contain any member functions; those will be added
5952/// by CreateOverloadedBinOp().
5953///
5954/// \param LHS Left-hand argument.
5955/// \param RHS Right-hand argument.
5956Sema::OwningExprResult
5957Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
5958                            unsigned OpcIn,
5959                            const UnresolvedSetImpl &Fns,
5960                            Expr *LHS, Expr *RHS) {
5961  Expr *Args[2] = { LHS, RHS };
5962  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
5963
5964  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5965  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5966  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5967
5968  // If either side is type-dependent, create an appropriate dependent
5969  // expression.
5970  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5971    if (Fns.empty()) {
5972      // If there are no functions to store, just build a dependent
5973      // BinaryOperator or CompoundAssignment.
5974      if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5975        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5976                                                  Context.DependentTy, OpLoc));
5977
5978      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5979                                                        Context.DependentTy,
5980                                                        Context.DependentTy,
5981                                                        Context.DependentTy,
5982                                                        OpLoc));
5983    }
5984
5985    // FIXME: save results of ADL from here?
5986    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
5987    UnresolvedLookupExpr *Fn
5988      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
5989                                     0, SourceRange(), OpName, OpLoc,
5990                                     /*ADL*/ true, IsOverloaded(Fns));
5991
5992    Fn->addDecls(Fns.begin(), Fns.end());
5993    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5994                                                   Args, 2,
5995                                                   Context.DependentTy,
5996                                                   OpLoc));
5997  }
5998
5999  // If this is the .* operator, which is not overloadable, just
6000  // create a built-in binary operator.
6001  if (Opc == BinaryOperator::PtrMemD)
6002    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
6003
6004  // If this is the assignment operator, we only perform overload resolution
6005  // if the left-hand side is a class or enumeration type. This is actually
6006  // a hack. The standard requires that we do overload resolution between the
6007  // various built-in candidates, but as DR507 points out, this can lead to
6008  // problems. So we do it this way, which pretty much follows what GCC does.
6009  // Note that we go the traditional code path for compound assignment forms.
6010  if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
6011    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
6012
6013  // Build an empty overload set.
6014  OverloadCandidateSet CandidateSet(OpLoc);
6015
6016  // Add the candidates from the given function set.
6017  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
6018
6019  // Add operator candidates that are member functions.
6020  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6021
6022  // Add candidates from ADL.
6023  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6024                                       Args, 2,
6025                                       /*ExplicitTemplateArgs*/ 0,
6026                                       CandidateSet);
6027
6028  // Add builtin operator candidates.
6029  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6030
6031  // Perform overload resolution.
6032  OverloadCandidateSet::iterator Best;
6033  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
6034    case OR_Success: {
6035      // We found a built-in operator or an overloaded operator.
6036      FunctionDecl *FnDecl = Best->Function;
6037
6038      if (FnDecl) {
6039        // We matched an overloaded operator. Build a call to that
6040        // operator.
6041
6042        // Convert the arguments.
6043        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
6044          // Best->Access is only meaningful for class members.
6045          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
6046
6047          OwningExprResult Arg1
6048            = PerformCopyInitialization(
6049                                        InitializedEntity::InitializeParameter(
6050                                                        FnDecl->getParamDecl(0)),
6051                                        SourceLocation(),
6052                                        Owned(Args[1]));
6053          if (Arg1.isInvalid())
6054            return ExprError();
6055
6056          if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
6057                                                  Best->FoundDecl, Method))
6058            return ExprError();
6059
6060          Args[1] = RHS = Arg1.takeAs<Expr>();
6061        } else {
6062          // Convert the arguments.
6063          OwningExprResult Arg0
6064            = PerformCopyInitialization(
6065                                        InitializedEntity::InitializeParameter(
6066                                                        FnDecl->getParamDecl(0)),
6067                                        SourceLocation(),
6068                                        Owned(Args[0]));
6069          if (Arg0.isInvalid())
6070            return ExprError();
6071
6072          OwningExprResult Arg1
6073            = PerformCopyInitialization(
6074                                        InitializedEntity::InitializeParameter(
6075                                                        FnDecl->getParamDecl(1)),
6076                                        SourceLocation(),
6077                                        Owned(Args[1]));
6078          if (Arg1.isInvalid())
6079            return ExprError();
6080          Args[0] = LHS = Arg0.takeAs<Expr>();
6081          Args[1] = RHS = Arg1.takeAs<Expr>();
6082        }
6083
6084        // Determine the result type
6085        QualType ResultTy
6086          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6087        ResultTy = ResultTy.getNonReferenceType();
6088
6089        // Build the actual expression node.
6090        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6091                                                 OpLoc);
6092        UsualUnaryConversions(FnExpr);
6093
6094        ExprOwningPtr<CXXOperatorCallExpr>
6095          TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6096                                                          Args, 2, ResultTy,
6097                                                          OpLoc));
6098
6099        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6100                                FnDecl))
6101          return ExprError();
6102
6103        return MaybeBindToTemporary(TheCall.release());
6104      } else {
6105        // We matched a built-in operator. Convert the arguments, then
6106        // break out so that we will build the appropriate built-in
6107        // operator node.
6108        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
6109                                      Best->Conversions[0], AA_Passing) ||
6110            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
6111                                      Best->Conversions[1], AA_Passing))
6112          return ExprError();
6113
6114        break;
6115      }
6116    }
6117
6118    case OR_No_Viable_Function: {
6119      // C++ [over.match.oper]p9:
6120      //   If the operator is the operator , [...] and there are no
6121      //   viable functions, then the operator is assumed to be the
6122      //   built-in operator and interpreted according to clause 5.
6123      if (Opc == BinaryOperator::Comma)
6124        break;
6125
6126      // For class as left operand for assignment or compound assigment operator
6127      // do not fall through to handling in built-in, but report that no overloaded
6128      // assignment operator found
6129      OwningExprResult Result = ExprError();
6130      if (Args[0]->getType()->isRecordType() &&
6131          Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
6132        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
6133             << BinaryOperator::getOpcodeStr(Opc)
6134             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6135      } else {
6136        // No viable function; try to create a built-in operation, which will
6137        // produce an error. Then, show the non-viable candidates.
6138        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
6139      }
6140      assert(Result.isInvalid() &&
6141             "C++ binary operator overloading is missing candidates!");
6142      if (Result.isInvalid())
6143        PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
6144                                BinaryOperator::getOpcodeStr(Opc), OpLoc);
6145      return move(Result);
6146    }
6147
6148    case OR_Ambiguous:
6149      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
6150          << BinaryOperator::getOpcodeStr(Opc)
6151          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6152      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
6153                              BinaryOperator::getOpcodeStr(Opc), OpLoc);
6154      return ExprError();
6155
6156    case OR_Deleted:
6157      Diag(OpLoc, diag::err_ovl_deleted_oper)
6158        << Best->Function->isDeleted()
6159        << BinaryOperator::getOpcodeStr(Opc)
6160        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6161      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
6162      return ExprError();
6163  }
6164
6165  // We matched a built-in operator; build it.
6166  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
6167}
6168
6169Action::OwningExprResult
6170Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6171                                         SourceLocation RLoc,
6172                                         ExprArg Base, ExprArg Idx) {
6173  Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6174                    static_cast<Expr*>(Idx.get()) };
6175  DeclarationName OpName =
6176      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6177
6178  // If either side is type-dependent, create an appropriate dependent
6179  // expression.
6180  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6181
6182    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
6183    UnresolvedLookupExpr *Fn
6184      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
6185                                     0, SourceRange(), OpName, LLoc,
6186                                     /*ADL*/ true, /*Overloaded*/ false);
6187    // Can't add any actual overloads yet
6188
6189    Base.release();
6190    Idx.release();
6191    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6192                                                   Args, 2,
6193                                                   Context.DependentTy,
6194                                                   RLoc));
6195  }
6196
6197  // Build an empty overload set.
6198  OverloadCandidateSet CandidateSet(LLoc);
6199
6200  // Subscript can only be overloaded as a member function.
6201
6202  // Add operator candidates that are member functions.
6203  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6204
6205  // Add builtin operator candidates.
6206  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6207
6208  // Perform overload resolution.
6209  OverloadCandidateSet::iterator Best;
6210  switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6211    case OR_Success: {
6212      // We found a built-in operator or an overloaded operator.
6213      FunctionDecl *FnDecl = Best->Function;
6214
6215      if (FnDecl) {
6216        // We matched an overloaded operator. Build a call to that
6217        // operator.
6218
6219        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
6220
6221        // Convert the arguments.
6222        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
6223        if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
6224                                                Best->FoundDecl, Method))
6225          return ExprError();
6226
6227        // Convert the arguments.
6228        OwningExprResult InputInit
6229          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6230                                                      FnDecl->getParamDecl(0)),
6231                                      SourceLocation(),
6232                                      Owned(Args[1]));
6233        if (InputInit.isInvalid())
6234          return ExprError();
6235
6236        Args[1] = InputInit.takeAs<Expr>();
6237
6238        // Determine the result type
6239        QualType ResultTy
6240          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6241        ResultTy = ResultTy.getNonReferenceType();
6242
6243        // Build the actual expression node.
6244        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6245                                                 LLoc);
6246        UsualUnaryConversions(FnExpr);
6247
6248        Base.release();
6249        Idx.release();
6250        ExprOwningPtr<CXXOperatorCallExpr>
6251          TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6252                                                          FnExpr, Args, 2,
6253                                                          ResultTy, RLoc));
6254
6255        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6256                                FnDecl))
6257          return ExprError();
6258
6259        return MaybeBindToTemporary(TheCall.release());
6260      } else {
6261        // We matched a built-in operator. Convert the arguments, then
6262        // break out so that we will build the appropriate built-in
6263        // operator node.
6264        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
6265                                      Best->Conversions[0], AA_Passing) ||
6266            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
6267                                      Best->Conversions[1], AA_Passing))
6268          return ExprError();
6269
6270        break;
6271      }
6272    }
6273
6274    case OR_No_Viable_Function: {
6275      if (CandidateSet.empty())
6276        Diag(LLoc, diag::err_ovl_no_oper)
6277          << Args[0]->getType() << /*subscript*/ 0
6278          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6279      else
6280        Diag(LLoc, diag::err_ovl_no_viable_subscript)
6281          << Args[0]->getType()
6282          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6283      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
6284                              "[]", LLoc);
6285      return ExprError();
6286    }
6287
6288    case OR_Ambiguous:
6289      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
6290          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6291      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
6292                              "[]", LLoc);
6293      return ExprError();
6294
6295    case OR_Deleted:
6296      Diag(LLoc, diag::err_ovl_deleted_oper)
6297        << Best->Function->isDeleted() << "[]"
6298        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6299      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
6300                              "[]", LLoc);
6301      return ExprError();
6302    }
6303
6304  // We matched a built-in operator; build it.
6305  Base.release();
6306  Idx.release();
6307  return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6308                                         Owned(Args[1]), RLoc);
6309}
6310
6311/// BuildCallToMemberFunction - Build a call to a member
6312/// function. MemExpr is the expression that refers to the member
6313/// function (and includes the object parameter), Args/NumArgs are the
6314/// arguments to the function call (not including the object
6315/// parameter). The caller needs to validate that the member
6316/// expression refers to a member function or an overloaded member
6317/// function.
6318Sema::OwningExprResult
6319Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6320                                SourceLocation LParenLoc, Expr **Args,
6321                                unsigned NumArgs, SourceLocation *CommaLocs,
6322                                SourceLocation RParenLoc) {
6323  // Dig out the member expression. This holds both the object
6324  // argument and the member function we're referring to.
6325  Expr *NakedMemExpr = MemExprE->IgnoreParens();
6326
6327  MemberExpr *MemExpr;
6328  CXXMethodDecl *Method = 0;
6329  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
6330  NestedNameSpecifier *Qualifier = 0;
6331  if (isa<MemberExpr>(NakedMemExpr)) {
6332    MemExpr = cast<MemberExpr>(NakedMemExpr);
6333    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6334    FoundDecl = MemExpr->getFoundDecl();
6335    Qualifier = MemExpr->getQualifier();
6336  } else {
6337    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
6338    Qualifier = UnresExpr->getQualifier();
6339
6340    QualType ObjectType = UnresExpr->getBaseType();
6341
6342    // Add overload candidates
6343    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
6344
6345    // FIXME: avoid copy.
6346    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6347    if (UnresExpr->hasExplicitTemplateArgs()) {
6348      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6349      TemplateArgs = &TemplateArgsBuffer;
6350    }
6351
6352    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6353           E = UnresExpr->decls_end(); I != E; ++I) {
6354
6355      NamedDecl *Func = *I;
6356      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6357      if (isa<UsingShadowDecl>(Func))
6358        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6359
6360      if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
6361        // If explicit template arguments were provided, we can't call a
6362        // non-template member function.
6363        if (TemplateArgs)
6364          continue;
6365
6366        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
6367                           Args, NumArgs,
6368                           CandidateSet, /*SuppressUserConversions=*/false);
6369      } else {
6370        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
6371                                   I.getPair(), ActingDC, TemplateArgs,
6372                                   ObjectType, Args, NumArgs,
6373                                   CandidateSet,
6374                                   /*SuppressUsedConversions=*/false);
6375      }
6376    }
6377
6378    DeclarationName DeclName = UnresExpr->getMemberName();
6379
6380    OverloadCandidateSet::iterator Best;
6381    switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
6382    case OR_Success:
6383      Method = cast<CXXMethodDecl>(Best->Function);
6384      FoundDecl = Best->FoundDecl;
6385      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
6386      break;
6387
6388    case OR_No_Viable_Function:
6389      Diag(UnresExpr->getMemberLoc(),
6390           diag::err_ovl_no_viable_member_function_in_call)
6391        << DeclName << MemExprE->getSourceRange();
6392      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6393      // FIXME: Leaking incoming expressions!
6394      return ExprError();
6395
6396    case OR_Ambiguous:
6397      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
6398        << DeclName << MemExprE->getSourceRange();
6399      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6400      // FIXME: Leaking incoming expressions!
6401      return ExprError();
6402
6403    case OR_Deleted:
6404      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
6405        << Best->Function->isDeleted()
6406        << DeclName << MemExprE->getSourceRange();
6407      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6408      // FIXME: Leaking incoming expressions!
6409      return ExprError();
6410    }
6411
6412    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
6413
6414    // If overload resolution picked a static member, build a
6415    // non-member call based on that function.
6416    if (Method->isStatic()) {
6417      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6418                                   Args, NumArgs, RParenLoc);
6419    }
6420
6421    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
6422  }
6423
6424  assert(Method && "Member call to something that isn't a method?");
6425  ExprOwningPtr<CXXMemberCallExpr>
6426    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
6427                                                  NumArgs,
6428                                  Method->getResultType().getNonReferenceType(),
6429                                  RParenLoc));
6430
6431  // Check for a valid return type.
6432  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6433                          TheCall.get(), Method))
6434    return ExprError();
6435
6436  // Convert the object argument (for a non-static member function call).
6437  // We only need to do this if there was actually an overload; otherwise
6438  // it was done at lookup.
6439  Expr *ObjectArg = MemExpr->getBase();
6440  if (!Method->isStatic() &&
6441      PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6442                                          FoundDecl, Method))
6443    return ExprError();
6444  MemExpr->setBase(ObjectArg);
6445
6446  // Convert the rest of the arguments
6447  const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
6448  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
6449                              RParenLoc))
6450    return ExprError();
6451
6452  if (CheckFunctionCall(Method, TheCall.get()))
6453    return ExprError();
6454
6455  return MaybeBindToTemporary(TheCall.release());
6456}
6457
6458/// BuildCallToObjectOfClassType - Build a call to an object of class
6459/// type (C++ [over.call.object]), which can end up invoking an
6460/// overloaded function call operator (@c operator()) or performing a
6461/// user-defined conversion on the object argument.
6462Sema::ExprResult
6463Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
6464                                   SourceLocation LParenLoc,
6465                                   Expr **Args, unsigned NumArgs,
6466                                   SourceLocation *CommaLocs,
6467                                   SourceLocation RParenLoc) {
6468  assert(Object->getType()->isRecordType() && "Requires object type argument");
6469  const RecordType *Record = Object->getType()->getAs<RecordType>();
6470
6471  // C++ [over.call.object]p1:
6472  //  If the primary-expression E in the function call syntax
6473  //  evaluates to a class object of type "cv T", then the set of
6474  //  candidate functions includes at least the function call
6475  //  operators of T. The function call operators of T are obtained by
6476  //  ordinary lookup of the name operator() in the context of
6477  //  (E).operator().
6478  OverloadCandidateSet CandidateSet(LParenLoc);
6479  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
6480
6481  if (RequireCompleteType(LParenLoc, Object->getType(),
6482                          PDiag(diag::err_incomplete_object_call)
6483                          << Object->getSourceRange()))
6484    return true;
6485
6486  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6487  LookupQualifiedName(R, Record->getDecl());
6488  R.suppressDiagnostics();
6489
6490  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
6491       Oper != OperEnd; ++Oper) {
6492    AddMethodCandidate(Oper.getPair(), Object->getType(),
6493                       Args, NumArgs, CandidateSet,
6494                       /*SuppressUserConversions=*/ false);
6495  }
6496
6497  // C++ [over.call.object]p2:
6498  //   In addition, for each conversion function declared in T of the
6499  //   form
6500  //
6501  //        operator conversion-type-id () cv-qualifier;
6502  //
6503  //   where cv-qualifier is the same cv-qualification as, or a
6504  //   greater cv-qualification than, cv, and where conversion-type-id
6505  //   denotes the type "pointer to function of (P1,...,Pn) returning
6506  //   R", or the type "reference to pointer to function of
6507  //   (P1,...,Pn) returning R", or the type "reference to function
6508  //   of (P1,...,Pn) returning R", a surrogate call function [...]
6509  //   is also considered as a candidate function. Similarly,
6510  //   surrogate call functions are added to the set of candidate
6511  //   functions for each conversion function declared in an
6512  //   accessible base class provided the function is not hidden
6513  //   within T by another intervening declaration.
6514  const UnresolvedSetImpl *Conversions
6515    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
6516  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6517         E = Conversions->end(); I != E; ++I) {
6518    NamedDecl *D = *I;
6519    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6520    if (isa<UsingShadowDecl>(D))
6521      D = cast<UsingShadowDecl>(D)->getTargetDecl();
6522
6523    // Skip over templated conversion functions; they aren't
6524    // surrogates.
6525    if (isa<FunctionTemplateDecl>(D))
6526      continue;
6527
6528    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6529
6530    // Strip the reference type (if any) and then the pointer type (if
6531    // any) to get down to what might be a function type.
6532    QualType ConvType = Conv->getConversionType().getNonReferenceType();
6533    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6534      ConvType = ConvPtrType->getPointeeType();
6535
6536    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
6537      AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
6538                            Object->getType(), Args, NumArgs,
6539                            CandidateSet);
6540  }
6541
6542  // Perform overload resolution.
6543  OverloadCandidateSet::iterator Best;
6544  switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
6545  case OR_Success:
6546    // Overload resolution succeeded; we'll build the appropriate call
6547    // below.
6548    break;
6549
6550  case OR_No_Viable_Function:
6551    if (CandidateSet.empty())
6552      Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6553        << Object->getType() << /*call*/ 1
6554        << Object->getSourceRange();
6555    else
6556      Diag(Object->getSourceRange().getBegin(),
6557           diag::err_ovl_no_viable_object_call)
6558        << Object->getType() << Object->getSourceRange();
6559    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6560    break;
6561
6562  case OR_Ambiguous:
6563    Diag(Object->getSourceRange().getBegin(),
6564         diag::err_ovl_ambiguous_object_call)
6565      << Object->getType() << Object->getSourceRange();
6566    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
6567    break;
6568
6569  case OR_Deleted:
6570    Diag(Object->getSourceRange().getBegin(),
6571         diag::err_ovl_deleted_object_call)
6572      << Best->Function->isDeleted()
6573      << Object->getType() << Object->getSourceRange();
6574    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6575    break;
6576  }
6577
6578  if (Best == CandidateSet.end()) {
6579    // We had an error; delete all of the subexpressions and return
6580    // the error.
6581    Object->Destroy(Context);
6582    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6583      Args[ArgIdx]->Destroy(Context);
6584    return true;
6585  }
6586
6587  if (Best->Function == 0) {
6588    // Since there is no function declaration, this is one of the
6589    // surrogate candidates. Dig out the conversion function.
6590    CXXConversionDecl *Conv
6591      = cast<CXXConversionDecl>(
6592                         Best->Conversions[0].UserDefined.ConversionFunction);
6593
6594    CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
6595
6596    // We selected one of the surrogate functions that converts the
6597    // object parameter to a function pointer. Perform the conversion
6598    // on the object argument, then let ActOnCallExpr finish the job.
6599
6600    // Create an implicit member expr to refer to the conversion operator.
6601    // and then call it.
6602    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6603                                                   Conv);
6604
6605    return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
6606                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6607                         CommaLocs, RParenLoc).result();
6608  }
6609
6610  CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
6611
6612  // We found an overloaded operator(). Build a CXXOperatorCallExpr
6613  // that calls this method, using Object for the implicit object
6614  // parameter and passing along the remaining arguments.
6615  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
6616  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
6617
6618  unsigned NumArgsInProto = Proto->getNumArgs();
6619  unsigned NumArgsToCheck = NumArgs;
6620
6621  // Build the full argument list for the method call (the
6622  // implicit object parameter is placed at the beginning of the
6623  // list).
6624  Expr **MethodArgs;
6625  if (NumArgs < NumArgsInProto) {
6626    NumArgsToCheck = NumArgsInProto;
6627    MethodArgs = new Expr*[NumArgsInProto + 1];
6628  } else {
6629    MethodArgs = new Expr*[NumArgs + 1];
6630  }
6631  MethodArgs[0] = Object;
6632  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6633    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
6634
6635  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
6636                                          SourceLocation());
6637  UsualUnaryConversions(NewFn);
6638
6639  // Once we've built TheCall, all of the expressions are properly
6640  // owned.
6641  QualType ResultTy = Method->getResultType().getNonReferenceType();
6642  ExprOwningPtr<CXXOperatorCallExpr>
6643    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
6644                                                    MethodArgs, NumArgs + 1,
6645                                                    ResultTy, RParenLoc));
6646  delete [] MethodArgs;
6647
6648  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6649                          Method))
6650    return true;
6651
6652  // We may have default arguments. If so, we need to allocate more
6653  // slots in the call for them.
6654  if (NumArgs < NumArgsInProto)
6655    TheCall->setNumArgs(Context, NumArgsInProto + 1);
6656  else if (NumArgs > NumArgsInProto)
6657    NumArgsToCheck = NumArgsInProto;
6658
6659  bool IsError = false;
6660
6661  // Initialize the implicit object parameter.
6662  IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
6663                                                 Best->FoundDecl, Method);
6664  TheCall->setArg(0, Object);
6665
6666
6667  // Check the argument types.
6668  for (unsigned i = 0; i != NumArgsToCheck; i++) {
6669    Expr *Arg;
6670    if (i < NumArgs) {
6671      Arg = Args[i];
6672
6673      // Pass the argument.
6674
6675      OwningExprResult InputInit
6676        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6677                                                    Method->getParamDecl(i)),
6678                                    SourceLocation(), Owned(Arg));
6679
6680      IsError |= InputInit.isInvalid();
6681      Arg = InputInit.takeAs<Expr>();
6682    } else {
6683      OwningExprResult DefArg
6684        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6685      if (DefArg.isInvalid()) {
6686        IsError = true;
6687        break;
6688      }
6689
6690      Arg = DefArg.takeAs<Expr>();
6691    }
6692
6693    TheCall->setArg(i + 1, Arg);
6694  }
6695
6696  // If this is a variadic call, handle args passed through "...".
6697  if (Proto->isVariadic()) {
6698    // Promote the arguments (C99 6.5.2.2p7).
6699    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6700      Expr *Arg = Args[i];
6701      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
6702      TheCall->setArg(i + 1, Arg);
6703    }
6704  }
6705
6706  if (IsError) return true;
6707
6708  if (CheckFunctionCall(Method, TheCall.get()))
6709    return true;
6710
6711  return MaybeBindToTemporary(TheCall.release()).result();
6712}
6713
6714/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
6715///  (if one exists), where @c Base is an expression of class type and
6716/// @c Member is the name of the member we're trying to find.
6717Sema::OwningExprResult
6718Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6719  Expr *Base = static_cast<Expr *>(BaseIn.get());
6720  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
6721
6722  SourceLocation Loc = Base->getExprLoc();
6723
6724  // C++ [over.ref]p1:
6725  //
6726  //   [...] An expression x->m is interpreted as (x.operator->())->m
6727  //   for a class object x of type T if T::operator->() exists and if
6728  //   the operator is selected as the best match function by the
6729  //   overload resolution mechanism (13.3).
6730  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6731  OverloadCandidateSet CandidateSet(Loc);
6732  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
6733
6734  if (RequireCompleteType(Loc, Base->getType(),
6735                          PDiag(diag::err_typecheck_incomplete_tag)
6736                            << Base->getSourceRange()))
6737    return ExprError();
6738
6739  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6740  LookupQualifiedName(R, BaseRecord->getDecl());
6741  R.suppressDiagnostics();
6742
6743  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
6744       Oper != OperEnd; ++Oper) {
6745    AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
6746                       /*SuppressUserConversions=*/false);
6747  }
6748
6749  // Perform overload resolution.
6750  OverloadCandidateSet::iterator Best;
6751  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
6752  case OR_Success:
6753    // Overload resolution succeeded; we'll build the call below.
6754    break;
6755
6756  case OR_No_Viable_Function:
6757    if (CandidateSet.empty())
6758      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6759        << Base->getType() << Base->getSourceRange();
6760    else
6761      Diag(OpLoc, diag::err_ovl_no_viable_oper)
6762        << "operator->" << Base->getSourceRange();
6763    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
6764    return ExprError();
6765
6766  case OR_Ambiguous:
6767    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
6768      << "->" << Base->getSourceRange();
6769    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
6770    return ExprError();
6771
6772  case OR_Deleted:
6773    Diag(OpLoc,  diag::err_ovl_deleted_oper)
6774      << Best->Function->isDeleted()
6775      << "->" << Base->getSourceRange();
6776    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
6777    return ExprError();
6778  }
6779
6780  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6781
6782  // Convert the object parameter.
6783  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
6784  if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6785                                          Best->FoundDecl, Method))
6786    return ExprError();
6787
6788  // No concerns about early exits now.
6789  BaseIn.release();
6790
6791  // Build the operator call.
6792  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6793                                           SourceLocation());
6794  UsualUnaryConversions(FnExpr);
6795
6796  QualType ResultTy = Method->getResultType().getNonReferenceType();
6797  ExprOwningPtr<CXXOperatorCallExpr>
6798    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6799                                                    &Base, 1, ResultTy, OpLoc));
6800
6801  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6802                          Method))
6803          return ExprError();
6804  return move(TheCall);
6805}
6806
6807/// FixOverloadedFunctionReference - E is an expression that refers to
6808/// a C++ overloaded function (possibly with some parentheses and
6809/// perhaps a '&' around it). We have resolved the overloaded function
6810/// to the function declaration Fn, so patch up the expression E to
6811/// refer (possibly indirectly) to Fn. Returns the new expr.
6812Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
6813                                           FunctionDecl *Fn) {
6814  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6815    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6816                                                   Found, Fn);
6817    if (SubExpr == PE->getSubExpr())
6818      return PE->Retain();
6819
6820    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6821  }
6822
6823  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6824    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6825                                                   Found, Fn);
6826    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
6827                               SubExpr->getType()) &&
6828           "Implicit cast type cannot be determined from overload");
6829    if (SubExpr == ICE->getSubExpr())
6830      return ICE->Retain();
6831
6832    return new (Context) ImplicitCastExpr(ICE->getType(),
6833                                          ICE->getCastKind(),
6834                                          SubExpr,
6835                                          ICE->isLvalueCast());
6836  }
6837
6838  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
6839    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
6840           "Can only take the address of an overloaded function");
6841    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6842      if (Method->isStatic()) {
6843        // Do nothing: static member functions aren't any different
6844        // from non-member functions.
6845      } else {
6846        // Fix the sub expression, which really has to be an
6847        // UnresolvedLookupExpr holding an overloaded member function
6848        // or template.
6849        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6850                                                       Found, Fn);
6851        if (SubExpr == UnOp->getSubExpr())
6852          return UnOp->Retain();
6853
6854        assert(isa<DeclRefExpr>(SubExpr)
6855               && "fixed to something other than a decl ref");
6856        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6857               && "fixed to a member ref with no nested name qualifier");
6858
6859        // We have taken the address of a pointer to member
6860        // function. Perform the computation here so that we get the
6861        // appropriate pointer to member type.
6862        QualType ClassType
6863          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6864        QualType MemPtrType
6865          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6866
6867        return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6868                                           MemPtrType, UnOp->getOperatorLoc());
6869      }
6870    }
6871    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6872                                                   Found, Fn);
6873    if (SubExpr == UnOp->getSubExpr())
6874      return UnOp->Retain();
6875
6876    return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6877                                     Context.getPointerType(SubExpr->getType()),
6878                                       UnOp->getOperatorLoc());
6879  }
6880
6881  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
6882    // FIXME: avoid copy.
6883    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6884    if (ULE->hasExplicitTemplateArgs()) {
6885      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6886      TemplateArgs = &TemplateArgsBuffer;
6887    }
6888
6889    return DeclRefExpr::Create(Context,
6890                               ULE->getQualifier(),
6891                               ULE->getQualifierRange(),
6892                               Fn,
6893                               ULE->getNameLoc(),
6894                               Fn->getType(),
6895                               TemplateArgs);
6896  }
6897
6898  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
6899    // FIXME: avoid copy.
6900    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6901    if (MemExpr->hasExplicitTemplateArgs()) {
6902      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6903      TemplateArgs = &TemplateArgsBuffer;
6904    }
6905
6906    Expr *Base;
6907
6908    // If we're filling in
6909    if (MemExpr->isImplicitAccess()) {
6910      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6911        return DeclRefExpr::Create(Context,
6912                                   MemExpr->getQualifier(),
6913                                   MemExpr->getQualifierRange(),
6914                                   Fn,
6915                                   MemExpr->getMemberLoc(),
6916                                   Fn->getType(),
6917                                   TemplateArgs);
6918      } else {
6919        SourceLocation Loc = MemExpr->getMemberLoc();
6920        if (MemExpr->getQualifier())
6921          Loc = MemExpr->getQualifierRange().getBegin();
6922        Base = new (Context) CXXThisExpr(Loc,
6923                                         MemExpr->getBaseType(),
6924                                         /*isImplicit=*/true);
6925      }
6926    } else
6927      Base = MemExpr->getBase()->Retain();
6928
6929    return MemberExpr::Create(Context, Base,
6930                              MemExpr->isArrow(),
6931                              MemExpr->getQualifier(),
6932                              MemExpr->getQualifierRange(),
6933                              Fn,
6934                              Found,
6935                              MemExpr->getMemberLoc(),
6936                              TemplateArgs,
6937                              Fn->getType());
6938  }
6939
6940  assert(false && "Invalid reference to overloaded function");
6941  return E->Retain();
6942}
6943
6944Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6945                                                          DeclAccessPair Found,
6946                                                            FunctionDecl *Fn) {
6947  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
6948}
6949
6950} // end namespace clang
6951