SemaOverload.cpp revision 3b6133ecd2c20761beaa8747be05aeed4376380c
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>(D)))
1586          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1587        else
1588          Conv = cast<CXXConversionDecl>(D);
1589
1590        if (AllowExplicit || !Conv->isExplicit()) {
1591          if (ConvTemplate)
1592            AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
1593                                           ActingContext, From, ToType,
1594                                           CandidateSet);
1595          else
1596            AddConversionCandidate(Conv, FoundDecl, ActingContext,
1597                                   From, ToType, CandidateSet);
1598        }
1599      }
1600    }
1601  }
1602
1603  OverloadCandidateSet::iterator Best;
1604  switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1605    case OR_Success:
1606      // Record the standard conversion we used and the conversion function.
1607      if (CXXConstructorDecl *Constructor
1608            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1609        // C++ [over.ics.user]p1:
1610        //   If the user-defined conversion is specified by a
1611        //   constructor (12.3.1), the initial standard conversion
1612        //   sequence converts the source type to the type required by
1613        //   the argument of the constructor.
1614        //
1615        QualType ThisType = Constructor->getThisType(Context);
1616        if (Best->Conversions[0].isEllipsis())
1617          User.EllipsisConversion = true;
1618        else {
1619          User.Before = Best->Conversions[0].Standard;
1620          User.EllipsisConversion = false;
1621        }
1622        User.ConversionFunction = Constructor;
1623        User.After.setAsIdentityConversion();
1624        User.After.setFromType(
1625          ThisType->getAs<PointerType>()->getPointeeType());
1626        User.After.setAllToTypes(ToType);
1627        return OR_Success;
1628      } else if (CXXConversionDecl *Conversion
1629                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1630        // C++ [over.ics.user]p1:
1631        //
1632        //   [...] If the user-defined conversion is specified by a
1633        //   conversion function (12.3.2), the initial standard
1634        //   conversion sequence converts the source type to the
1635        //   implicit object parameter of the conversion function.
1636        User.Before = Best->Conversions[0].Standard;
1637        User.ConversionFunction = Conversion;
1638        User.EllipsisConversion = false;
1639
1640        // C++ [over.ics.user]p2:
1641        //   The second standard conversion sequence converts the
1642        //   result of the user-defined conversion to the target type
1643        //   for the sequence. Since an implicit conversion sequence
1644        //   is an initialization, the special rules for
1645        //   initialization by user-defined conversion apply when
1646        //   selecting the best user-defined conversion for a
1647        //   user-defined conversion sequence (see 13.3.3 and
1648        //   13.3.3.1).
1649        User.After = Best->FinalConversion;
1650        return OR_Success;
1651      } else {
1652        assert(false && "Not a constructor or conversion function?");
1653        return OR_No_Viable_Function;
1654      }
1655
1656    case OR_No_Viable_Function:
1657      return OR_No_Viable_Function;
1658    case OR_Deleted:
1659      // No conversion here! We're done.
1660      return OR_Deleted;
1661
1662    case OR_Ambiguous:
1663      return OR_Ambiguous;
1664    }
1665
1666  return OR_No_Viable_Function;
1667}
1668
1669bool
1670Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
1671  ImplicitConversionSequence ICS;
1672  OverloadCandidateSet CandidateSet(From->getExprLoc());
1673  OverloadingResult OvResult =
1674    IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1675                            CandidateSet, true, false, false);
1676  if (OvResult == OR_Ambiguous)
1677    Diag(From->getSourceRange().getBegin(),
1678         diag::err_typecheck_ambiguous_condition)
1679          << From->getType() << ToType << From->getSourceRange();
1680  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1681    Diag(From->getSourceRange().getBegin(),
1682         diag::err_typecheck_nonviable_condition)
1683    << From->getType() << ToType << From->getSourceRange();
1684  else
1685    return false;
1686  PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
1687  return true;
1688}
1689
1690/// CompareImplicitConversionSequences - Compare two implicit
1691/// conversion sequences to determine whether one is better than the
1692/// other or if they are indistinguishable (C++ 13.3.3.2).
1693ImplicitConversionSequence::CompareKind
1694Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1695                                         const ImplicitConversionSequence& ICS2)
1696{
1697  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1698  // conversion sequences (as defined in 13.3.3.1)
1699  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1700  //      conversion sequence than a user-defined conversion sequence or
1701  //      an ellipsis conversion sequence, and
1702  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1703  //      conversion sequence than an ellipsis conversion sequence
1704  //      (13.3.3.1.3).
1705  //
1706  // C++0x [over.best.ics]p10:
1707  //   For the purpose of ranking implicit conversion sequences as
1708  //   described in 13.3.3.2, the ambiguous conversion sequence is
1709  //   treated as a user-defined sequence that is indistinguishable
1710  //   from any other user-defined conversion sequence.
1711  if (ICS1.getKind() < ICS2.getKind()) {
1712    if (!(ICS1.isUserDefined() && ICS2.isAmbiguous()))
1713      return ImplicitConversionSequence::Better;
1714  } else if (ICS2.getKind() < ICS1.getKind()) {
1715    if (!(ICS2.isUserDefined() && ICS1.isAmbiguous()))
1716      return ImplicitConversionSequence::Worse;
1717  }
1718
1719  if (ICS1.isAmbiguous() || ICS2.isAmbiguous())
1720    return ImplicitConversionSequence::Indistinguishable;
1721
1722  // Two implicit conversion sequences of the same form are
1723  // indistinguishable conversion sequences unless one of the
1724  // following rules apply: (C++ 13.3.3.2p3):
1725  if (ICS1.isStandard())
1726    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1727  else if (ICS1.isUserDefined()) {
1728    // User-defined conversion sequence U1 is a better conversion
1729    // sequence than another user-defined conversion sequence U2 if
1730    // they contain the same user-defined conversion function or
1731    // constructor and if the second standard conversion sequence of
1732    // U1 is better than the second standard conversion sequence of
1733    // U2 (C++ 13.3.3.2p3).
1734    if (ICS1.UserDefined.ConversionFunction ==
1735          ICS2.UserDefined.ConversionFunction)
1736      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1737                                                ICS2.UserDefined.After);
1738  }
1739
1740  return ImplicitConversionSequence::Indistinguishable;
1741}
1742
1743// Per 13.3.3.2p3, compare the given standard conversion sequences to
1744// determine if one is a proper subset of the other.
1745static ImplicitConversionSequence::CompareKind
1746compareStandardConversionSubsets(ASTContext &Context,
1747                                 const StandardConversionSequence& SCS1,
1748                                 const StandardConversionSequence& SCS2) {
1749  ImplicitConversionSequence::CompareKind Result
1750    = ImplicitConversionSequence::Indistinguishable;
1751
1752  if (SCS1.Second != SCS2.Second) {
1753    if (SCS1.Second == ICK_Identity)
1754      Result = ImplicitConversionSequence::Better;
1755    else if (SCS2.Second == ICK_Identity)
1756      Result = ImplicitConversionSequence::Worse;
1757    else
1758      return ImplicitConversionSequence::Indistinguishable;
1759  } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
1760    return ImplicitConversionSequence::Indistinguishable;
1761
1762  if (SCS1.Third == SCS2.Third) {
1763    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
1764                             : ImplicitConversionSequence::Indistinguishable;
1765  }
1766
1767  if (SCS1.Third == ICK_Identity)
1768    return Result == ImplicitConversionSequence::Worse
1769             ? ImplicitConversionSequence::Indistinguishable
1770             : ImplicitConversionSequence::Better;
1771
1772  if (SCS2.Third == ICK_Identity)
1773    return Result == ImplicitConversionSequence::Better
1774             ? ImplicitConversionSequence::Indistinguishable
1775             : ImplicitConversionSequence::Worse;
1776
1777  return ImplicitConversionSequence::Indistinguishable;
1778}
1779
1780/// CompareStandardConversionSequences - Compare two standard
1781/// conversion sequences to determine whether one is better than the
1782/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1783ImplicitConversionSequence::CompareKind
1784Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1785                                         const StandardConversionSequence& SCS2)
1786{
1787  // Standard conversion sequence S1 is a better conversion sequence
1788  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1789
1790  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1791  //     sequences in the canonical form defined by 13.3.3.1.1,
1792  //     excluding any Lvalue Transformation; the identity conversion
1793  //     sequence is considered to be a subsequence of any
1794  //     non-identity conversion sequence) or, if not that,
1795  if (ImplicitConversionSequence::CompareKind CK
1796        = compareStandardConversionSubsets(Context, SCS1, SCS2))
1797    return CK;
1798
1799  //  -- the rank of S1 is better than the rank of S2 (by the rules
1800  //     defined below), or, if not that,
1801  ImplicitConversionRank Rank1 = SCS1.getRank();
1802  ImplicitConversionRank Rank2 = SCS2.getRank();
1803  if (Rank1 < Rank2)
1804    return ImplicitConversionSequence::Better;
1805  else if (Rank2 < Rank1)
1806    return ImplicitConversionSequence::Worse;
1807
1808  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1809  // are indistinguishable unless one of the following rules
1810  // applies:
1811
1812  //   A conversion that is not a conversion of a pointer, or
1813  //   pointer to member, to bool is better than another conversion
1814  //   that is such a conversion.
1815  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1816    return SCS2.isPointerConversionToBool()
1817             ? ImplicitConversionSequence::Better
1818             : ImplicitConversionSequence::Worse;
1819
1820  // C++ [over.ics.rank]p4b2:
1821  //
1822  //   If class B is derived directly or indirectly from class A,
1823  //   conversion of B* to A* is better than conversion of B* to
1824  //   void*, and conversion of A* to void* is better than conversion
1825  //   of B* to void*.
1826  bool SCS1ConvertsToVoid
1827    = SCS1.isPointerConversionToVoidPointer(Context);
1828  bool SCS2ConvertsToVoid
1829    = SCS2.isPointerConversionToVoidPointer(Context);
1830  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1831    // Exactly one of the conversion sequences is a conversion to
1832    // a void pointer; it's the worse conversion.
1833    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1834                              : ImplicitConversionSequence::Worse;
1835  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1836    // Neither conversion sequence converts to a void pointer; compare
1837    // their derived-to-base conversions.
1838    if (ImplicitConversionSequence::CompareKind DerivedCK
1839          = CompareDerivedToBaseConversions(SCS1, SCS2))
1840      return DerivedCK;
1841  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1842    // Both conversion sequences are conversions to void
1843    // pointers. Compare the source types to determine if there's an
1844    // inheritance relationship in their sources.
1845    QualType FromType1 = SCS1.getFromType();
1846    QualType FromType2 = SCS2.getFromType();
1847
1848    // Adjust the types we're converting from via the array-to-pointer
1849    // conversion, if we need to.
1850    if (SCS1.First == ICK_Array_To_Pointer)
1851      FromType1 = Context.getArrayDecayedType(FromType1);
1852    if (SCS2.First == ICK_Array_To_Pointer)
1853      FromType2 = Context.getArrayDecayedType(FromType2);
1854
1855    QualType FromPointee1
1856      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1857    QualType FromPointee2
1858      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1859
1860    if (IsDerivedFrom(FromPointee2, FromPointee1))
1861      return ImplicitConversionSequence::Better;
1862    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1863      return ImplicitConversionSequence::Worse;
1864
1865    // Objective-C++: If one interface is more specific than the
1866    // other, it is the better one.
1867    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1868    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1869    if (FromIface1 && FromIface1) {
1870      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1871        return ImplicitConversionSequence::Better;
1872      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1873        return ImplicitConversionSequence::Worse;
1874    }
1875  }
1876
1877  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1878  // bullet 3).
1879  if (ImplicitConversionSequence::CompareKind QualCK
1880        = CompareQualificationConversions(SCS1, SCS2))
1881    return QualCK;
1882
1883  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1884    // C++0x [over.ics.rank]p3b4:
1885    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1886    //      implicit object parameter of a non-static member function declared
1887    //      without a ref-qualifier, and S1 binds an rvalue reference to an
1888    //      rvalue and S2 binds an lvalue reference.
1889    // FIXME: We don't know if we're dealing with the implicit object parameter,
1890    // or if the member function in this case has a ref qualifier.
1891    // (Of course, we don't have ref qualifiers yet.)
1892    if (SCS1.RRefBinding != SCS2.RRefBinding)
1893      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1894                              : ImplicitConversionSequence::Worse;
1895
1896    // C++ [over.ics.rank]p3b4:
1897    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1898    //      which the references refer are the same type except for
1899    //      top-level cv-qualifiers, and the type to which the reference
1900    //      initialized by S2 refers is more cv-qualified than the type
1901    //      to which the reference initialized by S1 refers.
1902    QualType T1 = SCS1.getToType(2);
1903    QualType T2 = SCS2.getToType(2);
1904    T1 = Context.getCanonicalType(T1);
1905    T2 = Context.getCanonicalType(T2);
1906    Qualifiers T1Quals, T2Quals;
1907    QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1908    QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1909    if (UnqualT1 == UnqualT2) {
1910      // If the type is an array type, promote the element qualifiers to the type
1911      // for comparison.
1912      if (isa<ArrayType>(T1) && T1Quals)
1913        T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1914      if (isa<ArrayType>(T2) && T2Quals)
1915        T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1916      if (T2.isMoreQualifiedThan(T1))
1917        return ImplicitConversionSequence::Better;
1918      else if (T1.isMoreQualifiedThan(T2))
1919        return ImplicitConversionSequence::Worse;
1920    }
1921  }
1922
1923  return ImplicitConversionSequence::Indistinguishable;
1924}
1925
1926/// CompareQualificationConversions - Compares two standard conversion
1927/// sequences to determine whether they can be ranked based on their
1928/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1929ImplicitConversionSequence::CompareKind
1930Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1931                                      const StandardConversionSequence& SCS2) {
1932  // C++ 13.3.3.2p3:
1933  //  -- S1 and S2 differ only in their qualification conversion and
1934  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1935  //     cv-qualification signature of type T1 is a proper subset of
1936  //     the cv-qualification signature of type T2, and S1 is not the
1937  //     deprecated string literal array-to-pointer conversion (4.2).
1938  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1939      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1940    return ImplicitConversionSequence::Indistinguishable;
1941
1942  // FIXME: the example in the standard doesn't use a qualification
1943  // conversion (!)
1944  QualType T1 = SCS1.getToType(2);
1945  QualType T2 = SCS2.getToType(2);
1946  T1 = Context.getCanonicalType(T1);
1947  T2 = Context.getCanonicalType(T2);
1948  Qualifiers T1Quals, T2Quals;
1949  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
1950  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
1951
1952  // If the types are the same, we won't learn anything by unwrapped
1953  // them.
1954  if (UnqualT1 == UnqualT2)
1955    return ImplicitConversionSequence::Indistinguishable;
1956
1957  // If the type is an array type, promote the element qualifiers to the type
1958  // for comparison.
1959  if (isa<ArrayType>(T1) && T1Quals)
1960    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
1961  if (isa<ArrayType>(T2) && T2Quals)
1962    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
1963
1964  ImplicitConversionSequence::CompareKind Result
1965    = ImplicitConversionSequence::Indistinguishable;
1966  while (UnwrapSimilarPointerTypes(T1, T2)) {
1967    // Within each iteration of the loop, we check the qualifiers to
1968    // determine if this still looks like a qualification
1969    // conversion. Then, if all is well, we unwrap one more level of
1970    // pointers or pointers-to-members and do it all again
1971    // until there are no more pointers or pointers-to-members left
1972    // to unwrap. This essentially mimics what
1973    // IsQualificationConversion does, but here we're checking for a
1974    // strict subset of qualifiers.
1975    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1976      // The qualifiers are the same, so this doesn't tell us anything
1977      // about how the sequences rank.
1978      ;
1979    else if (T2.isMoreQualifiedThan(T1)) {
1980      // T1 has fewer qualifiers, so it could be the better sequence.
1981      if (Result == ImplicitConversionSequence::Worse)
1982        // Neither has qualifiers that are a subset of the other's
1983        // qualifiers.
1984        return ImplicitConversionSequence::Indistinguishable;
1985
1986      Result = ImplicitConversionSequence::Better;
1987    } else if (T1.isMoreQualifiedThan(T2)) {
1988      // T2 has fewer qualifiers, so it could be the better sequence.
1989      if (Result == ImplicitConversionSequence::Better)
1990        // Neither has qualifiers that are a subset of the other's
1991        // qualifiers.
1992        return ImplicitConversionSequence::Indistinguishable;
1993
1994      Result = ImplicitConversionSequence::Worse;
1995    } else {
1996      // Qualifiers are disjoint.
1997      return ImplicitConversionSequence::Indistinguishable;
1998    }
1999
2000    // If the types after this point are equivalent, we're done.
2001    if (Context.hasSameUnqualifiedType(T1, T2))
2002      break;
2003  }
2004
2005  // Check that the winning standard conversion sequence isn't using
2006  // the deprecated string literal array to pointer conversion.
2007  switch (Result) {
2008  case ImplicitConversionSequence::Better:
2009    if (SCS1.DeprecatedStringLiteralToCharPtr)
2010      Result = ImplicitConversionSequence::Indistinguishable;
2011    break;
2012
2013  case ImplicitConversionSequence::Indistinguishable:
2014    break;
2015
2016  case ImplicitConversionSequence::Worse:
2017    if (SCS2.DeprecatedStringLiteralToCharPtr)
2018      Result = ImplicitConversionSequence::Indistinguishable;
2019    break;
2020  }
2021
2022  return Result;
2023}
2024
2025/// CompareDerivedToBaseConversions - Compares two standard conversion
2026/// sequences to determine whether they can be ranked based on their
2027/// various kinds of derived-to-base conversions (C++
2028/// [over.ics.rank]p4b3).  As part of these checks, we also look at
2029/// conversions between Objective-C interface types.
2030ImplicitConversionSequence::CompareKind
2031Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2032                                      const StandardConversionSequence& SCS2) {
2033  QualType FromType1 = SCS1.getFromType();
2034  QualType ToType1 = SCS1.getToType(1);
2035  QualType FromType2 = SCS2.getFromType();
2036  QualType ToType2 = SCS2.getToType(1);
2037
2038  // Adjust the types we're converting from via the array-to-pointer
2039  // conversion, if we need to.
2040  if (SCS1.First == ICK_Array_To_Pointer)
2041    FromType1 = Context.getArrayDecayedType(FromType1);
2042  if (SCS2.First == ICK_Array_To_Pointer)
2043    FromType2 = Context.getArrayDecayedType(FromType2);
2044
2045  // Canonicalize all of the types.
2046  FromType1 = Context.getCanonicalType(FromType1);
2047  ToType1 = Context.getCanonicalType(ToType1);
2048  FromType2 = Context.getCanonicalType(FromType2);
2049  ToType2 = Context.getCanonicalType(ToType2);
2050
2051  // C++ [over.ics.rank]p4b3:
2052  //
2053  //   If class B is derived directly or indirectly from class A and
2054  //   class C is derived directly or indirectly from B,
2055  //
2056  // For Objective-C, we let A, B, and C also be Objective-C
2057  // interfaces.
2058
2059  // Compare based on pointer conversions.
2060  if (SCS1.Second == ICK_Pointer_Conversion &&
2061      SCS2.Second == ICK_Pointer_Conversion &&
2062      /*FIXME: Remove if Objective-C id conversions get their own rank*/
2063      FromType1->isPointerType() && FromType2->isPointerType() &&
2064      ToType1->isPointerType() && ToType2->isPointerType()) {
2065    QualType FromPointee1
2066      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2067    QualType ToPointee1
2068      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2069    QualType FromPointee2
2070      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2071    QualType ToPointee2
2072      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2073
2074    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2075    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2076    const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2077    const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
2078
2079    //   -- conversion of C* to B* is better than conversion of C* to A*,
2080    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2081      if (IsDerivedFrom(ToPointee1, ToPointee2))
2082        return ImplicitConversionSequence::Better;
2083      else if (IsDerivedFrom(ToPointee2, ToPointee1))
2084        return ImplicitConversionSequence::Worse;
2085
2086      if (ToIface1 && ToIface2) {
2087        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2088          return ImplicitConversionSequence::Better;
2089        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2090          return ImplicitConversionSequence::Worse;
2091      }
2092    }
2093
2094    //   -- conversion of B* to A* is better than conversion of C* to A*,
2095    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2096      if (IsDerivedFrom(FromPointee2, FromPointee1))
2097        return ImplicitConversionSequence::Better;
2098      else if (IsDerivedFrom(FromPointee1, FromPointee2))
2099        return ImplicitConversionSequence::Worse;
2100
2101      if (FromIface1 && FromIface2) {
2102        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2103          return ImplicitConversionSequence::Better;
2104        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2105          return ImplicitConversionSequence::Worse;
2106      }
2107    }
2108  }
2109
2110  // Ranking of member-pointer types.
2111  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2112      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2113      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2114    const MemberPointerType * FromMemPointer1 =
2115                                        FromType1->getAs<MemberPointerType>();
2116    const MemberPointerType * ToMemPointer1 =
2117                                          ToType1->getAs<MemberPointerType>();
2118    const MemberPointerType * FromMemPointer2 =
2119                                          FromType2->getAs<MemberPointerType>();
2120    const MemberPointerType * ToMemPointer2 =
2121                                          ToType2->getAs<MemberPointerType>();
2122    const Type *FromPointeeType1 = FromMemPointer1->getClass();
2123    const Type *ToPointeeType1 = ToMemPointer1->getClass();
2124    const Type *FromPointeeType2 = FromMemPointer2->getClass();
2125    const Type *ToPointeeType2 = ToMemPointer2->getClass();
2126    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2127    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2128    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2129    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
2130    // conversion of A::* to B::* is better than conversion of A::* to C::*,
2131    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2132      if (IsDerivedFrom(ToPointee1, ToPointee2))
2133        return ImplicitConversionSequence::Worse;
2134      else if (IsDerivedFrom(ToPointee2, ToPointee1))
2135        return ImplicitConversionSequence::Better;
2136    }
2137    // conversion of B::* to C::* is better than conversion of A::* to C::*
2138    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2139      if (IsDerivedFrom(FromPointee1, FromPointee2))
2140        return ImplicitConversionSequence::Better;
2141      else if (IsDerivedFrom(FromPointee2, FromPointee1))
2142        return ImplicitConversionSequence::Worse;
2143    }
2144  }
2145
2146  if ((SCS1.ReferenceBinding || SCS1.CopyConstructor) &&
2147      (SCS2.ReferenceBinding || SCS2.CopyConstructor) &&
2148      SCS1.Second == ICK_Derived_To_Base) {
2149    //   -- conversion of C to B is better than conversion of C to A,
2150    //   -- binding of an expression of type C to a reference of type
2151    //      B& is better than binding an expression of type C to a
2152    //      reference of type A&,
2153    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2154        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2155      if (IsDerivedFrom(ToType1, ToType2))
2156        return ImplicitConversionSequence::Better;
2157      else if (IsDerivedFrom(ToType2, ToType1))
2158        return ImplicitConversionSequence::Worse;
2159    }
2160
2161    //   -- conversion of B to A is better than conversion of C to A.
2162    //   -- binding of an expression of type B to a reference of type
2163    //      A& is better than binding an expression of type C to a
2164    //      reference of type A&,
2165    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2166        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2167      if (IsDerivedFrom(FromType2, FromType1))
2168        return ImplicitConversionSequence::Better;
2169      else if (IsDerivedFrom(FromType1, FromType2))
2170        return ImplicitConversionSequence::Worse;
2171    }
2172  }
2173
2174  return ImplicitConversionSequence::Indistinguishable;
2175}
2176
2177/// 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
2823    // C++ [over.ics.user]p3:
2824    //   If the user-defined conversion is specified by a specialization of a
2825    //   conversion function template, the second standard conversion sequence
2826    //   shall have exact match rank.
2827    if (Conversion->getPrimaryTemplate() &&
2828        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
2829      Candidate.Viable = false;
2830      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
2831    }
2832
2833    break;
2834
2835  case ImplicitConversionSequence::BadConversion:
2836    Candidate.Viable = false;
2837    Candidate.FailureKind = ovl_fail_bad_final_conversion;
2838    break;
2839
2840  default:
2841    assert(false &&
2842           "Can only end up with a standard conversion sequence or failure");
2843  }
2844}
2845
2846/// \brief Adds a conversion function template specialization
2847/// candidate to the overload set, using template argument deduction
2848/// to deduce the template arguments of the conversion function
2849/// template from the type that we are converting to (C++
2850/// [temp.deduct.conv]).
2851void
2852Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2853                                     DeclAccessPair FoundDecl,
2854                                     CXXRecordDecl *ActingDC,
2855                                     Expr *From, QualType ToType,
2856                                     OverloadCandidateSet &CandidateSet) {
2857  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2858         "Only conversion function templates permitted here");
2859
2860  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2861    return;
2862
2863  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
2864  CXXConversionDecl *Specialization = 0;
2865  if (TemplateDeductionResult Result
2866        = DeduceTemplateArguments(FunctionTemplate, ToType,
2867                                  Specialization, Info)) {
2868    // FIXME: Record what happened with template argument deduction, so
2869    // that we can give the user a beautiful diagnostic.
2870    (void)Result;
2871    return;
2872  }
2873
2874  // Add the conversion function template specialization produced by
2875  // template argument deduction as a candidate.
2876  assert(Specialization && "Missing function template specialization?");
2877  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
2878                         CandidateSet);
2879}
2880
2881/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2882/// converts the given @c Object to a function pointer via the
2883/// conversion function @c Conversion, and then attempts to call it
2884/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2885/// the type of function that we'll eventually be calling.
2886void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2887                                 DeclAccessPair FoundDecl,
2888                                 CXXRecordDecl *ActingContext,
2889                                 const FunctionProtoType *Proto,
2890                                 QualType ObjectType,
2891                                 Expr **Args, unsigned NumArgs,
2892                                 OverloadCandidateSet& CandidateSet) {
2893  if (!CandidateSet.isNewCandidate(Conversion))
2894    return;
2895
2896  // Overload resolution is always an unevaluated context.
2897  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2898
2899  CandidateSet.push_back(OverloadCandidate());
2900  OverloadCandidate& Candidate = CandidateSet.back();
2901  Candidate.FoundDecl = FoundDecl;
2902  Candidate.Function = 0;
2903  Candidate.Surrogate = Conversion;
2904  Candidate.Viable = true;
2905  Candidate.IsSurrogate = true;
2906  Candidate.IgnoreObjectArgument = false;
2907  Candidate.Conversions.resize(NumArgs + 1);
2908
2909  // Determine the implicit conversion sequence for the implicit
2910  // object parameter.
2911  ImplicitConversionSequence ObjectInit
2912    = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
2913  if (ObjectInit.isBad()) {
2914    Candidate.Viable = false;
2915    Candidate.FailureKind = ovl_fail_bad_conversion;
2916    Candidate.Conversions[0] = ObjectInit;
2917    return;
2918  }
2919
2920  // The first conversion is actually a user-defined conversion whose
2921  // first conversion is ObjectInit's standard conversion (which is
2922  // effectively a reference binding). Record it as such.
2923  Candidate.Conversions[0].setUserDefined();
2924  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2925  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
2926  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2927  Candidate.Conversions[0].UserDefined.After
2928    = Candidate.Conversions[0].UserDefined.Before;
2929  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2930
2931  // Find the
2932  unsigned NumArgsInProto = Proto->getNumArgs();
2933
2934  // (C++ 13.3.2p2): A candidate function having fewer than m
2935  // parameters is viable only if it has an ellipsis in its parameter
2936  // list (8.3.5).
2937  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2938    Candidate.Viable = false;
2939    Candidate.FailureKind = ovl_fail_too_many_arguments;
2940    return;
2941  }
2942
2943  // Function types don't have any default arguments, so just check if
2944  // we have enough arguments.
2945  if (NumArgs < NumArgsInProto) {
2946    // Not enough arguments.
2947    Candidate.Viable = false;
2948    Candidate.FailureKind = ovl_fail_too_few_arguments;
2949    return;
2950  }
2951
2952  // Determine the implicit conversion sequences for each of the
2953  // arguments.
2954  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2955    if (ArgIdx < NumArgsInProto) {
2956      // (C++ 13.3.2p3): for F to be a viable function, there shall
2957      // exist for each argument an implicit conversion sequence
2958      // (13.3.3.1) that converts that argument to the corresponding
2959      // parameter of F.
2960      QualType ParamType = Proto->getArgType(ArgIdx);
2961      Candidate.Conversions[ArgIdx + 1]
2962        = TryCopyInitialization(Args[ArgIdx], ParamType,
2963                                /*SuppressUserConversions=*/false,
2964                                /*ForceRValue=*/false,
2965                                /*InOverloadResolution=*/false);
2966      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
2967        Candidate.Viable = false;
2968        Candidate.FailureKind = ovl_fail_bad_conversion;
2969        break;
2970      }
2971    } else {
2972      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2973      // argument for which there is no corresponding parameter is
2974      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2975      Candidate.Conversions[ArgIdx + 1].setEllipsis();
2976    }
2977  }
2978}
2979
2980// FIXME: This will eventually be removed, once we've migrated all of the
2981// operator overloading logic over to the scheme used by binary operators, which
2982// works for template instantiation.
2983void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2984                                 SourceLocation OpLoc,
2985                                 Expr **Args, unsigned NumArgs,
2986                                 OverloadCandidateSet& CandidateSet,
2987                                 SourceRange OpRange) {
2988  UnresolvedSet<16> Fns;
2989
2990  QualType T1 = Args[0]->getType();
2991  QualType T2;
2992  if (NumArgs > 1)
2993    T2 = Args[1]->getType();
2994
2995  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2996  if (S)
2997    LookupOverloadedOperatorName(Op, S, T1, T2, Fns);
2998  AddFunctionCandidates(Fns, Args, NumArgs, CandidateSet, false);
2999  AddArgumentDependentLookupCandidates(OpName, false, Args, NumArgs, 0,
3000                                       CandidateSet);
3001  AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
3002  AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
3003}
3004
3005/// \brief Add overload candidates for overloaded operators that are
3006/// member functions.
3007///
3008/// Add the overloaded operator candidates that are member functions
3009/// for the operator Op that was used in an operator expression such
3010/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3011/// CandidateSet will store the added overload candidates. (C++
3012/// [over.match.oper]).
3013void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3014                                       SourceLocation OpLoc,
3015                                       Expr **Args, unsigned NumArgs,
3016                                       OverloadCandidateSet& CandidateSet,
3017                                       SourceRange OpRange) {
3018  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3019
3020  // C++ [over.match.oper]p3:
3021  //   For a unary operator @ with an operand of a type whose
3022  //   cv-unqualified version is T1, and for a binary operator @ with
3023  //   a left operand of a type whose cv-unqualified version is T1 and
3024  //   a right operand of a type whose cv-unqualified version is T2,
3025  //   three sets of candidate functions, designated member
3026  //   candidates, non-member candidates and built-in candidates, are
3027  //   constructed as follows:
3028  QualType T1 = Args[0]->getType();
3029  QualType T2;
3030  if (NumArgs > 1)
3031    T2 = Args[1]->getType();
3032
3033  //     -- If T1 is a class type, the set of member candidates is the
3034  //        result of the qualified lookup of T1::operator@
3035  //        (13.3.1.1.1); otherwise, the set of member candidates is
3036  //        empty.
3037  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
3038    // Complete the type if it can be completed. Otherwise, we're done.
3039    if (RequireCompleteType(OpLoc, T1, PDiag()))
3040      return;
3041
3042    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3043    LookupQualifiedName(Operators, T1Rec->getDecl());
3044    Operators.suppressDiagnostics();
3045
3046    for (LookupResult::iterator Oper = Operators.begin(),
3047                             OperEnd = Operators.end();
3048         Oper != OperEnd;
3049         ++Oper)
3050      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
3051                         Args + 1, NumArgs - 1, CandidateSet,
3052                         /* SuppressUserConversions = */ false);
3053  }
3054}
3055
3056/// AddBuiltinCandidate - Add a candidate for a built-in
3057/// operator. ResultTy and ParamTys are the result and parameter types
3058/// of the built-in candidate, respectively. Args and NumArgs are the
3059/// arguments being passed to the candidate. IsAssignmentOperator
3060/// should be true when this built-in candidate is an assignment
3061/// operator. NumContextualBoolArguments is the number of arguments
3062/// (at the beginning of the argument list) that will be contextually
3063/// converted to bool.
3064void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
3065                               Expr **Args, unsigned NumArgs,
3066                               OverloadCandidateSet& CandidateSet,
3067                               bool IsAssignmentOperator,
3068                               unsigned NumContextualBoolArguments) {
3069  // Overload resolution is always an unevaluated context.
3070  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3071
3072  // Add this candidate
3073  CandidateSet.push_back(OverloadCandidate());
3074  OverloadCandidate& Candidate = CandidateSet.back();
3075  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
3076  Candidate.Function = 0;
3077  Candidate.IsSurrogate = false;
3078  Candidate.IgnoreObjectArgument = false;
3079  Candidate.BuiltinTypes.ResultTy = ResultTy;
3080  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3081    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3082
3083  // Determine the implicit conversion sequences for each of the
3084  // arguments.
3085  Candidate.Viable = true;
3086  Candidate.Conversions.resize(NumArgs);
3087  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3088    // C++ [over.match.oper]p4:
3089    //   For the built-in assignment operators, conversions of the
3090    //   left operand are restricted as follows:
3091    //     -- no temporaries are introduced to hold the left operand, and
3092    //     -- no user-defined conversions are applied to the left
3093    //        operand to achieve a type match with the left-most
3094    //        parameter of a built-in candidate.
3095    //
3096    // We block these conversions by turning off user-defined
3097    // conversions, since that is the only way that initialization of
3098    // a reference to a non-class type can occur from something that
3099    // is not of the same type.
3100    if (ArgIdx < NumContextualBoolArguments) {
3101      assert(ParamTys[ArgIdx] == Context.BoolTy &&
3102             "Contextual conversion to bool requires bool type");
3103      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3104    } else {
3105      Candidate.Conversions[ArgIdx]
3106        = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
3107                                ArgIdx == 0 && IsAssignmentOperator,
3108                                /*ForceRValue=*/false,
3109                                /*InOverloadResolution=*/false);
3110    }
3111    if (Candidate.Conversions[ArgIdx].isBad()) {
3112      Candidate.Viable = false;
3113      Candidate.FailureKind = ovl_fail_bad_conversion;
3114      break;
3115    }
3116  }
3117}
3118
3119/// BuiltinCandidateTypeSet - A set of types that will be used for the
3120/// candidate operator functions for built-in operators (C++
3121/// [over.built]). The types are separated into pointer types and
3122/// enumeration types.
3123class BuiltinCandidateTypeSet  {
3124  /// TypeSet - A set of types.
3125  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
3126
3127  /// PointerTypes - The set of pointer types that will be used in the
3128  /// built-in candidates.
3129  TypeSet PointerTypes;
3130
3131  /// MemberPointerTypes - The set of member pointer types that will be
3132  /// used in the built-in candidates.
3133  TypeSet MemberPointerTypes;
3134
3135  /// EnumerationTypes - The set of enumeration types that will be
3136  /// used in the built-in candidates.
3137  TypeSet EnumerationTypes;
3138
3139  /// Sema - The semantic analysis instance where we are building the
3140  /// candidate type set.
3141  Sema &SemaRef;
3142
3143  /// Context - The AST context in which we will build the type sets.
3144  ASTContext &Context;
3145
3146  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3147                                               const Qualifiers &VisibleQuals);
3148  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
3149
3150public:
3151  /// iterator - Iterates through the types that are part of the set.
3152  typedef TypeSet::iterator iterator;
3153
3154  BuiltinCandidateTypeSet(Sema &SemaRef)
3155    : SemaRef(SemaRef), Context(SemaRef.Context) { }
3156
3157  void AddTypesConvertedFrom(QualType Ty,
3158                             SourceLocation Loc,
3159                             bool AllowUserConversions,
3160                             bool AllowExplicitConversions,
3161                             const Qualifiers &VisibleTypeConversionsQuals);
3162
3163  /// pointer_begin - First pointer type found;
3164  iterator pointer_begin() { return PointerTypes.begin(); }
3165
3166  /// pointer_end - Past the last pointer type found;
3167  iterator pointer_end() { return PointerTypes.end(); }
3168
3169  /// member_pointer_begin - First member pointer type found;
3170  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3171
3172  /// member_pointer_end - Past the last member pointer type found;
3173  iterator member_pointer_end() { return MemberPointerTypes.end(); }
3174
3175  /// enumeration_begin - First enumeration type found;
3176  iterator enumeration_begin() { return EnumerationTypes.begin(); }
3177
3178  /// enumeration_end - Past the last enumeration type found;
3179  iterator enumeration_end() { return EnumerationTypes.end(); }
3180};
3181
3182/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
3183/// the set of pointer types along with any more-qualified variants of
3184/// that type. For example, if @p Ty is "int const *", this routine
3185/// will add "int const *", "int const volatile *", "int const
3186/// restrict *", and "int const volatile restrict *" to the set of
3187/// pointer types. Returns true if the add of @p Ty itself succeeded,
3188/// false otherwise.
3189///
3190/// FIXME: what to do about extended qualifiers?
3191bool
3192BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3193                                             const Qualifiers &VisibleQuals) {
3194
3195  // Insert this type.
3196  if (!PointerTypes.insert(Ty))
3197    return false;
3198
3199  const PointerType *PointerTy = Ty->getAs<PointerType>();
3200  assert(PointerTy && "type was not a pointer type!");
3201
3202  QualType PointeeTy = PointerTy->getPointeeType();
3203  // Don't add qualified variants of arrays. For one, they're not allowed
3204  // (the qualifier would sink to the element type), and for another, the
3205  // only overload situation where it matters is subscript or pointer +- int,
3206  // and those shouldn't have qualifier variants anyway.
3207  if (PointeeTy->isArrayType())
3208    return true;
3209  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3210  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
3211    BaseCVR = Array->getElementType().getCVRQualifiers();
3212  bool hasVolatile = VisibleQuals.hasVolatile();
3213  bool hasRestrict = VisibleQuals.hasRestrict();
3214
3215  // Iterate through all strict supersets of BaseCVR.
3216  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3217    if ((CVR | BaseCVR) != CVR) continue;
3218    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3219    // in the types.
3220    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3221    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
3222    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3223    PointerTypes.insert(Context.getPointerType(QPointeeTy));
3224  }
3225
3226  return true;
3227}
3228
3229/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3230/// to the set of pointer types along with any more-qualified variants of
3231/// that type. For example, if @p Ty is "int const *", this routine
3232/// will add "int const *", "int const volatile *", "int const
3233/// restrict *", and "int const volatile restrict *" to the set of
3234/// pointer types. Returns true if the add of @p Ty itself succeeded,
3235/// false otherwise.
3236///
3237/// FIXME: what to do about extended qualifiers?
3238bool
3239BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3240    QualType Ty) {
3241  // Insert this type.
3242  if (!MemberPointerTypes.insert(Ty))
3243    return false;
3244
3245  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3246  assert(PointerTy && "type was not a member pointer type!");
3247
3248  QualType PointeeTy = PointerTy->getPointeeType();
3249  // Don't add qualified variants of arrays. For one, they're not allowed
3250  // (the qualifier would sink to the element type), and for another, the
3251  // only overload situation where it matters is subscript or pointer +- int,
3252  // and those shouldn't have qualifier variants anyway.
3253  if (PointeeTy->isArrayType())
3254    return true;
3255  const Type *ClassTy = PointerTy->getClass();
3256
3257  // Iterate through all strict supersets of the pointee type's CVR
3258  // qualifiers.
3259  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3260  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3261    if ((CVR | BaseCVR) != CVR) continue;
3262
3263    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3264    MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
3265  }
3266
3267  return true;
3268}
3269
3270/// AddTypesConvertedFrom - Add each of the types to which the type @p
3271/// Ty can be implicit converted to the given set of @p Types. We're
3272/// primarily interested in pointer types and enumeration types. We also
3273/// take member pointer types, for the conditional operator.
3274/// AllowUserConversions is true if we should look at the conversion
3275/// functions of a class type, and AllowExplicitConversions if we
3276/// should also include the explicit conversion functions of a class
3277/// type.
3278void
3279BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
3280                                               SourceLocation Loc,
3281                                               bool AllowUserConversions,
3282                                               bool AllowExplicitConversions,
3283                                               const Qualifiers &VisibleQuals) {
3284  // Only deal with canonical types.
3285  Ty = Context.getCanonicalType(Ty);
3286
3287  // Look through reference types; they aren't part of the type of an
3288  // expression for the purposes of conversions.
3289  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
3290    Ty = RefTy->getPointeeType();
3291
3292  // We don't care about qualifiers on the type.
3293  Ty = Ty.getLocalUnqualifiedType();
3294
3295  // If we're dealing with an array type, decay to the pointer.
3296  if (Ty->isArrayType())
3297    Ty = SemaRef.Context.getArrayDecayedType(Ty);
3298
3299  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
3300    QualType PointeeTy = PointerTy->getPointeeType();
3301
3302    // Insert our type, and its more-qualified variants, into the set
3303    // of types.
3304    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
3305      return;
3306  } else if (Ty->isMemberPointerType()) {
3307    // Member pointers are far easier, since the pointee can't be converted.
3308    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3309      return;
3310  } else if (Ty->isEnumeralType()) {
3311    EnumerationTypes.insert(Ty);
3312  } else if (AllowUserConversions) {
3313    if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
3314      if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
3315        // No conversion functions in incomplete types.
3316        return;
3317      }
3318
3319      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3320      const UnresolvedSetImpl *Conversions
3321        = ClassDecl->getVisibleConversionFunctions();
3322      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3323             E = Conversions->end(); I != E; ++I) {
3324        NamedDecl *D = I.getDecl();
3325        if (isa<UsingShadowDecl>(D))
3326          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3327
3328        // Skip conversion function templates; they don't tell us anything
3329        // about which builtin types we can convert to.
3330        if (isa<FunctionTemplateDecl>(D))
3331          continue;
3332
3333        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
3334        if (AllowExplicitConversions || !Conv->isExplicit()) {
3335          AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
3336                                VisibleQuals);
3337        }
3338      }
3339    }
3340  }
3341}
3342
3343/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3344/// the volatile- and non-volatile-qualified assignment operators for the
3345/// given type to the candidate set.
3346static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3347                                                   QualType T,
3348                                                   Expr **Args,
3349                                                   unsigned NumArgs,
3350                                    OverloadCandidateSet &CandidateSet) {
3351  QualType ParamTypes[2];
3352
3353  // T& operator=(T&, T)
3354  ParamTypes[0] = S.Context.getLValueReferenceType(T);
3355  ParamTypes[1] = T;
3356  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3357                        /*IsAssignmentOperator=*/true);
3358
3359  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3360    // volatile T& operator=(volatile T&, T)
3361    ParamTypes[0]
3362      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
3363    ParamTypes[1] = T;
3364    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3365                          /*IsAssignmentOperator=*/true);
3366  }
3367}
3368
3369/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3370/// if any, found in visible type conversion functions found in ArgExpr's type.
3371static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3372    Qualifiers VRQuals;
3373    const RecordType *TyRec;
3374    if (const MemberPointerType *RHSMPType =
3375        ArgExpr->getType()->getAs<MemberPointerType>())
3376      TyRec = cast<RecordType>(RHSMPType->getClass());
3377    else
3378      TyRec = ArgExpr->getType()->getAs<RecordType>();
3379    if (!TyRec) {
3380      // Just to be safe, assume the worst case.
3381      VRQuals.addVolatile();
3382      VRQuals.addRestrict();
3383      return VRQuals;
3384    }
3385
3386    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3387    if (!ClassDecl->hasDefinition())
3388      return VRQuals;
3389
3390    const UnresolvedSetImpl *Conversions =
3391      ClassDecl->getVisibleConversionFunctions();
3392
3393    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3394           E = Conversions->end(); I != E; ++I) {
3395      NamedDecl *D = I.getDecl();
3396      if (isa<UsingShadowDecl>(D))
3397        D = cast<UsingShadowDecl>(D)->getTargetDecl();
3398      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
3399        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3400        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3401          CanTy = ResTypeRef->getPointeeType();
3402        // Need to go down the pointer/mempointer chain and add qualifiers
3403        // as see them.
3404        bool done = false;
3405        while (!done) {
3406          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3407            CanTy = ResTypePtr->getPointeeType();
3408          else if (const MemberPointerType *ResTypeMPtr =
3409                CanTy->getAs<MemberPointerType>())
3410            CanTy = ResTypeMPtr->getPointeeType();
3411          else
3412            done = true;
3413          if (CanTy.isVolatileQualified())
3414            VRQuals.addVolatile();
3415          if (CanTy.isRestrictQualified())
3416            VRQuals.addRestrict();
3417          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3418            return VRQuals;
3419        }
3420      }
3421    }
3422    return VRQuals;
3423}
3424
3425/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3426/// operator overloads to the candidate set (C++ [over.built]), based
3427/// on the operator @p Op and the arguments given. For example, if the
3428/// operator is a binary '+', this routine might add "int
3429/// operator+(int, int)" to cover integer addition.
3430void
3431Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3432                                   SourceLocation OpLoc,
3433                                   Expr **Args, unsigned NumArgs,
3434                                   OverloadCandidateSet& CandidateSet) {
3435  // The set of "promoted arithmetic types", which are the arithmetic
3436  // types are that preserved by promotion (C++ [over.built]p2). Note
3437  // that the first few of these types are the promoted integral
3438  // types; these types need to be first.
3439  // FIXME: What about complex?
3440  const unsigned FirstIntegralType = 0;
3441  const unsigned LastIntegralType = 13;
3442  const unsigned FirstPromotedIntegralType = 7,
3443                 LastPromotedIntegralType = 13;
3444  const unsigned FirstPromotedArithmeticType = 7,
3445                 LastPromotedArithmeticType = 16;
3446  const unsigned NumArithmeticTypes = 16;
3447  QualType ArithmeticTypes[NumArithmeticTypes] = {
3448    Context.BoolTy, Context.CharTy, Context.WCharTy,
3449// FIXME:   Context.Char16Ty, Context.Char32Ty,
3450    Context.SignedCharTy, Context.ShortTy,
3451    Context.UnsignedCharTy, Context.UnsignedShortTy,
3452    Context.IntTy, Context.LongTy, Context.LongLongTy,
3453    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3454    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3455  };
3456  assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3457         "Invalid first promoted integral type");
3458  assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3459           == Context.UnsignedLongLongTy &&
3460         "Invalid last promoted integral type");
3461  assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3462         "Invalid first promoted arithmetic type");
3463  assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3464            == Context.LongDoubleTy &&
3465         "Invalid last promoted arithmetic type");
3466
3467  // Find all of the types that the arguments can convert to, but only
3468  // if the operator we're looking at has built-in operator candidates
3469  // that make use of these types.
3470  Qualifiers VisibleTypeConversionsQuals;
3471  VisibleTypeConversionsQuals.addConst();
3472  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3473    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3474
3475  BuiltinCandidateTypeSet CandidateTypes(*this);
3476  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3477      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3478      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3479      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3480      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3481      (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3482    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3483      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3484                                           OpLoc,
3485                                           true,
3486                                           (Op == OO_Exclaim ||
3487                                            Op == OO_AmpAmp ||
3488                                            Op == OO_PipePipe),
3489                                           VisibleTypeConversionsQuals);
3490  }
3491
3492  bool isComparison = false;
3493  switch (Op) {
3494  case OO_None:
3495  case NUM_OVERLOADED_OPERATORS:
3496    assert(false && "Expected an overloaded operator");
3497    break;
3498
3499  case OO_Star: // '*' is either unary or binary
3500    if (NumArgs == 1)
3501      goto UnaryStar;
3502    else
3503      goto BinaryStar;
3504    break;
3505
3506  case OO_Plus: // '+' is either unary or binary
3507    if (NumArgs == 1)
3508      goto UnaryPlus;
3509    else
3510      goto BinaryPlus;
3511    break;
3512
3513  case OO_Minus: // '-' is either unary or binary
3514    if (NumArgs == 1)
3515      goto UnaryMinus;
3516    else
3517      goto BinaryMinus;
3518    break;
3519
3520  case OO_Amp: // '&' is either unary or binary
3521    if (NumArgs == 1)
3522      goto UnaryAmp;
3523    else
3524      goto BinaryAmp;
3525
3526  case OO_PlusPlus:
3527  case OO_MinusMinus:
3528    // C++ [over.built]p3:
3529    //
3530    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
3531    //   is either volatile or empty, there exist candidate operator
3532    //   functions of the form
3533    //
3534    //       VQ T&      operator++(VQ T&);
3535    //       T          operator++(VQ T&, int);
3536    //
3537    // C++ [over.built]p4:
3538    //
3539    //   For every pair (T, VQ), where T is an arithmetic type other
3540    //   than bool, and VQ is either volatile or empty, there exist
3541    //   candidate operator functions of the form
3542    //
3543    //       VQ T&      operator--(VQ T&);
3544    //       T          operator--(VQ T&, int);
3545    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3546         Arith < NumArithmeticTypes; ++Arith) {
3547      QualType ArithTy = ArithmeticTypes[Arith];
3548      QualType ParamTypes[2]
3549        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3550
3551      // Non-volatile version.
3552      if (NumArgs == 1)
3553        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3554      else
3555        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3556      // heuristic to reduce number of builtin candidates in the set.
3557      // Add volatile version only if there are conversions to a volatile type.
3558      if (VisibleTypeConversionsQuals.hasVolatile()) {
3559        // Volatile version
3560        ParamTypes[0]
3561          = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3562        if (NumArgs == 1)
3563          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3564        else
3565          AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3566      }
3567    }
3568
3569    // C++ [over.built]p5:
3570    //
3571    //   For every pair (T, VQ), where T is a cv-qualified or
3572    //   cv-unqualified object type, and VQ is either volatile or
3573    //   empty, there exist candidate operator functions of the form
3574    //
3575    //       T*VQ&      operator++(T*VQ&);
3576    //       T*VQ&      operator--(T*VQ&);
3577    //       T*         operator++(T*VQ&, int);
3578    //       T*         operator--(T*VQ&, int);
3579    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3580         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3581      // Skip pointer types that aren't pointers to object types.
3582      if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3583        continue;
3584
3585      QualType ParamTypes[2] = {
3586        Context.getLValueReferenceType(*Ptr), Context.IntTy
3587      };
3588
3589      // Without volatile
3590      if (NumArgs == 1)
3591        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3592      else
3593        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3594
3595      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3596          VisibleTypeConversionsQuals.hasVolatile()) {
3597        // With volatile
3598        ParamTypes[0]
3599          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3600        if (NumArgs == 1)
3601          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3602        else
3603          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3604      }
3605    }
3606    break;
3607
3608  UnaryStar:
3609    // C++ [over.built]p6:
3610    //   For every cv-qualified or cv-unqualified object type T, there
3611    //   exist candidate operator functions of the form
3612    //
3613    //       T&         operator*(T*);
3614    //
3615    // C++ [over.built]p7:
3616    //   For every function type T, there exist candidate operator
3617    //   functions of the form
3618    //       T&         operator*(T*);
3619    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3620         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3621      QualType ParamTy = *Ptr;
3622      QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3623      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3624                          &ParamTy, Args, 1, CandidateSet);
3625    }
3626    break;
3627
3628  UnaryPlus:
3629    // C++ [over.built]p8:
3630    //   For every type T, there exist candidate operator functions of
3631    //   the form
3632    //
3633    //       T*         operator+(T*);
3634    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3635         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3636      QualType ParamTy = *Ptr;
3637      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3638    }
3639
3640    // Fall through
3641
3642  UnaryMinus:
3643    // C++ [over.built]p9:
3644    //  For every promoted arithmetic type T, there exist candidate
3645    //  operator functions of the form
3646    //
3647    //       T         operator+(T);
3648    //       T         operator-(T);
3649    for (unsigned Arith = FirstPromotedArithmeticType;
3650         Arith < LastPromotedArithmeticType; ++Arith) {
3651      QualType ArithTy = ArithmeticTypes[Arith];
3652      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3653    }
3654    break;
3655
3656  case OO_Tilde:
3657    // C++ [over.built]p10:
3658    //   For every promoted integral type T, there exist candidate
3659    //   operator functions of the form
3660    //
3661    //        T         operator~(T);
3662    for (unsigned Int = FirstPromotedIntegralType;
3663         Int < LastPromotedIntegralType; ++Int) {
3664      QualType IntTy = ArithmeticTypes[Int];
3665      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3666    }
3667    break;
3668
3669  case OO_New:
3670  case OO_Delete:
3671  case OO_Array_New:
3672  case OO_Array_Delete:
3673  case OO_Call:
3674    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3675    break;
3676
3677  case OO_Comma:
3678  UnaryAmp:
3679  case OO_Arrow:
3680    // C++ [over.match.oper]p3:
3681    //   -- For the operator ',', the unary operator '&', or the
3682    //      operator '->', the built-in candidates set is empty.
3683    break;
3684
3685  case OO_EqualEqual:
3686  case OO_ExclaimEqual:
3687    // C++ [over.match.oper]p16:
3688    //   For every pointer to member type T, there exist candidate operator
3689    //   functions of the form
3690    //
3691    //        bool operator==(T,T);
3692    //        bool operator!=(T,T);
3693    for (BuiltinCandidateTypeSet::iterator
3694           MemPtr = CandidateTypes.member_pointer_begin(),
3695           MemPtrEnd = CandidateTypes.member_pointer_end();
3696         MemPtr != MemPtrEnd;
3697         ++MemPtr) {
3698      QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3699      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3700    }
3701
3702    // Fall through
3703
3704  case OO_Less:
3705  case OO_Greater:
3706  case OO_LessEqual:
3707  case OO_GreaterEqual:
3708    // C++ [over.built]p15:
3709    //
3710    //   For every pointer or enumeration type T, there exist
3711    //   candidate operator functions of the form
3712    //
3713    //        bool       operator<(T, T);
3714    //        bool       operator>(T, T);
3715    //        bool       operator<=(T, T);
3716    //        bool       operator>=(T, T);
3717    //        bool       operator==(T, T);
3718    //        bool       operator!=(T, T);
3719    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3720         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3721      QualType ParamTypes[2] = { *Ptr, *Ptr };
3722      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3723    }
3724    for (BuiltinCandidateTypeSet::iterator Enum
3725           = CandidateTypes.enumeration_begin();
3726         Enum != CandidateTypes.enumeration_end(); ++Enum) {
3727      QualType ParamTypes[2] = { *Enum, *Enum };
3728      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3729    }
3730
3731    // Fall through.
3732    isComparison = true;
3733
3734  BinaryPlus:
3735  BinaryMinus:
3736    if (!isComparison) {
3737      // We didn't fall through, so we must have OO_Plus or OO_Minus.
3738
3739      // C++ [over.built]p13:
3740      //
3741      //   For every cv-qualified or cv-unqualified object type T
3742      //   there exist candidate operator functions of the form
3743      //
3744      //      T*         operator+(T*, ptrdiff_t);
3745      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
3746      //      T*         operator-(T*, ptrdiff_t);
3747      //      T*         operator+(ptrdiff_t, T*);
3748      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
3749      //
3750      // C++ [over.built]p14:
3751      //
3752      //   For every T, where T is a pointer to object type, there
3753      //   exist candidate operator functions of the form
3754      //
3755      //      ptrdiff_t  operator-(T, T);
3756      for (BuiltinCandidateTypeSet::iterator Ptr
3757             = CandidateTypes.pointer_begin();
3758           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3759        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3760
3761        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3762        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3763
3764        if (Op == OO_Plus) {
3765          // T* operator+(ptrdiff_t, T*);
3766          ParamTypes[0] = ParamTypes[1];
3767          ParamTypes[1] = *Ptr;
3768          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3769        } else {
3770          // ptrdiff_t operator-(T, T);
3771          ParamTypes[1] = *Ptr;
3772          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3773                              Args, 2, CandidateSet);
3774        }
3775      }
3776    }
3777    // Fall through
3778
3779  case OO_Slash:
3780  BinaryStar:
3781  Conditional:
3782    // C++ [over.built]p12:
3783    //
3784    //   For every pair of promoted arithmetic types L and R, there
3785    //   exist candidate operator functions of the form
3786    //
3787    //        LR         operator*(L, R);
3788    //        LR         operator/(L, R);
3789    //        LR         operator+(L, R);
3790    //        LR         operator-(L, R);
3791    //        bool       operator<(L, R);
3792    //        bool       operator>(L, R);
3793    //        bool       operator<=(L, R);
3794    //        bool       operator>=(L, R);
3795    //        bool       operator==(L, R);
3796    //        bool       operator!=(L, R);
3797    //
3798    //   where LR is the result of the usual arithmetic conversions
3799    //   between types L and R.
3800    //
3801    // C++ [over.built]p24:
3802    //
3803    //   For every pair of promoted arithmetic types L and R, there exist
3804    //   candidate operator functions of the form
3805    //
3806    //        LR       operator?(bool, L, R);
3807    //
3808    //   where LR is the result of the usual arithmetic conversions
3809    //   between types L and R.
3810    // Our candidates ignore the first parameter.
3811    for (unsigned Left = FirstPromotedArithmeticType;
3812         Left < LastPromotedArithmeticType; ++Left) {
3813      for (unsigned Right = FirstPromotedArithmeticType;
3814           Right < LastPromotedArithmeticType; ++Right) {
3815        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3816        QualType Result
3817          = isComparison
3818          ? Context.BoolTy
3819          : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3820        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3821      }
3822    }
3823    break;
3824
3825  case OO_Percent:
3826  BinaryAmp:
3827  case OO_Caret:
3828  case OO_Pipe:
3829  case OO_LessLess:
3830  case OO_GreaterGreater:
3831    // C++ [over.built]p17:
3832    //
3833    //   For every pair of promoted integral types L and R, there
3834    //   exist candidate operator functions of the form
3835    //
3836    //      LR         operator%(L, R);
3837    //      LR         operator&(L, R);
3838    //      LR         operator^(L, R);
3839    //      LR         operator|(L, R);
3840    //      L          operator<<(L, R);
3841    //      L          operator>>(L, R);
3842    //
3843    //   where LR is the result of the usual arithmetic conversions
3844    //   between types L and R.
3845    for (unsigned Left = FirstPromotedIntegralType;
3846         Left < LastPromotedIntegralType; ++Left) {
3847      for (unsigned Right = FirstPromotedIntegralType;
3848           Right < LastPromotedIntegralType; ++Right) {
3849        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3850        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3851            ? LandR[0]
3852            : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3853        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3854      }
3855    }
3856    break;
3857
3858  case OO_Equal:
3859    // C++ [over.built]p20:
3860    //
3861    //   For every pair (T, VQ), where T is an enumeration or
3862    //   pointer to member type and VQ is either volatile or
3863    //   empty, there exist candidate operator functions of the form
3864    //
3865    //        VQ T&      operator=(VQ T&, T);
3866    for (BuiltinCandidateTypeSet::iterator
3867           Enum = CandidateTypes.enumeration_begin(),
3868           EnumEnd = CandidateTypes.enumeration_end();
3869         Enum != EnumEnd; ++Enum)
3870      AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3871                                             CandidateSet);
3872    for (BuiltinCandidateTypeSet::iterator
3873           MemPtr = CandidateTypes.member_pointer_begin(),
3874         MemPtrEnd = CandidateTypes.member_pointer_end();
3875         MemPtr != MemPtrEnd; ++MemPtr)
3876      AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3877                                             CandidateSet);
3878      // Fall through.
3879
3880  case OO_PlusEqual:
3881  case OO_MinusEqual:
3882    // C++ [over.built]p19:
3883    //
3884    //   For every pair (T, VQ), where T is any type and VQ is either
3885    //   volatile or empty, there exist candidate operator functions
3886    //   of the form
3887    //
3888    //        T*VQ&      operator=(T*VQ&, T*);
3889    //
3890    // C++ [over.built]p21:
3891    //
3892    //   For every pair (T, VQ), where T is a cv-qualified or
3893    //   cv-unqualified object type and VQ is either volatile or
3894    //   empty, there exist candidate operator functions of the form
3895    //
3896    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
3897    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
3898    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3899         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3900      QualType ParamTypes[2];
3901      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3902
3903      // non-volatile version
3904      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3905      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3906                          /*IsAssigmentOperator=*/Op == OO_Equal);
3907
3908      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3909          VisibleTypeConversionsQuals.hasVolatile()) {
3910        // volatile version
3911        ParamTypes[0]
3912          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3913        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3914                            /*IsAssigmentOperator=*/Op == OO_Equal);
3915      }
3916    }
3917    // Fall through.
3918
3919  case OO_StarEqual:
3920  case OO_SlashEqual:
3921    // C++ [over.built]p18:
3922    //
3923    //   For every triple (L, VQ, R), where L is an arithmetic type,
3924    //   VQ is either volatile or empty, and R is a promoted
3925    //   arithmetic type, there exist candidate operator functions of
3926    //   the form
3927    //
3928    //        VQ L&      operator=(VQ L&, R);
3929    //        VQ L&      operator*=(VQ L&, R);
3930    //        VQ L&      operator/=(VQ L&, R);
3931    //        VQ L&      operator+=(VQ L&, R);
3932    //        VQ L&      operator-=(VQ L&, R);
3933    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3934      for (unsigned Right = FirstPromotedArithmeticType;
3935           Right < LastPromotedArithmeticType; ++Right) {
3936        QualType ParamTypes[2];
3937        ParamTypes[1] = ArithmeticTypes[Right];
3938
3939        // Add this built-in operator as a candidate (VQ is empty).
3940        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3941        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3942                            /*IsAssigmentOperator=*/Op == OO_Equal);
3943
3944        // Add this built-in operator as a candidate (VQ is 'volatile').
3945        if (VisibleTypeConversionsQuals.hasVolatile()) {
3946          ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3947          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3948          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3949                              /*IsAssigmentOperator=*/Op == OO_Equal);
3950        }
3951      }
3952    }
3953    break;
3954
3955  case OO_PercentEqual:
3956  case OO_LessLessEqual:
3957  case OO_GreaterGreaterEqual:
3958  case OO_AmpEqual:
3959  case OO_CaretEqual:
3960  case OO_PipeEqual:
3961    // C++ [over.built]p22:
3962    //
3963    //   For every triple (L, VQ, R), where L is an integral type, VQ
3964    //   is either volatile or empty, and R is a promoted integral
3965    //   type, there exist candidate operator functions of the form
3966    //
3967    //        VQ L&       operator%=(VQ L&, R);
3968    //        VQ L&       operator<<=(VQ L&, R);
3969    //        VQ L&       operator>>=(VQ L&, R);
3970    //        VQ L&       operator&=(VQ L&, R);
3971    //        VQ L&       operator^=(VQ L&, R);
3972    //        VQ L&       operator|=(VQ L&, R);
3973    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3974      for (unsigned Right = FirstPromotedIntegralType;
3975           Right < LastPromotedIntegralType; ++Right) {
3976        QualType ParamTypes[2];
3977        ParamTypes[1] = ArithmeticTypes[Right];
3978
3979        // Add this built-in operator as a candidate (VQ is empty).
3980        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3981        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3982        if (VisibleTypeConversionsQuals.hasVolatile()) {
3983          // Add this built-in operator as a candidate (VQ is 'volatile').
3984          ParamTypes[0] = ArithmeticTypes[Left];
3985          ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3986          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3987          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3988        }
3989      }
3990    }
3991    break;
3992
3993  case OO_Exclaim: {
3994    // C++ [over.operator]p23:
3995    //
3996    //   There also exist candidate operator functions of the form
3997    //
3998    //        bool        operator!(bool);
3999    //        bool        operator&&(bool, bool);     [BELOW]
4000    //        bool        operator||(bool, bool);     [BELOW]
4001    QualType ParamTy = Context.BoolTy;
4002    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4003                        /*IsAssignmentOperator=*/false,
4004                        /*NumContextualBoolArguments=*/1);
4005    break;
4006  }
4007
4008  case OO_AmpAmp:
4009  case OO_PipePipe: {
4010    // C++ [over.operator]p23:
4011    //
4012    //   There also exist candidate operator functions of the form
4013    //
4014    //        bool        operator!(bool);            [ABOVE]
4015    //        bool        operator&&(bool, bool);
4016    //        bool        operator||(bool, bool);
4017    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
4018    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4019                        /*IsAssignmentOperator=*/false,
4020                        /*NumContextualBoolArguments=*/2);
4021    break;
4022  }
4023
4024  case OO_Subscript:
4025    // C++ [over.built]p13:
4026    //
4027    //   For every cv-qualified or cv-unqualified object type T there
4028    //   exist candidate operator functions of the form
4029    //
4030    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
4031    //        T&         operator[](T*, ptrdiff_t);
4032    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
4033    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
4034    //        T&         operator[](ptrdiff_t, T*);
4035    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4036         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4037      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4038      QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
4039      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
4040
4041      // T& operator[](T*, ptrdiff_t)
4042      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4043
4044      // T& operator[](ptrdiff_t, T*);
4045      ParamTypes[0] = ParamTypes[1];
4046      ParamTypes[1] = *Ptr;
4047      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4048    }
4049    break;
4050
4051  case OO_ArrowStar:
4052    // C++ [over.built]p11:
4053    //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4054    //    C1 is the same type as C2 or is a derived class of C2, T is an object
4055    //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4056    //    there exist candidate operator functions of the form
4057    //    CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4058    //    where CV12 is the union of CV1 and CV2.
4059    {
4060      for (BuiltinCandidateTypeSet::iterator Ptr =
4061             CandidateTypes.pointer_begin();
4062           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4063        QualType C1Ty = (*Ptr);
4064        QualType C1;
4065        QualifierCollector Q1;
4066        if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
4067          C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
4068          if (!isa<RecordType>(C1))
4069            continue;
4070          // heuristic to reduce number of builtin candidates in the set.
4071          // Add volatile/restrict version only if there are conversions to a
4072          // volatile/restrict type.
4073          if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4074            continue;
4075          if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4076            continue;
4077        }
4078        for (BuiltinCandidateTypeSet::iterator
4079             MemPtr = CandidateTypes.member_pointer_begin(),
4080             MemPtrEnd = CandidateTypes.member_pointer_end();
4081             MemPtr != MemPtrEnd; ++MemPtr) {
4082          const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4083          QualType C2 = QualType(mptr->getClass(), 0);
4084          C2 = C2.getUnqualifiedType();
4085          if (C1 != C2 && !IsDerivedFrom(C1, C2))
4086            break;
4087          QualType ParamTypes[2] = { *Ptr, *MemPtr };
4088          // build CV12 T&
4089          QualType T = mptr->getPointeeType();
4090          if (!VisibleTypeConversionsQuals.hasVolatile() &&
4091              T.isVolatileQualified())
4092            continue;
4093          if (!VisibleTypeConversionsQuals.hasRestrict() &&
4094              T.isRestrictQualified())
4095            continue;
4096          T = Q1.apply(T);
4097          QualType ResultTy = Context.getLValueReferenceType(T);
4098          AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4099        }
4100      }
4101    }
4102    break;
4103
4104  case OO_Conditional:
4105    // Note that we don't consider the first argument, since it has been
4106    // contextually converted to bool long ago. The candidates below are
4107    // therefore added as binary.
4108    //
4109    // C++ [over.built]p24:
4110    //   For every type T, where T is a pointer or pointer-to-member type,
4111    //   there exist candidate operator functions of the form
4112    //
4113    //        T        operator?(bool, T, T);
4114    //
4115    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4116         E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4117      QualType ParamTypes[2] = { *Ptr, *Ptr };
4118      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4119    }
4120    for (BuiltinCandidateTypeSet::iterator Ptr =
4121           CandidateTypes.member_pointer_begin(),
4122         E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4123      QualType ParamTypes[2] = { *Ptr, *Ptr };
4124      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4125    }
4126    goto Conditional;
4127  }
4128}
4129
4130/// \brief Add function candidates found via argument-dependent lookup
4131/// to the set of overloading candidates.
4132///
4133/// This routine performs argument-dependent name lookup based on the
4134/// given function name (which may also be an operator name) and adds
4135/// all of the overload candidates found by ADL to the overload
4136/// candidate set (C++ [basic.lookup.argdep]).
4137void
4138Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4139                                           bool Operator,
4140                                           Expr **Args, unsigned NumArgs,
4141                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4142                                           OverloadCandidateSet& CandidateSet,
4143                                           bool PartialOverloading) {
4144  ADLResult Fns;
4145
4146  // FIXME: This approach for uniquing ADL results (and removing
4147  // redundant candidates from the set) relies on pointer-equality,
4148  // which means we need to key off the canonical decl.  However,
4149  // always going back to the canonical decl might not get us the
4150  // right set of default arguments.  What default arguments are
4151  // we supposed to consider on ADL candidates, anyway?
4152
4153  // FIXME: Pass in the explicit template arguments?
4154  ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
4155
4156  // Erase all of the candidates we already knew about.
4157  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4158                                   CandEnd = CandidateSet.end();
4159       Cand != CandEnd; ++Cand)
4160    if (Cand->Function) {
4161      Fns.erase(Cand->Function);
4162      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4163        Fns.erase(FunTmpl);
4164    }
4165
4166  // For each of the ADL candidates we found, add it to the overload
4167  // set.
4168  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
4169    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
4170    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
4171      if (ExplicitTemplateArgs)
4172        continue;
4173
4174      AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
4175                           false, false, PartialOverloading);
4176    } else
4177      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
4178                                   FoundDecl, ExplicitTemplateArgs,
4179                                   Args, NumArgs, CandidateSet);
4180  }
4181}
4182
4183/// isBetterOverloadCandidate - Determines whether the first overload
4184/// candidate is a better candidate than the second (C++ 13.3.3p1).
4185bool
4186Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
4187                                const OverloadCandidate& Cand2,
4188                                SourceLocation Loc) {
4189  // Define viable functions to be better candidates than non-viable
4190  // functions.
4191  if (!Cand2.Viable)
4192    return Cand1.Viable;
4193  else if (!Cand1.Viable)
4194    return false;
4195
4196  // C++ [over.match.best]p1:
4197  //
4198  //   -- if F is a static member function, ICS1(F) is defined such
4199  //      that ICS1(F) is neither better nor worse than ICS1(G) for
4200  //      any function G, and, symmetrically, ICS1(G) is neither
4201  //      better nor worse than ICS1(F).
4202  unsigned StartArg = 0;
4203  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4204    StartArg = 1;
4205
4206  // C++ [over.match.best]p1:
4207  //   A viable function F1 is defined to be a better function than another
4208  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
4209  //   conversion sequence than ICSi(F2), and then...
4210  unsigned NumArgs = Cand1.Conversions.size();
4211  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4212  bool HasBetterConversion = false;
4213  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
4214    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4215                                               Cand2.Conversions[ArgIdx])) {
4216    case ImplicitConversionSequence::Better:
4217      // Cand1 has a better conversion sequence.
4218      HasBetterConversion = true;
4219      break;
4220
4221    case ImplicitConversionSequence::Worse:
4222      // Cand1 can't be better than Cand2.
4223      return false;
4224
4225    case ImplicitConversionSequence::Indistinguishable:
4226      // Do nothing.
4227      break;
4228    }
4229  }
4230
4231  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
4232  //       ICSj(F2), or, if not that,
4233  if (HasBetterConversion)
4234    return true;
4235
4236  //     - F1 is a non-template function and F2 is a function template
4237  //       specialization, or, if not that,
4238  if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4239      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4240    return true;
4241
4242  //   -- F1 and F2 are function template specializations, and the function
4243  //      template for F1 is more specialized than the template for F2
4244  //      according to the partial ordering rules described in 14.5.5.2, or,
4245  //      if not that,
4246  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4247      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4248    if (FunctionTemplateDecl *BetterTemplate
4249          = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4250                                       Cand2.Function->getPrimaryTemplate(),
4251                                       Loc,
4252                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4253                                                             : TPOC_Call))
4254      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
4255
4256  //   -- the context is an initialization by user-defined conversion
4257  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
4258  //      from the return type of F1 to the destination type (i.e.,
4259  //      the type of the entity being initialized) is a better
4260  //      conversion sequence than the standard conversion sequence
4261  //      from the return type of F2 to the destination type.
4262  if (Cand1.Function && Cand2.Function &&
4263      isa<CXXConversionDecl>(Cand1.Function) &&
4264      isa<CXXConversionDecl>(Cand2.Function)) {
4265    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4266                                               Cand2.FinalConversion)) {
4267    case ImplicitConversionSequence::Better:
4268      // Cand1 has a better conversion sequence.
4269      return true;
4270
4271    case ImplicitConversionSequence::Worse:
4272      // Cand1 can't be better than Cand2.
4273      return false;
4274
4275    case ImplicitConversionSequence::Indistinguishable:
4276      // Do nothing
4277      break;
4278    }
4279  }
4280
4281  return false;
4282}
4283
4284/// \brief Computes the best viable function (C++ 13.3.3)
4285/// within an overload candidate set.
4286///
4287/// \param CandidateSet the set of candidate functions.
4288///
4289/// \param Loc the location of the function name (or operator symbol) for
4290/// which overload resolution occurs.
4291///
4292/// \param Best f overload resolution was successful or found a deleted
4293/// function, Best points to the candidate function found.
4294///
4295/// \returns The result of overload resolution.
4296OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4297                                           SourceLocation Loc,
4298                                        OverloadCandidateSet::iterator& Best) {
4299  // Find the best viable function.
4300  Best = CandidateSet.end();
4301  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4302       Cand != CandidateSet.end(); ++Cand) {
4303    if (Cand->Viable) {
4304      if (Best == CandidateSet.end() ||
4305          isBetterOverloadCandidate(*Cand, *Best, Loc))
4306        Best = Cand;
4307    }
4308  }
4309
4310  // If we didn't find any viable functions, abort.
4311  if (Best == CandidateSet.end())
4312    return OR_No_Viable_Function;
4313
4314  // Make sure that this function is better than every other viable
4315  // function. If not, we have an ambiguity.
4316  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4317       Cand != CandidateSet.end(); ++Cand) {
4318    if (Cand->Viable &&
4319        Cand != Best &&
4320        !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
4321      Best = CandidateSet.end();
4322      return OR_Ambiguous;
4323    }
4324  }
4325
4326  // Best is the best viable function.
4327  if (Best->Function &&
4328      (Best->Function->isDeleted() ||
4329       Best->Function->getAttr<UnavailableAttr>()))
4330    return OR_Deleted;
4331
4332  // C++ [basic.def.odr]p2:
4333  //   An overloaded function is used if it is selected by overload resolution
4334  //   when referred to from a potentially-evaluated expression. [Note: this
4335  //   covers calls to named functions (5.2.2), operator overloading
4336  //   (clause 13), user-defined conversions (12.3.2), allocation function for
4337  //   placement new (5.3.4), as well as non-default initialization (8.5).
4338  if (Best->Function)
4339    MarkDeclarationReferenced(Loc, Best->Function);
4340  return OR_Success;
4341}
4342
4343namespace {
4344
4345enum OverloadCandidateKind {
4346  oc_function,
4347  oc_method,
4348  oc_constructor,
4349  oc_function_template,
4350  oc_method_template,
4351  oc_constructor_template,
4352  oc_implicit_default_constructor,
4353  oc_implicit_copy_constructor,
4354  oc_implicit_copy_assignment
4355};
4356
4357OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4358                                                FunctionDecl *Fn,
4359                                                std::string &Description) {
4360  bool isTemplate = false;
4361
4362  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4363    isTemplate = true;
4364    Description = S.getTemplateArgumentBindingsText(
4365      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4366  }
4367
4368  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
4369    if (!Ctor->isImplicit())
4370      return isTemplate ? oc_constructor_template : oc_constructor;
4371
4372    return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4373                                     : oc_implicit_default_constructor;
4374  }
4375
4376  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4377    // This actually gets spelled 'candidate function' for now, but
4378    // it doesn't hurt to split it out.
4379    if (!Meth->isImplicit())
4380      return isTemplate ? oc_method_template : oc_method;
4381
4382    assert(Meth->isCopyAssignment()
4383           && "implicit method is not copy assignment operator?");
4384    return oc_implicit_copy_assignment;
4385  }
4386
4387  return isTemplate ? oc_function_template : oc_function;
4388}
4389
4390} // end anonymous namespace
4391
4392// Notes the location of an overload candidate.
4393void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
4394  std::string FnDesc;
4395  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4396  Diag(Fn->getLocation(), diag::note_ovl_candidate)
4397    << (unsigned) K << FnDesc;
4398}
4399
4400/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
4401/// "lead" diagnostic; it will be given two arguments, the source and
4402/// target types of the conversion.
4403void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4404                                       SourceLocation CaretLoc,
4405                                       const PartialDiagnostic &PDiag) {
4406  Diag(CaretLoc, PDiag)
4407    << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4408  for (AmbiguousConversionSequence::const_iterator
4409         I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4410    NoteOverloadCandidate(*I);
4411  }
4412}
4413
4414namespace {
4415
4416void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4417  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4418  assert(Conv.isBad());
4419  assert(Cand->Function && "for now, candidate must be a function");
4420  FunctionDecl *Fn = Cand->Function;
4421
4422  // There's a conversion slot for the object argument if this is a
4423  // non-constructor method.  Note that 'I' corresponds the
4424  // conversion-slot index.
4425  bool isObjectArgument = false;
4426  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
4427    if (I == 0)
4428      isObjectArgument = true;
4429    else
4430      I--;
4431  }
4432
4433  std::string FnDesc;
4434  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4435
4436  Expr *FromExpr = Conv.Bad.FromExpr;
4437  QualType FromTy = Conv.Bad.getFromType();
4438  QualType ToTy = Conv.Bad.getToType();
4439
4440  if (FromTy == S.Context.OverloadTy) {
4441    assert(FromExpr && "overload set argument came from implicit argument?");
4442    Expr *E = FromExpr->IgnoreParens();
4443    if (isa<UnaryOperator>(E))
4444      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
4445    DeclarationName Name = cast<OverloadExpr>(E)->getName();
4446
4447    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4448      << (unsigned) FnKind << FnDesc
4449      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4450      << ToTy << Name << I+1;
4451    return;
4452  }
4453
4454  // Do some hand-waving analysis to see if the non-viability is due
4455  // to a qualifier mismatch.
4456  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4457  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4458  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4459    CToTy = RT->getPointeeType();
4460  else {
4461    // TODO: detect and diagnose the full richness of const mismatches.
4462    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4463      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4464        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4465  }
4466
4467  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4468      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4469    // It is dumb that we have to do this here.
4470    while (isa<ArrayType>(CFromTy))
4471      CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4472    while (isa<ArrayType>(CToTy))
4473      CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4474
4475    Qualifiers FromQs = CFromTy.getQualifiers();
4476    Qualifiers ToQs = CToTy.getQualifiers();
4477
4478    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
4479      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
4480        << (unsigned) FnKind << FnDesc
4481        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4482        << FromTy
4483        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
4484        << (unsigned) isObjectArgument << I+1;
4485      return;
4486    }
4487
4488    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4489    assert(CVR && "unexpected qualifiers mismatch");
4490
4491    if (isObjectArgument) {
4492      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
4493        << (unsigned) FnKind << FnDesc
4494        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4495        << FromTy << (CVR - 1);
4496    } else {
4497      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
4498        << (unsigned) FnKind << FnDesc
4499        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4500        << FromTy << (CVR - 1) << I+1;
4501    }
4502    return;
4503  }
4504
4505  // Diagnose references or pointers to incomplete types differently,
4506  // since it's far from impossible that the incompleteness triggered
4507  // the failure.
4508  QualType TempFromTy = FromTy.getNonReferenceType();
4509  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
4510    TempFromTy = PTy->getPointeeType();
4511  if (TempFromTy->isIncompleteType()) {
4512    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
4513      << (unsigned) FnKind << FnDesc
4514      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4515      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4516    return;
4517  }
4518
4519  // TODO: specialize more based on the kind of mismatch
4520  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
4521    << (unsigned) FnKind << FnDesc
4522    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4523    << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
4524}
4525
4526void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
4527                           unsigned NumFormalArgs) {
4528  // TODO: treat calls to a missing default constructor as a special case
4529
4530  FunctionDecl *Fn = Cand->Function;
4531  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
4532
4533  unsigned MinParams = Fn->getMinRequiredArguments();
4534
4535  // at least / at most / exactly
4536  unsigned mode, modeCount;
4537  if (NumFormalArgs < MinParams) {
4538    assert(Cand->FailureKind == ovl_fail_too_few_arguments);
4539    if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
4540      mode = 0; // "at least"
4541    else
4542      mode = 2; // "exactly"
4543    modeCount = MinParams;
4544  } else {
4545    assert(Cand->FailureKind == ovl_fail_too_many_arguments);
4546    if (MinParams != FnTy->getNumArgs())
4547      mode = 1; // "at most"
4548    else
4549      mode = 2; // "exactly"
4550    modeCount = FnTy->getNumArgs();
4551  }
4552
4553  std::string Description;
4554  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
4555
4556  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
4557    << (unsigned) FnKind << Description << mode << modeCount << NumFormalArgs;
4558}
4559
4560/// Diagnose a failed template-argument deduction.
4561void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
4562                          Expr **Args, unsigned NumArgs) {
4563  FunctionDecl *Fn = Cand->Function; // pattern
4564
4565  TemplateParameter Param = TemplateParameter::getFromOpaqueValue(
4566                                   Cand->DeductionFailure.TemplateParameter);
4567
4568  switch (Cand->DeductionFailure.Result) {
4569  case Sema::TDK_Success:
4570    llvm_unreachable("TDK_success while diagnosing bad deduction");
4571
4572  case Sema::TDK_Incomplete: {
4573    NamedDecl *ParamD;
4574    (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
4575    (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
4576    (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
4577    assert(ParamD && "no parameter found for incomplete deduction result");
4578    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
4579      << ParamD->getDeclName();
4580    return;
4581  }
4582
4583  // TODO: diagnose these individually, then kill off
4584  // note_ovl_candidate_bad_deduction, which is uselessly vague.
4585  case Sema::TDK_InstantiationDepth:
4586  case Sema::TDK_Inconsistent:
4587  case Sema::TDK_InconsistentQuals:
4588  case Sema::TDK_SubstitutionFailure:
4589  case Sema::TDK_NonDeducedMismatch:
4590  case Sema::TDK_TooManyArguments:
4591  case Sema::TDK_TooFewArguments:
4592  case Sema::TDK_InvalidExplicitArguments:
4593  case Sema::TDK_FailedOverloadResolution:
4594    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
4595    return;
4596  }
4597}
4598
4599/// Generates a 'note' diagnostic for an overload candidate.  We've
4600/// already generated a primary error at the call site.
4601///
4602/// It really does need to be a single diagnostic with its caret
4603/// pointed at the candidate declaration.  Yes, this creates some
4604/// major challenges of technical writing.  Yes, this makes pointing
4605/// out problems with specific arguments quite awkward.  It's still
4606/// better than generating twenty screens of text for every failed
4607/// overload.
4608///
4609/// It would be great to be able to express per-candidate problems
4610/// more richly for those diagnostic clients that cared, but we'd
4611/// still have to be just as careful with the default diagnostics.
4612void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
4613                           Expr **Args, unsigned NumArgs) {
4614  FunctionDecl *Fn = Cand->Function;
4615
4616  // Note deleted candidates, but only if they're viable.
4617  if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
4618    std::string FnDesc;
4619    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4620
4621    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
4622      << FnKind << FnDesc << Fn->isDeleted();
4623    return;
4624  }
4625
4626  // We don't really have anything else to say about viable candidates.
4627  if (Cand->Viable) {
4628    S.NoteOverloadCandidate(Fn);
4629    return;
4630  }
4631
4632  switch (Cand->FailureKind) {
4633  case ovl_fail_too_many_arguments:
4634  case ovl_fail_too_few_arguments:
4635    return DiagnoseArityMismatch(S, Cand, NumArgs);
4636
4637  case ovl_fail_bad_deduction:
4638    return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
4639
4640  case ovl_fail_trivial_conversion:
4641  case ovl_fail_bad_final_conversion:
4642  case ovl_fail_final_conversion_not_exact:
4643    return S.NoteOverloadCandidate(Fn);
4644
4645  case ovl_fail_bad_conversion: {
4646    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
4647    for (unsigned N = Cand->Conversions.size(); I != N; ++I)
4648      if (Cand->Conversions[I].isBad())
4649        return DiagnoseBadConversion(S, Cand, I);
4650
4651    // FIXME: this currently happens when we're called from SemaInit
4652    // when user-conversion overload fails.  Figure out how to handle
4653    // those conditions and diagnose them well.
4654    return S.NoteOverloadCandidate(Fn);
4655  }
4656  }
4657}
4658
4659void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
4660  // Desugar the type of the surrogate down to a function type,
4661  // retaining as many typedefs as possible while still showing
4662  // the function type (and, therefore, its parameter types).
4663  QualType FnType = Cand->Surrogate->getConversionType();
4664  bool isLValueReference = false;
4665  bool isRValueReference = false;
4666  bool isPointer = false;
4667  if (const LValueReferenceType *FnTypeRef =
4668        FnType->getAs<LValueReferenceType>()) {
4669    FnType = FnTypeRef->getPointeeType();
4670    isLValueReference = true;
4671  } else if (const RValueReferenceType *FnTypeRef =
4672               FnType->getAs<RValueReferenceType>()) {
4673    FnType = FnTypeRef->getPointeeType();
4674    isRValueReference = true;
4675  }
4676  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4677    FnType = FnTypePtr->getPointeeType();
4678    isPointer = true;
4679  }
4680  // Desugar down to a function type.
4681  FnType = QualType(FnType->getAs<FunctionType>(), 0);
4682  // Reconstruct the pointer/reference as appropriate.
4683  if (isPointer) FnType = S.Context.getPointerType(FnType);
4684  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
4685  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
4686
4687  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
4688    << FnType;
4689}
4690
4691void NoteBuiltinOperatorCandidate(Sema &S,
4692                                  const char *Opc,
4693                                  SourceLocation OpLoc,
4694                                  OverloadCandidate *Cand) {
4695  assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
4696  std::string TypeStr("operator");
4697  TypeStr += Opc;
4698  TypeStr += "(";
4699  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4700  if (Cand->Conversions.size() == 1) {
4701    TypeStr += ")";
4702    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
4703  } else {
4704    TypeStr += ", ";
4705    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4706    TypeStr += ")";
4707    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
4708  }
4709}
4710
4711void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
4712                                  OverloadCandidate *Cand) {
4713  unsigned NoOperands = Cand->Conversions.size();
4714  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4715    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4716    if (ICS.isBad()) break; // all meaningless after first invalid
4717    if (!ICS.isAmbiguous()) continue;
4718
4719    S.DiagnoseAmbiguousConversion(ICS, OpLoc,
4720                              S.PDiag(diag::note_ambiguous_type_conversion));
4721  }
4722}
4723
4724SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
4725  if (Cand->Function)
4726    return Cand->Function->getLocation();
4727  if (Cand->IsSurrogate)
4728    return Cand->Surrogate->getLocation();
4729  return SourceLocation();
4730}
4731
4732struct CompareOverloadCandidatesForDisplay {
4733  Sema &S;
4734  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
4735
4736  bool operator()(const OverloadCandidate *L,
4737                  const OverloadCandidate *R) {
4738    // Fast-path this check.
4739    if (L == R) return false;
4740
4741    // Order first by viability.
4742    if (L->Viable) {
4743      if (!R->Viable) return true;
4744
4745      // TODO: introduce a tri-valued comparison for overload
4746      // candidates.  Would be more worthwhile if we had a sort
4747      // that could exploit it.
4748      if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
4749      if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
4750    } else if (R->Viable)
4751      return false;
4752
4753    assert(L->Viable == R->Viable);
4754
4755    // Criteria by which we can sort non-viable candidates:
4756    if (!L->Viable) {
4757      // 1. Arity mismatches come after other candidates.
4758      if (L->FailureKind == ovl_fail_too_many_arguments ||
4759          L->FailureKind == ovl_fail_too_few_arguments)
4760        return false;
4761      if (R->FailureKind == ovl_fail_too_many_arguments ||
4762          R->FailureKind == ovl_fail_too_few_arguments)
4763        return true;
4764
4765      // 2. Bad conversions come first and are ordered by the number
4766      // of bad conversions and quality of good conversions.
4767      if (L->FailureKind == ovl_fail_bad_conversion) {
4768        if (R->FailureKind != ovl_fail_bad_conversion)
4769          return true;
4770
4771        // If there's any ordering between the defined conversions...
4772        // FIXME: this might not be transitive.
4773        assert(L->Conversions.size() == R->Conversions.size());
4774
4775        int leftBetter = 0;
4776        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
4777        for (unsigned E = L->Conversions.size(); I != E; ++I) {
4778          switch (S.CompareImplicitConversionSequences(L->Conversions[I],
4779                                                       R->Conversions[I])) {
4780          case ImplicitConversionSequence::Better:
4781            leftBetter++;
4782            break;
4783
4784          case ImplicitConversionSequence::Worse:
4785            leftBetter--;
4786            break;
4787
4788          case ImplicitConversionSequence::Indistinguishable:
4789            break;
4790          }
4791        }
4792        if (leftBetter > 0) return true;
4793        if (leftBetter < 0) return false;
4794
4795      } else if (R->FailureKind == ovl_fail_bad_conversion)
4796        return false;
4797
4798      // TODO: others?
4799    }
4800
4801    // Sort everything else by location.
4802    SourceLocation LLoc = GetLocationForCandidate(L);
4803    SourceLocation RLoc = GetLocationForCandidate(R);
4804
4805    // Put candidates without locations (e.g. builtins) at the end.
4806    if (LLoc.isInvalid()) return false;
4807    if (RLoc.isInvalid()) return true;
4808
4809    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
4810  }
4811};
4812
4813/// CompleteNonViableCandidate - Normally, overload resolution only
4814/// computes up to the first
4815void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
4816                                Expr **Args, unsigned NumArgs) {
4817  assert(!Cand->Viable);
4818
4819  // Don't do anything on failures other than bad conversion.
4820  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
4821
4822  // Skip forward to the first bad conversion.
4823  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
4824  unsigned ConvCount = Cand->Conversions.size();
4825  while (true) {
4826    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
4827    ConvIdx++;
4828    if (Cand->Conversions[ConvIdx - 1].isBad())
4829      break;
4830  }
4831
4832  if (ConvIdx == ConvCount)
4833    return;
4834
4835  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
4836         "remaining conversion is initialized?");
4837
4838  // FIXME: these should probably be preserved from the overload
4839  // operation somehow.
4840  bool SuppressUserConversions = false;
4841  bool ForceRValue = false;
4842
4843  const FunctionProtoType* Proto;
4844  unsigned ArgIdx = ConvIdx;
4845
4846  if (Cand->IsSurrogate) {
4847    QualType ConvType
4848      = Cand->Surrogate->getConversionType().getNonReferenceType();
4849    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4850      ConvType = ConvPtrType->getPointeeType();
4851    Proto = ConvType->getAs<FunctionProtoType>();
4852    ArgIdx--;
4853  } else if (Cand->Function) {
4854    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
4855    if (isa<CXXMethodDecl>(Cand->Function) &&
4856        !isa<CXXConstructorDecl>(Cand->Function))
4857      ArgIdx--;
4858  } else {
4859    // Builtin binary operator with a bad first conversion.
4860    assert(ConvCount <= 3);
4861    for (; ConvIdx != ConvCount; ++ConvIdx)
4862      Cand->Conversions[ConvIdx]
4863        = S.TryCopyInitialization(Args[ConvIdx],
4864                                  Cand->BuiltinTypes.ParamTypes[ConvIdx],
4865                                  SuppressUserConversions, ForceRValue,
4866                                  /*InOverloadResolution*/ true);
4867    return;
4868  }
4869
4870  // Fill in the rest of the conversions.
4871  unsigned NumArgsInProto = Proto->getNumArgs();
4872  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
4873    if (ArgIdx < NumArgsInProto)
4874      Cand->Conversions[ConvIdx]
4875        = S.TryCopyInitialization(Args[ArgIdx], Proto->getArgType(ArgIdx),
4876                                  SuppressUserConversions, ForceRValue,
4877                                  /*InOverloadResolution=*/true);
4878    else
4879      Cand->Conversions[ConvIdx].setEllipsis();
4880  }
4881}
4882
4883} // end anonymous namespace
4884
4885/// PrintOverloadCandidates - When overload resolution fails, prints
4886/// diagnostic messages containing the candidates in the candidate
4887/// set.
4888void
4889Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
4890                              OverloadCandidateDisplayKind OCD,
4891                              Expr **Args, unsigned NumArgs,
4892                              const char *Opc,
4893                              SourceLocation OpLoc) {
4894  // Sort the candidates by viability and position.  Sorting directly would
4895  // be prohibitive, so we make a set of pointers and sort those.
4896  llvm::SmallVector<OverloadCandidate*, 32> Cands;
4897  if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
4898  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4899                                  LastCand = CandidateSet.end();
4900       Cand != LastCand; ++Cand) {
4901    if (Cand->Viable)
4902      Cands.push_back(Cand);
4903    else if (OCD == OCD_AllCandidates) {
4904      CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
4905      Cands.push_back(Cand);
4906    }
4907  }
4908
4909  std::sort(Cands.begin(), Cands.end(),
4910            CompareOverloadCandidatesForDisplay(*this));
4911
4912  bool ReportedAmbiguousConversions = false;
4913
4914  llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
4915  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
4916    OverloadCandidate *Cand = *I;
4917
4918    if (Cand->Function)
4919      NoteFunctionCandidate(*this, Cand, Args, NumArgs);
4920    else if (Cand->IsSurrogate)
4921      NoteSurrogateCandidate(*this, Cand);
4922
4923    // This a builtin candidate.  We do not, in general, want to list
4924    // every possible builtin candidate.
4925    else if (Cand->Viable) {
4926      // Generally we only see ambiguities including viable builtin
4927      // operators if overload resolution got screwed up by an
4928      // ambiguous user-defined conversion.
4929      //
4930      // FIXME: It's quite possible for different conversions to see
4931      // different ambiguities, though.
4932      if (!ReportedAmbiguousConversions) {
4933        NoteAmbiguousUserConversions(*this, OpLoc, Cand);
4934        ReportedAmbiguousConversions = true;
4935      }
4936
4937      // If this is a viable builtin, print it.
4938      NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
4939    }
4940  }
4941}
4942
4943static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
4944  if (isa<UnresolvedLookupExpr>(E))
4945    return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
4946
4947  return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
4948}
4949
4950/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4951/// an overloaded function (C++ [over.over]), where @p From is an
4952/// expression with overloaded function type and @p ToType is the type
4953/// we're trying to resolve to. For example:
4954///
4955/// @code
4956/// int f(double);
4957/// int f(int);
4958///
4959/// int (*pfd)(double) = f; // selects f(double)
4960/// @endcode
4961///
4962/// This routine returns the resulting FunctionDecl if it could be
4963/// resolved, and NULL otherwise. When @p Complain is true, this
4964/// routine will emit diagnostics if there is an error.
4965FunctionDecl *
4966Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
4967                                         bool Complain,
4968                                         DeclAccessPair &FoundResult) {
4969  QualType FunctionType = ToType;
4970  bool IsMember = false;
4971  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
4972    FunctionType = ToTypePtr->getPointeeType();
4973  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
4974    FunctionType = ToTypeRef->getPointeeType();
4975  else if (const MemberPointerType *MemTypePtr =
4976                    ToType->getAs<MemberPointerType>()) {
4977    FunctionType = MemTypePtr->getPointeeType();
4978    IsMember = true;
4979  }
4980
4981  // We only look at pointers or references to functions.
4982  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
4983  if (!FunctionType->isFunctionType())
4984    return 0;
4985
4986  // Find the actual overloaded function declaration.
4987  if (From->getType() != Context.OverloadTy)
4988    return 0;
4989
4990  // C++ [over.over]p1:
4991  //   [...] [Note: any redundant set of parentheses surrounding the
4992  //   overloaded function name is ignored (5.1). ]
4993  // C++ [over.over]p1:
4994  //   [...] The overloaded function name can be preceded by the &
4995  //   operator.
4996  OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
4997  TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
4998  if (OvlExpr->hasExplicitTemplateArgs()) {
4999    OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5000    ExplicitTemplateArgs = &ETABuffer;
5001  }
5002
5003  // Look through all of the overloaded functions, searching for one
5004  // whose type matches exactly.
5005  llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
5006  llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5007
5008  bool FoundNonTemplateFunction = false;
5009  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5010         E = OvlExpr->decls_end(); I != E; ++I) {
5011    // Look through any using declarations to find the underlying function.
5012    NamedDecl *Fn = (*I)->getUnderlyingDecl();
5013
5014    // C++ [over.over]p3:
5015    //   Non-member functions and static member functions match
5016    //   targets of type "pointer-to-function" or "reference-to-function."
5017    //   Nonstatic member functions match targets of
5018    //   type "pointer-to-member-function."
5019    // Note that according to DR 247, the containing class does not matter.
5020
5021    if (FunctionTemplateDecl *FunctionTemplate
5022          = dyn_cast<FunctionTemplateDecl>(Fn)) {
5023      if (CXXMethodDecl *Method
5024            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
5025        // Skip non-static function templates when converting to pointer, and
5026        // static when converting to member pointer.
5027        if (Method->isStatic() == IsMember)
5028          continue;
5029      } else if (IsMember)
5030        continue;
5031
5032      // C++ [over.over]p2:
5033      //   If the name is a function template, template argument deduction is
5034      //   done (14.8.2.2), and if the argument deduction succeeds, the
5035      //   resulting template argument list is used to generate a single
5036      //   function template specialization, which is added to the set of
5037      //   overloaded functions considered.
5038      // FIXME: We don't really want to build the specialization here, do we?
5039      FunctionDecl *Specialization = 0;
5040      TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
5041      if (TemplateDeductionResult Result
5042            = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5043                                      FunctionType, Specialization, Info)) {
5044        // FIXME: make a note of the failed deduction for diagnostics.
5045        (void)Result;
5046      } else {
5047        // FIXME: If the match isn't exact, shouldn't we just drop this as
5048        // a candidate? Find a testcase before changing the code.
5049        assert(FunctionType
5050                 == Context.getCanonicalType(Specialization->getType()));
5051        Matches.push_back(std::make_pair(I.getPair(),
5052                    cast<FunctionDecl>(Specialization->getCanonicalDecl())));
5053      }
5054
5055      continue;
5056    }
5057
5058    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5059      // Skip non-static functions when converting to pointer, and static
5060      // when converting to member pointer.
5061      if (Method->isStatic() == IsMember)
5062        continue;
5063
5064      // If we have explicit template arguments, skip non-templates.
5065      if (OvlExpr->hasExplicitTemplateArgs())
5066        continue;
5067    } else if (IsMember)
5068      continue;
5069
5070    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
5071      QualType ResultTy;
5072      if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5073          IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5074                               ResultTy)) {
5075        Matches.push_back(std::make_pair(I.getPair(),
5076                           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
5077        FoundNonTemplateFunction = true;
5078      }
5079    }
5080  }
5081
5082  // If there were 0 or 1 matches, we're done.
5083  if (Matches.empty())
5084    return 0;
5085  else if (Matches.size() == 1) {
5086    FunctionDecl *Result = Matches[0].second;
5087    FoundResult = Matches[0].first;
5088    MarkDeclarationReferenced(From->getLocStart(), Result);
5089    if (Complain)
5090      CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
5091    return Result;
5092  }
5093
5094  // C++ [over.over]p4:
5095  //   If more than one function is selected, [...]
5096  if (!FoundNonTemplateFunction) {
5097    //   [...] and any given function template specialization F1 is
5098    //   eliminated if the set contains a second function template
5099    //   specialization whose function template is more specialized
5100    //   than the function template of F1 according to the partial
5101    //   ordering rules of 14.5.5.2.
5102
5103    // The algorithm specified above is quadratic. We instead use a
5104    // two-pass algorithm (similar to the one used to identify the
5105    // best viable function in an overload set) that identifies the
5106    // best function template (if it exists).
5107
5108    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5109    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5110      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
5111
5112    UnresolvedSetIterator Result =
5113        getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
5114                           TPOC_Other, From->getLocStart(),
5115                           PDiag(),
5116                           PDiag(diag::err_addr_ovl_ambiguous)
5117                               << Matches[0].second->getDeclName(),
5118                           PDiag(diag::note_ovl_candidate)
5119                               << (unsigned) oc_function_template);
5120    assert(Result != MatchesCopy.end() && "no most-specialized template");
5121    MarkDeclarationReferenced(From->getLocStart(), *Result);
5122    FoundResult = Matches[Result - MatchesCopy.begin()].first;
5123    if (Complain)
5124      CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
5125    return cast<FunctionDecl>(*Result);
5126  }
5127
5128  //   [...] any function template specializations in the set are
5129  //   eliminated if the set also contains a non-template function, [...]
5130  for (unsigned I = 0, N = Matches.size(); I != N; ) {
5131    if (Matches[I].second->getPrimaryTemplate() == 0)
5132      ++I;
5133    else {
5134      Matches[I] = Matches[--N];
5135      Matches.set_size(N);
5136    }
5137  }
5138
5139  // [...] After such eliminations, if any, there shall remain exactly one
5140  // selected function.
5141  if (Matches.size() == 1) {
5142    MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
5143    FoundResult = Matches[0].first;
5144    if (Complain)
5145      CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5146    return cast<FunctionDecl>(Matches[0].second);
5147  }
5148
5149  // FIXME: We should probably return the same thing that BestViableFunction
5150  // returns (even if we issue the diagnostics here).
5151  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
5152    << Matches[0].second->getDeclName();
5153  for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5154    NoteOverloadCandidate(Matches[I].second);
5155  return 0;
5156}
5157
5158/// \brief Given an expression that refers to an overloaded function, try to
5159/// resolve that overloaded function expression down to a single function.
5160///
5161/// This routine can only resolve template-ids that refer to a single function
5162/// template, where that template-id refers to a single template whose template
5163/// arguments are either provided by the template-id or have defaults,
5164/// as described in C++0x [temp.arg.explicit]p3.
5165FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5166  // C++ [over.over]p1:
5167  //   [...] [Note: any redundant set of parentheses surrounding the
5168  //   overloaded function name is ignored (5.1). ]
5169  // C++ [over.over]p1:
5170  //   [...] The overloaded function name can be preceded by the &
5171  //   operator.
5172
5173  if (From->getType() != Context.OverloadTy)
5174    return 0;
5175
5176  OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5177
5178  // If we didn't actually find any template-ids, we're done.
5179  if (!OvlExpr->hasExplicitTemplateArgs())
5180    return 0;
5181
5182  TemplateArgumentListInfo ExplicitTemplateArgs;
5183  OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
5184
5185  // Look through all of the overloaded functions, searching for one
5186  // whose type matches exactly.
5187  FunctionDecl *Matched = 0;
5188  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5189         E = OvlExpr->decls_end(); I != E; ++I) {
5190    // C++0x [temp.arg.explicit]p3:
5191    //   [...] In contexts where deduction is done and fails, or in contexts
5192    //   where deduction is not done, if a template argument list is
5193    //   specified and it, along with any default template arguments,
5194    //   identifies a single function template specialization, then the
5195    //   template-id is an lvalue for the function template specialization.
5196    FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5197
5198    // C++ [over.over]p2:
5199    //   If the name is a function template, template argument deduction is
5200    //   done (14.8.2.2), and if the argument deduction succeeds, the
5201    //   resulting template argument list is used to generate a single
5202    //   function template specialization, which is added to the set of
5203    //   overloaded functions considered.
5204    FunctionDecl *Specialization = 0;
5205    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
5206    if (TemplateDeductionResult Result
5207          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5208                                    Specialization, Info)) {
5209      // FIXME: make a note of the failed deduction for diagnostics.
5210      (void)Result;
5211      continue;
5212    }
5213
5214    // Multiple matches; we can't resolve to a single declaration.
5215    if (Matched)
5216      return 0;
5217
5218    Matched = Specialization;
5219  }
5220
5221  return Matched;
5222}
5223
5224/// \brief Add a single candidate to the overload set.
5225static void AddOverloadedCallCandidate(Sema &S,
5226                                       DeclAccessPair FoundDecl,
5227                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
5228                                       Expr **Args, unsigned NumArgs,
5229                                       OverloadCandidateSet &CandidateSet,
5230                                       bool PartialOverloading) {
5231  NamedDecl *Callee = FoundDecl.getDecl();
5232  if (isa<UsingShadowDecl>(Callee))
5233    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5234
5235  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
5236    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
5237    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
5238                           false, false, PartialOverloading);
5239    return;
5240  }
5241
5242  if (FunctionTemplateDecl *FuncTemplate
5243      = dyn_cast<FunctionTemplateDecl>(Callee)) {
5244    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5245                                   ExplicitTemplateArgs,
5246                                   Args, NumArgs, CandidateSet);
5247    return;
5248  }
5249
5250  assert(false && "unhandled case in overloaded call candidate");
5251
5252  // do nothing?
5253}
5254
5255/// \brief Add the overload candidates named by callee and/or found by argument
5256/// dependent lookup to the given overload set.
5257void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
5258                                       Expr **Args, unsigned NumArgs,
5259                                       OverloadCandidateSet &CandidateSet,
5260                                       bool PartialOverloading) {
5261
5262#ifndef NDEBUG
5263  // Verify that ArgumentDependentLookup is consistent with the rules
5264  // in C++0x [basic.lookup.argdep]p3:
5265  //
5266  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
5267  //   and let Y be the lookup set produced by argument dependent
5268  //   lookup (defined as follows). If X contains
5269  //
5270  //     -- a declaration of a class member, or
5271  //
5272  //     -- a block-scope function declaration that is not a
5273  //        using-declaration, or
5274  //
5275  //     -- a declaration that is neither a function or a function
5276  //        template
5277  //
5278  //   then Y is empty.
5279
5280  if (ULE->requiresADL()) {
5281    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5282           E = ULE->decls_end(); I != E; ++I) {
5283      assert(!(*I)->getDeclContext()->isRecord());
5284      assert(isa<UsingShadowDecl>(*I) ||
5285             !(*I)->getDeclContext()->isFunctionOrMethod());
5286      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
5287    }
5288  }
5289#endif
5290
5291  // It would be nice to avoid this copy.
5292  TemplateArgumentListInfo TABuffer;
5293  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5294  if (ULE->hasExplicitTemplateArgs()) {
5295    ULE->copyTemplateArgumentsInto(TABuffer);
5296    ExplicitTemplateArgs = &TABuffer;
5297  }
5298
5299  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5300         E = ULE->decls_end(); I != E; ++I)
5301    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
5302                               Args, NumArgs, CandidateSet,
5303                               PartialOverloading);
5304
5305  if (ULE->requiresADL())
5306    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5307                                         Args, NumArgs,
5308                                         ExplicitTemplateArgs,
5309                                         CandidateSet,
5310                                         PartialOverloading);
5311}
5312
5313static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5314                                      Expr **Args, unsigned NumArgs) {
5315  Fn->Destroy(SemaRef.Context);
5316  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5317    Args[Arg]->Destroy(SemaRef.Context);
5318  return SemaRef.ExprError();
5319}
5320
5321/// Attempts to recover from a call where no functions were found.
5322///
5323/// Returns true if new candidates were found.
5324static Sema::OwningExprResult
5325BuildRecoveryCallExpr(Sema &SemaRef, Expr *Fn,
5326                      UnresolvedLookupExpr *ULE,
5327                      SourceLocation LParenLoc,
5328                      Expr **Args, unsigned NumArgs,
5329                      SourceLocation *CommaLocs,
5330                      SourceLocation RParenLoc) {
5331
5332  CXXScopeSpec SS;
5333  if (ULE->getQualifier()) {
5334    SS.setScopeRep(ULE->getQualifier());
5335    SS.setRange(ULE->getQualifierRange());
5336  }
5337
5338  TemplateArgumentListInfo TABuffer;
5339  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5340  if (ULE->hasExplicitTemplateArgs()) {
5341    ULE->copyTemplateArgumentsInto(TABuffer);
5342    ExplicitTemplateArgs = &TABuffer;
5343  }
5344
5345  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5346                 Sema::LookupOrdinaryName);
5347  if (SemaRef.DiagnoseEmptyLookup(/*Scope=*/0, SS, R))
5348    return Destroy(SemaRef, Fn, Args, NumArgs);
5349
5350  assert(!R.empty() && "lookup results empty despite recovery");
5351
5352  // Build an implicit member call if appropriate.  Just drop the
5353  // casts and such from the call, we don't really care.
5354  Sema::OwningExprResult NewFn = SemaRef.ExprError();
5355  if ((*R.begin())->isCXXClassMember())
5356    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5357  else if (ExplicitTemplateArgs)
5358    NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5359  else
5360    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5361
5362  if (NewFn.isInvalid())
5363    return Destroy(SemaRef, Fn, Args, NumArgs);
5364
5365  Fn->Destroy(SemaRef.Context);
5366
5367  // This shouldn't cause an infinite loop because we're giving it
5368  // an expression with non-empty lookup results, which should never
5369  // end up here.
5370  return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5371                         Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5372                               CommaLocs, RParenLoc);
5373}
5374
5375/// ResolveOverloadedCallFn - Given the call expression that calls Fn
5376/// (which eventually refers to the declaration Func) and the call
5377/// arguments Args/NumArgs, attempt to resolve the function call down
5378/// to a specific function. If overload resolution succeeds, returns
5379/// the function declaration produced by overload
5380/// resolution. Otherwise, emits diagnostics, deletes all of the
5381/// arguments and Fn, and returns NULL.
5382Sema::OwningExprResult
5383Sema::BuildOverloadedCallExpr(Expr *Fn, UnresolvedLookupExpr *ULE,
5384                              SourceLocation LParenLoc,
5385                              Expr **Args, unsigned NumArgs,
5386                              SourceLocation *CommaLocs,
5387                              SourceLocation RParenLoc) {
5388#ifndef NDEBUG
5389  if (ULE->requiresADL()) {
5390    // To do ADL, we must have found an unqualified name.
5391    assert(!ULE->getQualifier() && "qualified name with ADL");
5392
5393    // We don't perform ADL for implicit declarations of builtins.
5394    // Verify that this was correctly set up.
5395    FunctionDecl *F;
5396    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5397        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5398        F->getBuiltinID() && F->isImplicit())
5399      assert(0 && "performing ADL for builtin");
5400
5401    // We don't perform ADL in C.
5402    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5403  }
5404#endif
5405
5406  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
5407
5408  // Add the functions denoted by the callee to the set of candidate
5409  // functions, including those from argument-dependent lookup.
5410  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
5411
5412  // If we found nothing, try to recover.
5413  // AddRecoveryCallCandidates diagnoses the error itself, so we just
5414  // bailout out if it fails.
5415  if (CandidateSet.empty())
5416    return BuildRecoveryCallExpr(*this, Fn, ULE, LParenLoc, Args, NumArgs,
5417                                 CommaLocs, RParenLoc);
5418
5419  OverloadCandidateSet::iterator Best;
5420  switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
5421  case OR_Success: {
5422    FunctionDecl *FDecl = Best->Function;
5423    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
5424    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
5425    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
5426  }
5427
5428  case OR_No_Viable_Function:
5429    Diag(Fn->getSourceRange().getBegin(),
5430         diag::err_ovl_no_viable_function_in_call)
5431      << ULE->getName() << Fn->getSourceRange();
5432    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
5433    break;
5434
5435  case OR_Ambiguous:
5436    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
5437      << ULE->getName() << Fn->getSourceRange();
5438    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
5439    break;
5440
5441  case OR_Deleted:
5442    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
5443      << Best->Function->isDeleted()
5444      << ULE->getName()
5445      << Fn->getSourceRange();
5446    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
5447    break;
5448  }
5449
5450  // Overload resolution failed. Destroy all of the subexpressions and
5451  // return NULL.
5452  Fn->Destroy(Context);
5453  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5454    Args[Arg]->Destroy(Context);
5455  return ExprError();
5456}
5457
5458static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
5459  return Functions.size() > 1 ||
5460    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
5461}
5462
5463/// \brief Create a unary operation that may resolve to an overloaded
5464/// operator.
5465///
5466/// \param OpLoc The location of the operator itself (e.g., '*').
5467///
5468/// \param OpcIn The UnaryOperator::Opcode that describes this
5469/// operator.
5470///
5471/// \param Functions The set of non-member functions that will be
5472/// considered by overload resolution. The caller needs to build this
5473/// set based on the context using, e.g.,
5474/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5475/// set should not contain any member functions; those will be added
5476/// by CreateOverloadedUnaryOp().
5477///
5478/// \param input The input argument.
5479Sema::OwningExprResult
5480Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
5481                              const UnresolvedSetImpl &Fns,
5482                              ExprArg input) {
5483  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5484  Expr *Input = (Expr *)input.get();
5485
5486  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
5487  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
5488  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5489
5490  Expr *Args[2] = { Input, 0 };
5491  unsigned NumArgs = 1;
5492
5493  // For post-increment and post-decrement, add the implicit '0' as
5494  // the second argument, so that we know this is a post-increment or
5495  // post-decrement.
5496  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
5497    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
5498    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
5499                                           SourceLocation());
5500    NumArgs = 2;
5501  }
5502
5503  if (Input->isTypeDependent()) {
5504    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
5505    UnresolvedLookupExpr *Fn
5506      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
5507                                     0, SourceRange(), OpName, OpLoc,
5508                                     /*ADL*/ true, IsOverloaded(Fns));
5509    Fn->addDecls(Fns.begin(), Fns.end());
5510
5511    input.release();
5512    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5513                                                   &Args[0], NumArgs,
5514                                                   Context.DependentTy,
5515                                                   OpLoc));
5516  }
5517
5518  // Build an empty overload set.
5519  OverloadCandidateSet CandidateSet(OpLoc);
5520
5521  // Add the candidates from the given function set.
5522  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
5523
5524  // Add operator candidates that are member functions.
5525  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5526
5527  // Add candidates from ADL.
5528  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5529                                       Args, NumArgs,
5530                                       /*ExplicitTemplateArgs*/ 0,
5531                                       CandidateSet);
5532
5533  // Add builtin operator candidates.
5534  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
5535
5536  // Perform overload resolution.
5537  OverloadCandidateSet::iterator Best;
5538  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5539  case OR_Success: {
5540    // We found a built-in operator or an overloaded operator.
5541    FunctionDecl *FnDecl = Best->Function;
5542
5543    if (FnDecl) {
5544      // We matched an overloaded operator. Build a call to that
5545      // operator.
5546
5547      // Convert the arguments.
5548      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5549        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
5550
5551        if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
5552                                                Best->FoundDecl, Method))
5553          return ExprError();
5554      } else {
5555        // Convert the arguments.
5556        OwningExprResult InputInit
5557          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5558                                                      FnDecl->getParamDecl(0)),
5559                                      SourceLocation(),
5560                                      move(input));
5561        if (InputInit.isInvalid())
5562          return ExprError();
5563
5564        input = move(InputInit);
5565        Input = (Expr *)input.get();
5566      }
5567
5568      // Determine the result type
5569      QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
5570
5571      // Build the actual expression node.
5572      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5573                                               SourceLocation());
5574      UsualUnaryConversions(FnExpr);
5575
5576      input.release();
5577      Args[0] = Input;
5578      ExprOwningPtr<CallExpr> TheCall(this,
5579        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5580                                          Args, NumArgs, ResultTy, OpLoc));
5581
5582      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5583                              FnDecl))
5584        return ExprError();
5585
5586      return MaybeBindToTemporary(TheCall.release());
5587    } else {
5588      // We matched a built-in operator. Convert the arguments, then
5589      // break out so that we will build the appropriate built-in
5590      // operator node.
5591        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
5592                                      Best->Conversions[0], AA_Passing))
5593          return ExprError();
5594
5595        break;
5596      }
5597    }
5598
5599    case OR_No_Viable_Function:
5600      // No viable function; fall through to handling this as a
5601      // built-in operator, which will produce an error message for us.
5602      break;
5603
5604    case OR_Ambiguous:
5605      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5606          << UnaryOperator::getOpcodeStr(Opc)
5607          << Input->getSourceRange();
5608      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
5609                              UnaryOperator::getOpcodeStr(Opc), OpLoc);
5610      return ExprError();
5611
5612    case OR_Deleted:
5613      Diag(OpLoc, diag::err_ovl_deleted_oper)
5614        << Best->Function->isDeleted()
5615        << UnaryOperator::getOpcodeStr(Opc)
5616        << Input->getSourceRange();
5617      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
5618      return ExprError();
5619    }
5620
5621  // Either we found no viable overloaded operator or we matched a
5622  // built-in operator. In either case, fall through to trying to
5623  // build a built-in operation.
5624  input.release();
5625  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
5626}
5627
5628/// \brief Create a binary operation that may resolve to an overloaded
5629/// operator.
5630///
5631/// \param OpLoc The location of the operator itself (e.g., '+').
5632///
5633/// \param OpcIn The BinaryOperator::Opcode that describes this
5634/// operator.
5635///
5636/// \param Functions The set of non-member functions that will be
5637/// considered by overload resolution. The caller needs to build this
5638/// set based on the context using, e.g.,
5639/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
5640/// set should not contain any member functions; those will be added
5641/// by CreateOverloadedBinOp().
5642///
5643/// \param LHS Left-hand argument.
5644/// \param RHS Right-hand argument.
5645Sema::OwningExprResult
5646Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
5647                            unsigned OpcIn,
5648                            const UnresolvedSetImpl &Fns,
5649                            Expr *LHS, Expr *RHS) {
5650  Expr *Args[2] = { LHS, RHS };
5651  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
5652
5653  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
5654  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
5655  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5656
5657  // If either side is type-dependent, create an appropriate dependent
5658  // expression.
5659  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5660    if (Fns.empty()) {
5661      // If there are no functions to store, just build a dependent
5662      // BinaryOperator or CompoundAssignment.
5663      if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
5664        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
5665                                                  Context.DependentTy, OpLoc));
5666
5667      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
5668                                                        Context.DependentTy,
5669                                                        Context.DependentTy,
5670                                                        Context.DependentTy,
5671                                                        OpLoc));
5672    }
5673
5674    // FIXME: save results of ADL from here?
5675    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
5676    UnresolvedLookupExpr *Fn
5677      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
5678                                     0, SourceRange(), OpName, OpLoc,
5679                                     /*ADL*/ true, IsOverloaded(Fns));
5680
5681    Fn->addDecls(Fns.begin(), Fns.end());
5682    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
5683                                                   Args, 2,
5684                                                   Context.DependentTy,
5685                                                   OpLoc));
5686  }
5687
5688  // If this is the .* operator, which is not overloadable, just
5689  // create a built-in binary operator.
5690  if (Opc == BinaryOperator::PtrMemD)
5691    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5692
5693  // If this is the assignment operator, we only perform overload resolution
5694  // if the left-hand side is a class or enumeration type. This is actually
5695  // a hack. The standard requires that we do overload resolution between the
5696  // various built-in candidates, but as DR507 points out, this can lead to
5697  // problems. So we do it this way, which pretty much follows what GCC does.
5698  // Note that we go the traditional code path for compound assignment forms.
5699  if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
5700    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5701
5702  // Build an empty overload set.
5703  OverloadCandidateSet CandidateSet(OpLoc);
5704
5705  // Add the candidates from the given function set.
5706  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
5707
5708  // Add operator candidates that are member functions.
5709  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5710
5711  // Add candidates from ADL.
5712  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
5713                                       Args, 2,
5714                                       /*ExplicitTemplateArgs*/ 0,
5715                                       CandidateSet);
5716
5717  // Add builtin operator candidates.
5718  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
5719
5720  // Perform overload resolution.
5721  OverloadCandidateSet::iterator Best;
5722  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5723    case OR_Success: {
5724      // We found a built-in operator or an overloaded operator.
5725      FunctionDecl *FnDecl = Best->Function;
5726
5727      if (FnDecl) {
5728        // We matched an overloaded operator. Build a call to that
5729        // operator.
5730
5731        // Convert the arguments.
5732        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5733          // Best->Access is only meaningful for class members.
5734          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
5735
5736          OwningExprResult Arg1
5737            = PerformCopyInitialization(
5738                                        InitializedEntity::InitializeParameter(
5739                                                        FnDecl->getParamDecl(0)),
5740                                        SourceLocation(),
5741                                        Owned(Args[1]));
5742          if (Arg1.isInvalid())
5743            return ExprError();
5744
5745          if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5746                                                  Best->FoundDecl, Method))
5747            return ExprError();
5748
5749          Args[1] = RHS = Arg1.takeAs<Expr>();
5750        } else {
5751          // Convert the arguments.
5752          OwningExprResult Arg0
5753            = PerformCopyInitialization(
5754                                        InitializedEntity::InitializeParameter(
5755                                                        FnDecl->getParamDecl(0)),
5756                                        SourceLocation(),
5757                                        Owned(Args[0]));
5758          if (Arg0.isInvalid())
5759            return ExprError();
5760
5761          OwningExprResult Arg1
5762            = PerformCopyInitialization(
5763                                        InitializedEntity::InitializeParameter(
5764                                                        FnDecl->getParamDecl(1)),
5765                                        SourceLocation(),
5766                                        Owned(Args[1]));
5767          if (Arg1.isInvalid())
5768            return ExprError();
5769          Args[0] = LHS = Arg0.takeAs<Expr>();
5770          Args[1] = RHS = Arg1.takeAs<Expr>();
5771        }
5772
5773        // Determine the result type
5774        QualType ResultTy
5775          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5776        ResultTy = ResultTy.getNonReferenceType();
5777
5778        // Build the actual expression node.
5779        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5780                                                 OpLoc);
5781        UsualUnaryConversions(FnExpr);
5782
5783        ExprOwningPtr<CXXOperatorCallExpr>
5784          TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5785                                                          Args, 2, ResultTy,
5786                                                          OpLoc));
5787
5788        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5789                                FnDecl))
5790          return ExprError();
5791
5792        return MaybeBindToTemporary(TheCall.release());
5793      } else {
5794        // We matched a built-in operator. Convert the arguments, then
5795        // break out so that we will build the appropriate built-in
5796        // operator node.
5797        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5798                                      Best->Conversions[0], AA_Passing) ||
5799            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5800                                      Best->Conversions[1], AA_Passing))
5801          return ExprError();
5802
5803        break;
5804      }
5805    }
5806
5807    case OR_No_Viable_Function: {
5808      // C++ [over.match.oper]p9:
5809      //   If the operator is the operator , [...] and there are no
5810      //   viable functions, then the operator is assumed to be the
5811      //   built-in operator and interpreted according to clause 5.
5812      if (Opc == BinaryOperator::Comma)
5813        break;
5814
5815      // For class as left operand for assignment or compound assigment operator
5816      // do not fall through to handling in built-in, but report that no overloaded
5817      // assignment operator found
5818      OwningExprResult Result = ExprError();
5819      if (Args[0]->getType()->isRecordType() &&
5820          Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
5821        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
5822             << BinaryOperator::getOpcodeStr(Opc)
5823             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5824      } else {
5825        // No viable function; try to create a built-in operation, which will
5826        // produce an error. Then, show the non-viable candidates.
5827        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5828      }
5829      assert(Result.isInvalid() &&
5830             "C++ binary operator overloading is missing candidates!");
5831      if (Result.isInvalid())
5832        PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
5833                                BinaryOperator::getOpcodeStr(Opc), OpLoc);
5834      return move(Result);
5835    }
5836
5837    case OR_Ambiguous:
5838      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5839          << BinaryOperator::getOpcodeStr(Opc)
5840          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5841      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
5842                              BinaryOperator::getOpcodeStr(Opc), OpLoc);
5843      return ExprError();
5844
5845    case OR_Deleted:
5846      Diag(OpLoc, diag::err_ovl_deleted_oper)
5847        << Best->Function->isDeleted()
5848        << BinaryOperator::getOpcodeStr(Opc)
5849        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5850      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
5851      return ExprError();
5852  }
5853
5854  // We matched a built-in operator; build it.
5855  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5856}
5857
5858Action::OwningExprResult
5859Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5860                                         SourceLocation RLoc,
5861                                         ExprArg Base, ExprArg Idx) {
5862  Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5863                    static_cast<Expr*>(Idx.get()) };
5864  DeclarationName OpName =
5865      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5866
5867  // If either side is type-dependent, create an appropriate dependent
5868  // expression.
5869  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5870
5871    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
5872    UnresolvedLookupExpr *Fn
5873      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
5874                                     0, SourceRange(), OpName, LLoc,
5875                                     /*ADL*/ true, /*Overloaded*/ false);
5876    // Can't add any actual overloads yet
5877
5878    Base.release();
5879    Idx.release();
5880    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5881                                                   Args, 2,
5882                                                   Context.DependentTy,
5883                                                   RLoc));
5884  }
5885
5886  // Build an empty overload set.
5887  OverloadCandidateSet CandidateSet(LLoc);
5888
5889  // Subscript can only be overloaded as a member function.
5890
5891  // Add operator candidates that are member functions.
5892  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5893
5894  // Add builtin operator candidates.
5895  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5896
5897  // Perform overload resolution.
5898  OverloadCandidateSet::iterator Best;
5899  switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5900    case OR_Success: {
5901      // We found a built-in operator or an overloaded operator.
5902      FunctionDecl *FnDecl = Best->Function;
5903
5904      if (FnDecl) {
5905        // We matched an overloaded operator. Build a call to that
5906        // operator.
5907
5908        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
5909
5910        // Convert the arguments.
5911        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5912        if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5913                                                Best->FoundDecl, Method))
5914          return ExprError();
5915
5916        // Convert the arguments.
5917        OwningExprResult InputInit
5918          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
5919                                                      FnDecl->getParamDecl(0)),
5920                                      SourceLocation(),
5921                                      Owned(Args[1]));
5922        if (InputInit.isInvalid())
5923          return ExprError();
5924
5925        Args[1] = InputInit.takeAs<Expr>();
5926
5927        // Determine the result type
5928        QualType ResultTy
5929          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5930        ResultTy = ResultTy.getNonReferenceType();
5931
5932        // Build the actual expression node.
5933        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5934                                                 LLoc);
5935        UsualUnaryConversions(FnExpr);
5936
5937        Base.release();
5938        Idx.release();
5939        ExprOwningPtr<CXXOperatorCallExpr>
5940          TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5941                                                          FnExpr, Args, 2,
5942                                                          ResultTy, RLoc));
5943
5944        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5945                                FnDecl))
5946          return ExprError();
5947
5948        return MaybeBindToTemporary(TheCall.release());
5949      } else {
5950        // We matched a built-in operator. Convert the arguments, then
5951        // break out so that we will build the appropriate built-in
5952        // operator node.
5953        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5954                                      Best->Conversions[0], AA_Passing) ||
5955            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5956                                      Best->Conversions[1], AA_Passing))
5957          return ExprError();
5958
5959        break;
5960      }
5961    }
5962
5963    case OR_No_Viable_Function: {
5964      if (CandidateSet.empty())
5965        Diag(LLoc, diag::err_ovl_no_oper)
5966          << Args[0]->getType() << /*subscript*/ 0
5967          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5968      else
5969        Diag(LLoc, diag::err_ovl_no_viable_subscript)
5970          << Args[0]->getType()
5971          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5972      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
5973                              "[]", LLoc);
5974      return ExprError();
5975    }
5976
5977    case OR_Ambiguous:
5978      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
5979          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5980      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
5981                              "[]", LLoc);
5982      return ExprError();
5983
5984    case OR_Deleted:
5985      Diag(LLoc, diag::err_ovl_deleted_oper)
5986        << Best->Function->isDeleted() << "[]"
5987        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5988      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
5989                              "[]", LLoc);
5990      return ExprError();
5991    }
5992
5993  // We matched a built-in operator; build it.
5994  Base.release();
5995  Idx.release();
5996  return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5997                                         Owned(Args[1]), RLoc);
5998}
5999
6000/// BuildCallToMemberFunction - Build a call to a member
6001/// function. MemExpr is the expression that refers to the member
6002/// function (and includes the object parameter), Args/NumArgs are the
6003/// arguments to the function call (not including the object
6004/// parameter). The caller needs to validate that the member
6005/// expression refers to a member function or an overloaded member
6006/// function.
6007Sema::OwningExprResult
6008Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6009                                SourceLocation LParenLoc, Expr **Args,
6010                                unsigned NumArgs, SourceLocation *CommaLocs,
6011                                SourceLocation RParenLoc) {
6012  // Dig out the member expression. This holds both the object
6013  // argument and the member function we're referring to.
6014  Expr *NakedMemExpr = MemExprE->IgnoreParens();
6015
6016  MemberExpr *MemExpr;
6017  CXXMethodDecl *Method = 0;
6018  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
6019  NestedNameSpecifier *Qualifier = 0;
6020  if (isa<MemberExpr>(NakedMemExpr)) {
6021    MemExpr = cast<MemberExpr>(NakedMemExpr);
6022    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6023    FoundDecl = MemExpr->getFoundDecl();
6024    Qualifier = MemExpr->getQualifier();
6025  } else {
6026    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
6027    Qualifier = UnresExpr->getQualifier();
6028
6029    QualType ObjectType = UnresExpr->getBaseType();
6030
6031    // Add overload candidates
6032    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
6033
6034    // FIXME: avoid copy.
6035    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6036    if (UnresExpr->hasExplicitTemplateArgs()) {
6037      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6038      TemplateArgs = &TemplateArgsBuffer;
6039    }
6040
6041    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6042           E = UnresExpr->decls_end(); I != E; ++I) {
6043
6044      NamedDecl *Func = *I;
6045      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6046      if (isa<UsingShadowDecl>(Func))
6047        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6048
6049      if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
6050        // If explicit template arguments were provided, we can't call a
6051        // non-template member function.
6052        if (TemplateArgs)
6053          continue;
6054
6055        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
6056                           Args, NumArgs,
6057                           CandidateSet, /*SuppressUserConversions=*/false);
6058      } else {
6059        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
6060                                   I.getPair(), ActingDC, TemplateArgs,
6061                                   ObjectType, Args, NumArgs,
6062                                   CandidateSet,
6063                                   /*SuppressUsedConversions=*/false);
6064      }
6065    }
6066
6067    DeclarationName DeclName = UnresExpr->getMemberName();
6068
6069    OverloadCandidateSet::iterator Best;
6070    switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
6071    case OR_Success:
6072      Method = cast<CXXMethodDecl>(Best->Function);
6073      FoundDecl = Best->FoundDecl;
6074      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
6075      break;
6076
6077    case OR_No_Viable_Function:
6078      Diag(UnresExpr->getMemberLoc(),
6079           diag::err_ovl_no_viable_member_function_in_call)
6080        << DeclName << MemExprE->getSourceRange();
6081      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6082      // FIXME: Leaking incoming expressions!
6083      return ExprError();
6084
6085    case OR_Ambiguous:
6086      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
6087        << DeclName << MemExprE->getSourceRange();
6088      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6089      // FIXME: Leaking incoming expressions!
6090      return ExprError();
6091
6092    case OR_Deleted:
6093      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
6094        << Best->Function->isDeleted()
6095        << DeclName << MemExprE->getSourceRange();
6096      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6097      // FIXME: Leaking incoming expressions!
6098      return ExprError();
6099    }
6100
6101    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
6102
6103    // If overload resolution picked a static member, build a
6104    // non-member call based on that function.
6105    if (Method->isStatic()) {
6106      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6107                                   Args, NumArgs, RParenLoc);
6108    }
6109
6110    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
6111  }
6112
6113  assert(Method && "Member call to something that isn't a method?");
6114  ExprOwningPtr<CXXMemberCallExpr>
6115    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
6116                                                  NumArgs,
6117                                  Method->getResultType().getNonReferenceType(),
6118                                  RParenLoc));
6119
6120  // Check for a valid return type.
6121  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6122                          TheCall.get(), Method))
6123    return ExprError();
6124
6125  // Convert the object argument (for a non-static member function call).
6126  // We only need to do this if there was actually an overload; otherwise
6127  // it was done at lookup.
6128  Expr *ObjectArg = MemExpr->getBase();
6129  if (!Method->isStatic() &&
6130      PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6131                                          FoundDecl, Method))
6132    return ExprError();
6133  MemExpr->setBase(ObjectArg);
6134
6135  // Convert the rest of the arguments
6136  const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
6137  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
6138                              RParenLoc))
6139    return ExprError();
6140
6141  if (CheckFunctionCall(Method, TheCall.get()))
6142    return ExprError();
6143
6144  return MaybeBindToTemporary(TheCall.release());
6145}
6146
6147/// BuildCallToObjectOfClassType - Build a call to an object of class
6148/// type (C++ [over.call.object]), which can end up invoking an
6149/// overloaded function call operator (@c operator()) or performing a
6150/// user-defined conversion on the object argument.
6151Sema::ExprResult
6152Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
6153                                   SourceLocation LParenLoc,
6154                                   Expr **Args, unsigned NumArgs,
6155                                   SourceLocation *CommaLocs,
6156                                   SourceLocation RParenLoc) {
6157  assert(Object->getType()->isRecordType() && "Requires object type argument");
6158  const RecordType *Record = Object->getType()->getAs<RecordType>();
6159
6160  // C++ [over.call.object]p1:
6161  //  If the primary-expression E in the function call syntax
6162  //  evaluates to a class object of type "cv T", then the set of
6163  //  candidate functions includes at least the function call
6164  //  operators of T. The function call operators of T are obtained by
6165  //  ordinary lookup of the name operator() in the context of
6166  //  (E).operator().
6167  OverloadCandidateSet CandidateSet(LParenLoc);
6168  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
6169
6170  if (RequireCompleteType(LParenLoc, Object->getType(),
6171                          PDiag(diag::err_incomplete_object_call)
6172                          << Object->getSourceRange()))
6173    return true;
6174
6175  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6176  LookupQualifiedName(R, Record->getDecl());
6177  R.suppressDiagnostics();
6178
6179  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
6180       Oper != OperEnd; ++Oper) {
6181    AddMethodCandidate(Oper.getPair(), Object->getType(),
6182                       Args, NumArgs, CandidateSet,
6183                       /*SuppressUserConversions=*/ false);
6184  }
6185
6186  // C++ [over.call.object]p2:
6187  //   In addition, for each conversion function declared in T of the
6188  //   form
6189  //
6190  //        operator conversion-type-id () cv-qualifier;
6191  //
6192  //   where cv-qualifier is the same cv-qualification as, or a
6193  //   greater cv-qualification than, cv, and where conversion-type-id
6194  //   denotes the type "pointer to function of (P1,...,Pn) returning
6195  //   R", or the type "reference to pointer to function of
6196  //   (P1,...,Pn) returning R", or the type "reference to function
6197  //   of (P1,...,Pn) returning R", a surrogate call function [...]
6198  //   is also considered as a candidate function. Similarly,
6199  //   surrogate call functions are added to the set of candidate
6200  //   functions for each conversion function declared in an
6201  //   accessible base class provided the function is not hidden
6202  //   within T by another intervening declaration.
6203  const UnresolvedSetImpl *Conversions
6204    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
6205  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6206         E = Conversions->end(); I != E; ++I) {
6207    NamedDecl *D = *I;
6208    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6209    if (isa<UsingShadowDecl>(D))
6210      D = cast<UsingShadowDecl>(D)->getTargetDecl();
6211
6212    // Skip over templated conversion functions; they aren't
6213    // surrogates.
6214    if (isa<FunctionTemplateDecl>(D))
6215      continue;
6216
6217    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6218
6219    // Strip the reference type (if any) and then the pointer type (if
6220    // any) to get down to what might be a function type.
6221    QualType ConvType = Conv->getConversionType().getNonReferenceType();
6222    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6223      ConvType = ConvPtrType->getPointeeType();
6224
6225    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
6226      AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
6227                            Object->getType(), Args, NumArgs,
6228                            CandidateSet);
6229  }
6230
6231  // Perform overload resolution.
6232  OverloadCandidateSet::iterator Best;
6233  switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
6234  case OR_Success:
6235    // Overload resolution succeeded; we'll build the appropriate call
6236    // below.
6237    break;
6238
6239  case OR_No_Viable_Function:
6240    if (CandidateSet.empty())
6241      Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6242        << Object->getType() << /*call*/ 1
6243        << Object->getSourceRange();
6244    else
6245      Diag(Object->getSourceRange().getBegin(),
6246           diag::err_ovl_no_viable_object_call)
6247        << Object->getType() << Object->getSourceRange();
6248    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6249    break;
6250
6251  case OR_Ambiguous:
6252    Diag(Object->getSourceRange().getBegin(),
6253         diag::err_ovl_ambiguous_object_call)
6254      << Object->getType() << Object->getSourceRange();
6255    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
6256    break;
6257
6258  case OR_Deleted:
6259    Diag(Object->getSourceRange().getBegin(),
6260         diag::err_ovl_deleted_object_call)
6261      << Best->Function->isDeleted()
6262      << Object->getType() << Object->getSourceRange();
6263    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6264    break;
6265  }
6266
6267  if (Best == CandidateSet.end()) {
6268    // We had an error; delete all of the subexpressions and return
6269    // the error.
6270    Object->Destroy(Context);
6271    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6272      Args[ArgIdx]->Destroy(Context);
6273    return true;
6274  }
6275
6276  if (Best->Function == 0) {
6277    // Since there is no function declaration, this is one of the
6278    // surrogate candidates. Dig out the conversion function.
6279    CXXConversionDecl *Conv
6280      = cast<CXXConversionDecl>(
6281                         Best->Conversions[0].UserDefined.ConversionFunction);
6282
6283    CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
6284
6285    // We selected one of the surrogate functions that converts the
6286    // object parameter to a function pointer. Perform the conversion
6287    // on the object argument, then let ActOnCallExpr finish the job.
6288
6289    // Create an implicit member expr to refer to the conversion operator.
6290    // and then call it.
6291    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6292                                                   Conv);
6293
6294    return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
6295                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
6296                         CommaLocs, RParenLoc).release();
6297  }
6298
6299  CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
6300
6301  // We found an overloaded operator(). Build a CXXOperatorCallExpr
6302  // that calls this method, using Object for the implicit object
6303  // parameter and passing along the remaining arguments.
6304  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
6305  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
6306
6307  unsigned NumArgsInProto = Proto->getNumArgs();
6308  unsigned NumArgsToCheck = NumArgs;
6309
6310  // Build the full argument list for the method call (the
6311  // implicit object parameter is placed at the beginning of the
6312  // list).
6313  Expr **MethodArgs;
6314  if (NumArgs < NumArgsInProto) {
6315    NumArgsToCheck = NumArgsInProto;
6316    MethodArgs = new Expr*[NumArgsInProto + 1];
6317  } else {
6318    MethodArgs = new Expr*[NumArgs + 1];
6319  }
6320  MethodArgs[0] = Object;
6321  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6322    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
6323
6324  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
6325                                          SourceLocation());
6326  UsualUnaryConversions(NewFn);
6327
6328  // Once we've built TheCall, all of the expressions are properly
6329  // owned.
6330  QualType ResultTy = Method->getResultType().getNonReferenceType();
6331  ExprOwningPtr<CXXOperatorCallExpr>
6332    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
6333                                                    MethodArgs, NumArgs + 1,
6334                                                    ResultTy, RParenLoc));
6335  delete [] MethodArgs;
6336
6337  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6338                          Method))
6339    return true;
6340
6341  // We may have default arguments. If so, we need to allocate more
6342  // slots in the call for them.
6343  if (NumArgs < NumArgsInProto)
6344    TheCall->setNumArgs(Context, NumArgsInProto + 1);
6345  else if (NumArgs > NumArgsInProto)
6346    NumArgsToCheck = NumArgsInProto;
6347
6348  bool IsError = false;
6349
6350  // Initialize the implicit object parameter.
6351  IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
6352                                                 Best->FoundDecl, Method);
6353  TheCall->setArg(0, Object);
6354
6355
6356  // Check the argument types.
6357  for (unsigned i = 0; i != NumArgsToCheck; i++) {
6358    Expr *Arg;
6359    if (i < NumArgs) {
6360      Arg = Args[i];
6361
6362      // Pass the argument.
6363
6364      OwningExprResult InputInit
6365        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6366                                                    Method->getParamDecl(i)),
6367                                    SourceLocation(), Owned(Arg));
6368
6369      IsError |= InputInit.isInvalid();
6370      Arg = InputInit.takeAs<Expr>();
6371    } else {
6372      OwningExprResult DefArg
6373        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6374      if (DefArg.isInvalid()) {
6375        IsError = true;
6376        break;
6377      }
6378
6379      Arg = DefArg.takeAs<Expr>();
6380    }
6381
6382    TheCall->setArg(i + 1, Arg);
6383  }
6384
6385  // If this is a variadic call, handle args passed through "...".
6386  if (Proto->isVariadic()) {
6387    // Promote the arguments (C99 6.5.2.2p7).
6388    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6389      Expr *Arg = Args[i];
6390      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
6391      TheCall->setArg(i + 1, Arg);
6392    }
6393  }
6394
6395  if (IsError) return true;
6396
6397  if (CheckFunctionCall(Method, TheCall.get()))
6398    return true;
6399
6400  return MaybeBindToTemporary(TheCall.release()).release();
6401}
6402
6403/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
6404///  (if one exists), where @c Base is an expression of class type and
6405/// @c Member is the name of the member we're trying to find.
6406Sema::OwningExprResult
6407Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
6408  Expr *Base = static_cast<Expr *>(BaseIn.get());
6409  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
6410
6411  SourceLocation Loc = Base->getExprLoc();
6412
6413  // C++ [over.ref]p1:
6414  //
6415  //   [...] An expression x->m is interpreted as (x.operator->())->m
6416  //   for a class object x of type T if T::operator->() exists and if
6417  //   the operator is selected as the best match function by the
6418  //   overload resolution mechanism (13.3).
6419  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
6420  OverloadCandidateSet CandidateSet(Loc);
6421  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
6422
6423  if (RequireCompleteType(Loc, Base->getType(),
6424                          PDiag(diag::err_typecheck_incomplete_tag)
6425                            << Base->getSourceRange()))
6426    return ExprError();
6427
6428  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
6429  LookupQualifiedName(R, BaseRecord->getDecl());
6430  R.suppressDiagnostics();
6431
6432  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
6433       Oper != OperEnd; ++Oper) {
6434    AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
6435                       /*SuppressUserConversions=*/false);
6436  }
6437
6438  // Perform overload resolution.
6439  OverloadCandidateSet::iterator Best;
6440  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
6441  case OR_Success:
6442    // Overload resolution succeeded; we'll build the call below.
6443    break;
6444
6445  case OR_No_Viable_Function:
6446    if (CandidateSet.empty())
6447      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6448        << Base->getType() << Base->getSourceRange();
6449    else
6450      Diag(OpLoc, diag::err_ovl_no_viable_oper)
6451        << "operator->" << Base->getSourceRange();
6452    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
6453    return ExprError();
6454
6455  case OR_Ambiguous:
6456    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
6457      << "->" << Base->getSourceRange();
6458    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
6459    return ExprError();
6460
6461  case OR_Deleted:
6462    Diag(OpLoc,  diag::err_ovl_deleted_oper)
6463      << Best->Function->isDeleted()
6464      << "->" << Base->getSourceRange();
6465    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
6466    return ExprError();
6467  }
6468
6469  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
6470
6471  // Convert the object parameter.
6472  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
6473  if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
6474                                          Best->FoundDecl, Method))
6475    return ExprError();
6476
6477  // No concerns about early exits now.
6478  BaseIn.release();
6479
6480  // Build the operator call.
6481  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
6482                                           SourceLocation());
6483  UsualUnaryConversions(FnExpr);
6484
6485  QualType ResultTy = Method->getResultType().getNonReferenceType();
6486  ExprOwningPtr<CXXOperatorCallExpr>
6487    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
6488                                                    &Base, 1, ResultTy, OpLoc));
6489
6490  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
6491                          Method))
6492          return ExprError();
6493  return move(TheCall);
6494}
6495
6496/// FixOverloadedFunctionReference - E is an expression that refers to
6497/// a C++ overloaded function (possibly with some parentheses and
6498/// perhaps a '&' around it). We have resolved the overloaded function
6499/// to the function declaration Fn, so patch up the expression E to
6500/// refer (possibly indirectly) to Fn. Returns the new expr.
6501Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
6502                                           FunctionDecl *Fn) {
6503  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6504    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
6505                                                   Found, Fn);
6506    if (SubExpr == PE->getSubExpr())
6507      return PE->Retain();
6508
6509    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
6510  }
6511
6512  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
6513    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
6514                                                   Found, Fn);
6515    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
6516                               SubExpr->getType()) &&
6517           "Implicit cast type cannot be determined from overload");
6518    if (SubExpr == ICE->getSubExpr())
6519      return ICE->Retain();
6520
6521    return new (Context) ImplicitCastExpr(ICE->getType(),
6522                                          ICE->getCastKind(),
6523                                          SubExpr,
6524                                          ICE->isLvalueCast());
6525  }
6526
6527  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
6528    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
6529           "Can only take the address of an overloaded function");
6530    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
6531      if (Method->isStatic()) {
6532        // Do nothing: static member functions aren't any different
6533        // from non-member functions.
6534      } else {
6535        // Fix the sub expression, which really has to be an
6536        // UnresolvedLookupExpr holding an overloaded member function
6537        // or template.
6538        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6539                                                       Found, Fn);
6540        if (SubExpr == UnOp->getSubExpr())
6541          return UnOp->Retain();
6542
6543        assert(isa<DeclRefExpr>(SubExpr)
6544               && "fixed to something other than a decl ref");
6545        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
6546               && "fixed to a member ref with no nested name qualifier");
6547
6548        // We have taken the address of a pointer to member
6549        // function. Perform the computation here so that we get the
6550        // appropriate pointer to member type.
6551        QualType ClassType
6552          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
6553        QualType MemPtrType
6554          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
6555
6556        return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6557                                           MemPtrType, UnOp->getOperatorLoc());
6558      }
6559    }
6560    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
6561                                                   Found, Fn);
6562    if (SubExpr == UnOp->getSubExpr())
6563      return UnOp->Retain();
6564
6565    return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
6566                                     Context.getPointerType(SubExpr->getType()),
6567                                       UnOp->getOperatorLoc());
6568  }
6569
6570  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
6571    // FIXME: avoid copy.
6572    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6573    if (ULE->hasExplicitTemplateArgs()) {
6574      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
6575      TemplateArgs = &TemplateArgsBuffer;
6576    }
6577
6578    return DeclRefExpr::Create(Context,
6579                               ULE->getQualifier(),
6580                               ULE->getQualifierRange(),
6581                               Fn,
6582                               ULE->getNameLoc(),
6583                               Fn->getType(),
6584                               TemplateArgs);
6585  }
6586
6587  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
6588    // FIXME: avoid copy.
6589    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6590    if (MemExpr->hasExplicitTemplateArgs()) {
6591      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6592      TemplateArgs = &TemplateArgsBuffer;
6593    }
6594
6595    Expr *Base;
6596
6597    // If we're filling in
6598    if (MemExpr->isImplicitAccess()) {
6599      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
6600        return DeclRefExpr::Create(Context,
6601                                   MemExpr->getQualifier(),
6602                                   MemExpr->getQualifierRange(),
6603                                   Fn,
6604                                   MemExpr->getMemberLoc(),
6605                                   Fn->getType(),
6606                                   TemplateArgs);
6607      } else {
6608        SourceLocation Loc = MemExpr->getMemberLoc();
6609        if (MemExpr->getQualifier())
6610          Loc = MemExpr->getQualifierRange().getBegin();
6611        Base = new (Context) CXXThisExpr(Loc,
6612                                         MemExpr->getBaseType(),
6613                                         /*isImplicit=*/true);
6614      }
6615    } else
6616      Base = MemExpr->getBase()->Retain();
6617
6618    return MemberExpr::Create(Context, Base,
6619                              MemExpr->isArrow(),
6620                              MemExpr->getQualifier(),
6621                              MemExpr->getQualifierRange(),
6622                              Fn,
6623                              Found,
6624                              MemExpr->getMemberLoc(),
6625                              TemplateArgs,
6626                              Fn->getType());
6627  }
6628
6629  assert(false && "Invalid reference to overloaded function");
6630  return E->Retain();
6631}
6632
6633Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
6634                                                          DeclAccessPair Found,
6635                                                            FunctionDecl *Fn) {
6636  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
6637}
6638
6639} // end namespace clang
6640