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