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