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