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