SemaOverload.cpp revision 82ad87b872b4c75b5e47f5b3514cc7ab082150d6
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 "SemaInherit.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeOrdering.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "llvm/ADT/SmallPtrSet.h"
24#include "llvm/ADT/STLExtras.h"
25#include "llvm/Support/Compiler.h"
26#include <algorithm>
27#include <cstdio>
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_Qualification_Adjustment,
42    ICC_Promotion,
43    ICC_Promotion,
44    ICC_Promotion,
45    ICC_Conversion,
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  };
56  return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62  static const ImplicitConversionRank
63    Rank[(int)ICK_Num_Conversion_Kinds] = {
64    ICR_Exact_Match,
65    ICR_Exact_Match,
66    ICR_Exact_Match,
67    ICR_Exact_Match,
68    ICR_Exact_Match,
69    ICR_Promotion,
70    ICR_Promotion,
71    ICR_Promotion,
72    ICR_Conversion,
73    ICR_Conversion,
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  };
83  return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90    "No conversion",
91    "Lvalue-to-rvalue",
92    "Array-to-pointer",
93    "Function-to-pointer",
94    "Qualification",
95    "Integral promotion",
96    "Floating point promotion",
97    "Complex promotion",
98    "Integral conversion",
99    "Floating conversion",
100    "Complex conversion",
101    "Floating-integral conversion",
102    "Complex-real conversion",
103    "Pointer conversion",
104    "Pointer-to-member conversion",
105    "Boolean conversion",
106    "Compatible-types conversion",
107    "Derived-to-base conversion"
108  };
109  return Name[Kind];
110}
111
112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115  First = ICK_Identity;
116  Second = ICK_Identity;
117  Third = ICK_Identity;
118  Deprecated = false;
119  ReferenceBinding = false;
120  DirectBinding = false;
121  RRefBinding = false;
122  CopyConstructor = 0;
123}
124
125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129  ImplicitConversionRank Rank = ICR_Exact_Match;
130  if  (GetConversionRank(First) > Rank)
131    Rank = GetConversionRank(First);
132  if  (GetConversionRank(Second) > Rank)
133    Rank = GetConversionRank(Second);
134  if  (GetConversionRank(Third) > Rank)
135    Rank = GetConversionRank(Third);
136  return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
141/// used as part of the ranking of standard conversion sequences
142/// (C++ 13.3.3.2p4).
143bool StandardConversionSequence::isPointerConversionToBool() const {
144  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
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 (ToType->isBooleanType() &&
152      (FromType->isPointerType() || FromType->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 = QualType::getFromOpaquePtr(FromTypePtr);
167  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
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)
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  bool PrintedSomething = false;
186  if (First != ICK_Identity) {
187    fprintf(stderr, "%s", GetImplicitConversionName(First));
188    PrintedSomething = true;
189  }
190
191  if (Second != ICK_Identity) {
192    if (PrintedSomething) {
193      fprintf(stderr, " -> ");
194    }
195    fprintf(stderr, "%s", GetImplicitConversionName(Second));
196
197    if (CopyConstructor) {
198      fprintf(stderr, " (by copy constructor)");
199    } else if (DirectBinding) {
200      fprintf(stderr, " (direct reference binding)");
201    } else if (ReferenceBinding) {
202      fprintf(stderr, " (reference binding)");
203    }
204    PrintedSomething = true;
205  }
206
207  if (Third != ICK_Identity) {
208    if (PrintedSomething) {
209      fprintf(stderr, " -> ");
210    }
211    fprintf(stderr, "%s", GetImplicitConversionName(Third));
212    PrintedSomething = true;
213  }
214
215  if (!PrintedSomething) {
216    fprintf(stderr, "No conversions required");
217  }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223  if (Before.First || Before.Second || Before.Third) {
224    Before.DebugPrint();
225    fprintf(stderr, " -> ");
226  }
227  fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
228  if (After.First || After.Second || After.Third) {
229    fprintf(stderr, " -> ");
230    After.DebugPrint();
231  }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237  switch (ConversionKind) {
238  case StandardConversion:
239    fprintf(stderr, "Standard conversion: ");
240    Standard.DebugPrint();
241    break;
242  case UserDefinedConversion:
243    fprintf(stderr, "User-defined conversion: ");
244    UserDefined.DebugPrint();
245    break;
246  case EllipsisConversion:
247    fprintf(stderr, "Ellipsis conversion");
248    break;
249  case BadConversion:
250    fprintf(stderr, "Bad conversion");
251    break;
252  }
253
254  fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
263// FunctionDecl that New cannot be overloaded with.
264//
265// Example: Given the following input:
266//
267//   void f(int, float); // #1
268//   void f(int, int); // #2
269//   int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
272// so IsOverload will not be used.
273//
274// When we process #2, Old is a FunctionDecl for #1.  By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287                 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
288  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289    // Is this new function an overload of every function in the
290    // overload set?
291    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292                                           FuncEnd = Ovl->function_end();
293    for (; Func != FuncEnd; ++Func) {
294      if (!IsOverload(New, *Func, MatchedDecl)) {
295        MatchedDecl = Func;
296        return false;
297      }
298    }
299
300    // This function overloads every function in the overload set.
301    return true;
302  } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303    return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304  else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
305    FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
306    FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
308    // C++ [temp.fct]p2:
309    //   A function template can be overloaded with other function templates
310    //   and with normal (non-template) functions.
311    if ((OldTemplate == 0) != (NewTemplate == 0))
312      return true;
313
314    // Is the function New an overload of the function Old?
315    QualType OldQType = Context.getCanonicalType(Old->getType());
316    QualType NewQType = Context.getCanonicalType(New->getType());
317
318    // Compare the signatures (C++ 1.3.10) of the two functions to
319    // determine whether they are overloads. If we find any mismatch
320    // in the signature, they are overloads.
321
322    // If either of these functions is a K&R-style function (no
323    // prototype), then we consider them to have matching signatures.
324    if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325        isa<FunctionNoProtoType>(NewQType.getTypePtr()))
326      return false;
327
328    FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329    FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
330
331    // The signature of a function includes the types of its
332    // parameters (C++ 1.3.10), which includes the presence or absence
333    // of the ellipsis; see C++ DR 357).
334    if (OldQType != NewQType &&
335        (OldType->getNumArgs() != NewType->getNumArgs() ||
336         OldType->isVariadic() != NewType->isVariadic() ||
337         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338                     NewType->arg_type_begin())))
339      return true;
340
341    // C++ [temp.over.link]p4:
342    //   The signature of a function template consists of its function
343    //   signature, its return type and its template parameter list. The names
344    //   of the template parameters are significant only for establishing the
345    //   relationship between the template parameters and the rest of the
346    //   signature.
347    //
348    // We check the return type and template parameter lists for function
349    // templates first; the remaining checks follow.
350    if (NewTemplate &&
351        (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352                                         OldTemplate->getTemplateParameters(),
353                                         false, false, SourceLocation()) ||
354         OldType->getResultType() != NewType->getResultType()))
355      return true;
356
357    // If the function is a class member, its signature includes the
358    // cv-qualifiers (if any) on the function itself.
359    //
360    // As part of this, also check whether one of the member functions
361    // is static, in which case they are not overloads (C++
362    // 13.1p2). While not part of the definition of the signature,
363    // this check is important to determine whether these functions
364    // can be overloaded.
365    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
367    if (OldMethod && NewMethod &&
368        !OldMethod->isStatic() && !NewMethod->isStatic() &&
369        OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
370      return true;
371
372    // The signatures match; this is not an overload.
373    return false;
374  } else {
375    // (C++ 13p1):
376    //   Only function declarations can be overloaded; object and type
377    //   declarations cannot be overloaded.
378    return false;
379  }
380}
381
382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
386///
387///   void f(float f);
388///   void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
407ImplicitConversionSequence
408Sema::TryImplicitConversion(Expr* From, QualType ToType,
409                            bool SuppressUserConversions,
410                            bool AllowExplicit, bool ForceRValue,
411                            bool InOverloadResolution) {
412  ImplicitConversionSequence ICS;
413  OverloadCandidateSet Conversions;
414  OverloadingResult UserDefResult = OR_Success;
415  if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
416    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
417  else if (getLangOptions().CPlusPlus &&
418           (UserDefResult = IsUserDefinedConversion(From, ToType,
419                                   ICS.UserDefined,
420                                   Conversions,
421                                   !SuppressUserConversions, AllowExplicit,
422                                   ForceRValue)) == OR_Success) {
423    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
424    // C++ [over.ics.user]p4:
425    //   A conversion of an expression of class type to the same class
426    //   type is given Exact Match rank, and a conversion of an
427    //   expression of class type to a base class of that type is
428    //   given Conversion rank, in spite of the fact that a copy
429    //   constructor (i.e., a user-defined conversion function) is
430    //   called for those cases.
431    if (CXXConstructorDecl *Constructor
432          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
433      QualType FromCanon
434        = Context.getCanonicalType(From->getType().getUnqualifiedType());
435      QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
436      if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
437        // Turn this into a "standard" conversion sequence, so that it
438        // gets ranked with standard conversion sequences.
439        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
440        ICS.Standard.setAsIdentityConversion();
441        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
442        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
443        ICS.Standard.CopyConstructor = Constructor;
444        if (ToCanon != FromCanon)
445          ICS.Standard.Second = ICK_Derived_To_Base;
446      }
447    }
448
449    // C++ [over.best.ics]p4:
450    //   However, when considering the argument of a user-defined
451    //   conversion function that is a candidate by 13.3.1.3 when
452    //   invoked for the copying of the temporary in the second step
453    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
454    //   13.3.1.6 in all cases, only standard conversion sequences and
455    //   ellipsis conversion sequences are allowed.
456    if (SuppressUserConversions &&
457        ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
458      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
459  } else {
460    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
461    if (UserDefResult == OR_Ambiguous) {
462      for (OverloadCandidateSet::iterator Cand = Conversions.begin();
463           Cand != Conversions.end(); ++Cand)
464        ICS.ConversionFunctionSet.push_back(Cand->Function);
465    }
466  }
467
468  return ICS;
469}
470
471/// IsStandardConversion - Determines whether there is a standard
472/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
473/// expression From to the type ToType. Standard conversion sequences
474/// only consider non-class types; for conversions that involve class
475/// types, use TryImplicitConversion. If a conversion exists, SCS will
476/// contain the standard conversion sequence required to perform this
477/// conversion and this routine will return true. Otherwise, this
478/// routine will return false and the value of SCS is unspecified.
479bool
480Sema::IsStandardConversion(Expr* From, QualType ToType,
481                           bool InOverloadResolution,
482                           StandardConversionSequence &SCS) {
483  QualType FromType = From->getType();
484
485  // Standard conversions (C++ [conv])
486  SCS.setAsIdentityConversion();
487  SCS.Deprecated = false;
488  SCS.IncompatibleObjC = false;
489  SCS.FromTypePtr = FromType.getAsOpaquePtr();
490  SCS.CopyConstructor = 0;
491
492  // There are no standard conversions for class types in C++, so
493  // abort early. When overloading in C, however, we do permit
494  if (FromType->isRecordType() || ToType->isRecordType()) {
495    if (getLangOptions().CPlusPlus)
496      return false;
497
498    // When we're overloading in C, we allow, as standard conversions,
499  }
500
501  // The first conversion can be an lvalue-to-rvalue conversion,
502  // array-to-pointer conversion, or function-to-pointer conversion
503  // (C++ 4p1).
504
505  // Lvalue-to-rvalue conversion (C++ 4.1):
506  //   An lvalue (3.10) of a non-function, non-array type T can be
507  //   converted to an rvalue.
508  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
509  if (argIsLvalue == Expr::LV_Valid &&
510      !FromType->isFunctionType() && !FromType->isArrayType() &&
511      Context.getCanonicalType(FromType) != Context.OverloadTy) {
512    SCS.First = ICK_Lvalue_To_Rvalue;
513
514    // If T is a non-class type, the type of the rvalue is the
515    // cv-unqualified version of T. Otherwise, the type of the rvalue
516    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
517    // just strip the qualifiers because they don't matter.
518
519    // FIXME: Doesn't see through to qualifiers behind a typedef!
520    FromType = FromType.getUnqualifiedType();
521  } else if (FromType->isArrayType()) {
522    // Array-to-pointer conversion (C++ 4.2)
523    SCS.First = ICK_Array_To_Pointer;
524
525    // An lvalue or rvalue of type "array of N T" or "array of unknown
526    // bound of T" can be converted to an rvalue of type "pointer to
527    // T" (C++ 4.2p1).
528    FromType = Context.getArrayDecayedType(FromType);
529
530    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
531      // This conversion is deprecated. (C++ D.4).
532      SCS.Deprecated = true;
533
534      // For the purpose of ranking in overload resolution
535      // (13.3.3.1.1), this conversion is considered an
536      // array-to-pointer conversion followed by a qualification
537      // conversion (4.4). (C++ 4.2p2)
538      SCS.Second = ICK_Identity;
539      SCS.Third = ICK_Qualification;
540      SCS.ToTypePtr = ToType.getAsOpaquePtr();
541      return true;
542    }
543  } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
544    // Function-to-pointer conversion (C++ 4.3).
545    SCS.First = ICK_Function_To_Pointer;
546
547    // An lvalue of function type T can be converted to an rvalue of
548    // type "pointer to T." The result is a pointer to the
549    // function. (C++ 4.3p1).
550    FromType = Context.getPointerType(FromType);
551  } else if (FunctionDecl *Fn
552             = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
553    // Address of overloaded function (C++ [over.over]).
554    SCS.First = ICK_Function_To_Pointer;
555
556    // We were able to resolve the address of the overloaded function,
557    // so we can convert to the type of that function.
558    FromType = Fn->getType();
559    if (ToType->isLValueReferenceType())
560      FromType = Context.getLValueReferenceType(FromType);
561    else if (ToType->isRValueReferenceType())
562      FromType = Context.getRValueReferenceType(FromType);
563    else if (ToType->isMemberPointerType()) {
564      // Resolve address only succeeds if both sides are member pointers,
565      // but it doesn't have to be the same class. See DR 247.
566      // Note that this means that the type of &Derived::fn can be
567      // Ret (Base::*)(Args) if the fn overload actually found is from the
568      // base class, even if it was brought into the derived class via a
569      // using declaration. The standard isn't clear on this issue at all.
570      CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
571      FromType = Context.getMemberPointerType(FromType,
572                    Context.getTypeDeclType(M->getParent()).getTypePtr());
573    } else
574      FromType = Context.getPointerType(FromType);
575  } else {
576    // We don't require any conversions for the first step.
577    SCS.First = ICK_Identity;
578  }
579
580  // The second conversion can be an integral promotion, floating
581  // point promotion, integral conversion, floating point conversion,
582  // floating-integral conversion, pointer conversion,
583  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
584  // For overloading in C, this can also be a "compatible-type"
585  // conversion.
586  bool IncompatibleObjC = false;
587  if (Context.hasSameUnqualifiedType(FromType, ToType)) {
588    // The unqualified versions of the types are the same: there's no
589    // conversion to do.
590    SCS.Second = ICK_Identity;
591  } else if (IsIntegralPromotion(From, FromType, ToType)) {
592    // Integral promotion (C++ 4.5).
593    SCS.Second = ICK_Integral_Promotion;
594    FromType = ToType.getUnqualifiedType();
595  } else if (IsFloatingPointPromotion(FromType, ToType)) {
596    // Floating point promotion (C++ 4.6).
597    SCS.Second = ICK_Floating_Promotion;
598    FromType = ToType.getUnqualifiedType();
599  } else if (IsComplexPromotion(FromType, ToType)) {
600    // Complex promotion (Clang extension)
601    SCS.Second = ICK_Complex_Promotion;
602    FromType = ToType.getUnqualifiedType();
603  } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
604           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
605    // Integral conversions (C++ 4.7).
606    // FIXME: isIntegralType shouldn't be true for enums in C++.
607    SCS.Second = ICK_Integral_Conversion;
608    FromType = ToType.getUnqualifiedType();
609  } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
610    // Floating point conversions (C++ 4.8).
611    SCS.Second = ICK_Floating_Conversion;
612    FromType = ToType.getUnqualifiedType();
613  } else if (FromType->isComplexType() && ToType->isComplexType()) {
614    // Complex conversions (C99 6.3.1.6)
615    SCS.Second = ICK_Complex_Conversion;
616    FromType = ToType.getUnqualifiedType();
617  } else if ((FromType->isFloatingType() &&
618              ToType->isIntegralType() && (!ToType->isBooleanType() &&
619                                           !ToType->isEnumeralType())) ||
620             ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
621              ToType->isFloatingType())) {
622    // Floating-integral conversions (C++ 4.9).
623    // FIXME: isIntegralType shouldn't be true for enums in C++.
624    SCS.Second = ICK_Floating_Integral;
625    FromType = ToType.getUnqualifiedType();
626  } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
627             (ToType->isComplexType() && FromType->isArithmeticType())) {
628    // Complex-real conversions (C99 6.3.1.7)
629    SCS.Second = ICK_Complex_Real;
630    FromType = ToType.getUnqualifiedType();
631  } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
632                                 FromType, IncompatibleObjC)) {
633    // Pointer conversions (C++ 4.10).
634    SCS.Second = ICK_Pointer_Conversion;
635    SCS.IncompatibleObjC = IncompatibleObjC;
636  } else if (IsMemberPointerConversion(From, FromType, ToType,
637                                       InOverloadResolution, FromType)) {
638    // Pointer to member conversions (4.11).
639    SCS.Second = ICK_Pointer_Member;
640  } else if (ToType->isBooleanType() &&
641             (FromType->isArithmeticType() ||
642              FromType->isEnumeralType() ||
643              FromType->isPointerType() ||
644              FromType->isBlockPointerType() ||
645              FromType->isMemberPointerType() ||
646              FromType->isNullPtrType())) {
647    // Boolean conversions (C++ 4.12).
648    SCS.Second = ICK_Boolean_Conversion;
649    FromType = Context.BoolTy;
650  } else if (!getLangOptions().CPlusPlus &&
651             Context.typesAreCompatible(ToType, FromType)) {
652    // Compatible conversions (Clang extension for C function overloading)
653    SCS.Second = ICK_Compatible_Conversion;
654  } else {
655    // No second conversion required.
656    SCS.Second = ICK_Identity;
657  }
658
659  QualType CanonFrom;
660  QualType CanonTo;
661  // The third conversion can be a qualification conversion (C++ 4p1).
662  if (IsQualificationConversion(FromType, ToType)) {
663    SCS.Third = ICK_Qualification;
664    FromType = ToType;
665    CanonFrom = Context.getCanonicalType(FromType);
666    CanonTo = Context.getCanonicalType(ToType);
667  } else {
668    // No conversion required
669    SCS.Third = ICK_Identity;
670
671    // C++ [over.best.ics]p6:
672    //   [...] Any difference in top-level cv-qualification is
673    //   subsumed by the initialization itself and does not constitute
674    //   a conversion. [...]
675    CanonFrom = Context.getCanonicalType(FromType);
676    CanonTo = Context.getCanonicalType(ToType);
677    if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
678        CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
679      FromType = ToType;
680      CanonFrom = CanonTo;
681    }
682  }
683
684  // If we have not converted the argument type to the parameter type,
685  // this is a bad conversion sequence.
686  if (CanonFrom != CanonTo)
687    return false;
688
689  SCS.ToTypePtr = FromType.getAsOpaquePtr();
690  return true;
691}
692
693/// IsIntegralPromotion - Determines whether the conversion from the
694/// expression From (whose potentially-adjusted type is FromType) to
695/// ToType is an integral promotion (C++ 4.5). If so, returns true and
696/// sets PromotedType to the promoted type.
697bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
698  const BuiltinType *To = ToType->getAs<BuiltinType>();
699  // All integers are built-in.
700  if (!To) {
701    return false;
702  }
703
704  // An rvalue of type char, signed char, unsigned char, short int, or
705  // unsigned short int can be converted to an rvalue of type int if
706  // int can represent all the values of the source type; otherwise,
707  // the source rvalue can be converted to an rvalue of type unsigned
708  // int (C++ 4.5p1).
709  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
710    if (// We can promote any signed, promotable integer type to an int
711        (FromType->isSignedIntegerType() ||
712         // We can promote any unsigned integer type whose size is
713         // less than int to an int.
714         (!FromType->isSignedIntegerType() &&
715          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
716      return To->getKind() == BuiltinType::Int;
717    }
718
719    return To->getKind() == BuiltinType::UInt;
720  }
721
722  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
723  // can be converted to an rvalue of the first of the following types
724  // that can represent all the values of its underlying type: int,
725  // unsigned int, long, or unsigned long (C++ 4.5p2).
726  if ((FromType->isEnumeralType() || FromType->isWideCharType())
727      && ToType->isIntegerType()) {
728    // Determine whether the type we're converting from is signed or
729    // unsigned.
730    bool FromIsSigned;
731    uint64_t FromSize = Context.getTypeSize(FromType);
732    if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
733      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
734      FromIsSigned = UnderlyingType->isSignedIntegerType();
735    } else {
736      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
737      FromIsSigned = true;
738    }
739
740    // The types we'll try to promote to, in the appropriate
741    // order. Try each of these types.
742    QualType PromoteTypes[6] = {
743      Context.IntTy, Context.UnsignedIntTy,
744      Context.LongTy, Context.UnsignedLongTy ,
745      Context.LongLongTy, Context.UnsignedLongLongTy
746    };
747    for (int Idx = 0; Idx < 6; ++Idx) {
748      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
749      if (FromSize < ToSize ||
750          (FromSize == ToSize &&
751           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
752        // We found the type that we can promote to. If this is the
753        // type we wanted, we have a promotion. Otherwise, no
754        // promotion.
755        return Context.getCanonicalType(ToType).getUnqualifiedType()
756          == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
757      }
758    }
759  }
760
761  // An rvalue for an integral bit-field (9.6) can be converted to an
762  // rvalue of type int if int can represent all the values of the
763  // bit-field; otherwise, it can be converted to unsigned int if
764  // unsigned int can represent all the values of the bit-field. If
765  // the bit-field is larger yet, no integral promotion applies to
766  // it. If the bit-field has an enumerated type, it is treated as any
767  // other value of that type for promotion purposes (C++ 4.5p3).
768  // FIXME: We should delay checking of bit-fields until we actually perform the
769  // conversion.
770  using llvm::APSInt;
771  if (From)
772    if (FieldDecl *MemberDecl = From->getBitField()) {
773      APSInt BitWidth;
774      if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
775          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
776        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
777        ToSize = Context.getTypeSize(ToType);
778
779        // Are we promoting to an int from a bitfield that fits in an int?
780        if (BitWidth < ToSize ||
781            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
782          return To->getKind() == BuiltinType::Int;
783        }
784
785        // Are we promoting to an unsigned int from an unsigned bitfield
786        // that fits into an unsigned int?
787        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
788          return To->getKind() == BuiltinType::UInt;
789        }
790
791        return false;
792      }
793    }
794
795  // An rvalue of type bool can be converted to an rvalue of type int,
796  // with false becoming zero and true becoming one (C++ 4.5p4).
797  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
798    return true;
799  }
800
801  return false;
802}
803
804/// IsFloatingPointPromotion - Determines whether the conversion from
805/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
806/// returns true and sets PromotedType to the promoted type.
807bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
808  /// An rvalue of type float can be converted to an rvalue of type
809  /// double. (C++ 4.6p1).
810  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
811    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
812      if (FromBuiltin->getKind() == BuiltinType::Float &&
813          ToBuiltin->getKind() == BuiltinType::Double)
814        return true;
815
816      // C99 6.3.1.5p1:
817      //   When a float is promoted to double or long double, or a
818      //   double is promoted to long double [...].
819      if (!getLangOptions().CPlusPlus &&
820          (FromBuiltin->getKind() == BuiltinType::Float ||
821           FromBuiltin->getKind() == BuiltinType::Double) &&
822          (ToBuiltin->getKind() == BuiltinType::LongDouble))
823        return true;
824    }
825
826  return false;
827}
828
829/// \brief Determine if a conversion is a complex promotion.
830///
831/// A complex promotion is defined as a complex -> complex conversion
832/// where the conversion between the underlying real types is a
833/// floating-point or integral promotion.
834bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
835  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
836  if (!FromComplex)
837    return false;
838
839  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
840  if (!ToComplex)
841    return false;
842
843  return IsFloatingPointPromotion(FromComplex->getElementType(),
844                                  ToComplex->getElementType()) ||
845    IsIntegralPromotion(0, FromComplex->getElementType(),
846                        ToComplex->getElementType());
847}
848
849/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
850/// the pointer type FromPtr to a pointer to type ToPointee, with the
851/// same type qualifiers as FromPtr has on its pointee type. ToType,
852/// if non-empty, will be a pointer to ToType that may or may not have
853/// the right set of qualifiers on its pointee.
854static QualType
855BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
856                                   QualType ToPointee, QualType ToType,
857                                   ASTContext &Context) {
858  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
859  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
860  Qualifiers Quals = CanonFromPointee.getQualifiers();
861
862  // Exact qualifier match -> return the pointer type we're converting to.
863  if (CanonToPointee.getQualifiers() == Quals) {
864    // ToType is exactly what we need. Return it.
865    if (!ToType.isNull())
866      return ToType;
867
868    // Build a pointer to ToPointee. It has the right qualifiers
869    // already.
870    return Context.getPointerType(ToPointee);
871  }
872
873  // Just build a canonical type that has the right qualifiers.
874  return Context.getPointerType(
875         Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
876}
877
878static bool isNullPointerConstantForConversion(Expr *Expr,
879                                               bool InOverloadResolution,
880                                               ASTContext &Context) {
881  // Handle value-dependent integral null pointer constants correctly.
882  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
883  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
884      Expr->getType()->isIntegralType())
885    return !InOverloadResolution;
886
887  return Expr->isNullPointerConstant(Context,
888                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
889                                        : Expr::NPC_ValueDependentIsNull);
890}
891
892/// IsPointerConversion - Determines whether the conversion of the
893/// expression From, which has the (possibly adjusted) type FromType,
894/// can be converted to the type ToType via a pointer conversion (C++
895/// 4.10). If so, returns true and places the converted type (that
896/// might differ from ToType in its cv-qualifiers at some level) into
897/// ConvertedType.
898///
899/// This routine also supports conversions to and from block pointers
900/// and conversions with Objective-C's 'id', 'id<protocols...>', and
901/// pointers to interfaces. FIXME: Once we've determined the
902/// appropriate overloading rules for Objective-C, we may want to
903/// split the Objective-C checks into a different routine; however,
904/// GCC seems to consider all of these conversions to be pointer
905/// conversions, so for now they live here. IncompatibleObjC will be
906/// set if the conversion is an allowed Objective-C conversion that
907/// should result in a warning.
908bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
909                               bool InOverloadResolution,
910                               QualType& ConvertedType,
911                               bool &IncompatibleObjC) {
912  IncompatibleObjC = false;
913  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
914    return true;
915
916  // Conversion from a null pointer constant to any Objective-C pointer type.
917  if (ToType->isObjCObjectPointerType() &&
918      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
919    ConvertedType = ToType;
920    return true;
921  }
922
923  // Blocks: Block pointers can be converted to void*.
924  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
925      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
926    ConvertedType = ToType;
927    return true;
928  }
929  // Blocks: A null pointer constant can be converted to a block
930  // pointer type.
931  if (ToType->isBlockPointerType() &&
932      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
933    ConvertedType = ToType;
934    return true;
935  }
936
937  // If the left-hand-side is nullptr_t, the right side can be a null
938  // pointer constant.
939  if (ToType->isNullPtrType() &&
940      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
941    ConvertedType = ToType;
942    return true;
943  }
944
945  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
946  if (!ToTypePtr)
947    return false;
948
949  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
950  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
951    ConvertedType = ToType;
952    return true;
953  }
954
955  // Beyond this point, both types need to be pointers.
956  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
957  if (!FromTypePtr)
958    return false;
959
960  QualType FromPointeeType = FromTypePtr->getPointeeType();
961  QualType ToPointeeType = ToTypePtr->getPointeeType();
962
963  // An rvalue of type "pointer to cv T," where T is an object type,
964  // can be converted to an rvalue of type "pointer to cv void" (C++
965  // 4.10p2).
966  if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
967    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
968                                                       ToPointeeType,
969                                                       ToType, Context);
970    return true;
971  }
972
973  // When we're overloading in C, we allow a special kind of pointer
974  // conversion for compatible-but-not-identical pointee types.
975  if (!getLangOptions().CPlusPlus &&
976      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
977    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
978                                                       ToPointeeType,
979                                                       ToType, Context);
980    return true;
981  }
982
983  // C++ [conv.ptr]p3:
984  //
985  //   An rvalue of type "pointer to cv D," where D is a class type,
986  //   can be converted to an rvalue of type "pointer to cv B," where
987  //   B is a base class (clause 10) of D. If B is an inaccessible
988  //   (clause 11) or ambiguous (10.2) base class of D, a program that
989  //   necessitates this conversion is ill-formed. The result of the
990  //   conversion is a pointer to the base class sub-object of the
991  //   derived class object. The null pointer value is converted to
992  //   the null pointer value of the destination type.
993  //
994  // Note that we do not check for ambiguity or inaccessibility
995  // here. That is handled by CheckPointerConversion.
996  if (getLangOptions().CPlusPlus &&
997      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
998      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
999    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1000                                                       ToPointeeType,
1001                                                       ToType, Context);
1002    return true;
1003  }
1004
1005  return false;
1006}
1007
1008/// isObjCPointerConversion - Determines whether this is an
1009/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1010/// with the same arguments and return values.
1011bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1012                                   QualType& ConvertedType,
1013                                   bool &IncompatibleObjC) {
1014  if (!getLangOptions().ObjC1)
1015    return false;
1016
1017  // First, we handle all conversions on ObjC object pointer types.
1018  const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
1019  const ObjCObjectPointerType *FromObjCPtr =
1020    FromType->getAs<ObjCObjectPointerType>();
1021
1022  if (ToObjCPtr && FromObjCPtr) {
1023    // Objective C++: We're able to convert between "id" or "Class" and a
1024    // pointer to any interface (in both directions).
1025    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1026      ConvertedType = ToType;
1027      return true;
1028    }
1029    // Conversions with Objective-C's id<...>.
1030    if ((FromObjCPtr->isObjCQualifiedIdType() ||
1031         ToObjCPtr->isObjCQualifiedIdType()) &&
1032        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1033                                                  /*compare=*/false)) {
1034      ConvertedType = ToType;
1035      return true;
1036    }
1037    // Objective C++: We're able to convert from a pointer to an
1038    // interface to a pointer to a different interface.
1039    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1040      ConvertedType = ToType;
1041      return true;
1042    }
1043
1044    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1045      // Okay: this is some kind of implicit downcast of Objective-C
1046      // interfaces, which is permitted. However, we're going to
1047      // complain about it.
1048      IncompatibleObjC = true;
1049      ConvertedType = FromType;
1050      return true;
1051    }
1052  }
1053  // Beyond this point, both types need to be C pointers or block pointers.
1054  QualType ToPointeeType;
1055  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1056    ToPointeeType = ToCPtr->getPointeeType();
1057  else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
1058    ToPointeeType = ToBlockPtr->getPointeeType();
1059  else
1060    return false;
1061
1062  QualType FromPointeeType;
1063  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1064    FromPointeeType = FromCPtr->getPointeeType();
1065  else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
1066    FromPointeeType = FromBlockPtr->getPointeeType();
1067  else
1068    return false;
1069
1070  // If we have pointers to pointers, recursively check whether this
1071  // is an Objective-C conversion.
1072  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1073      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1074                              IncompatibleObjC)) {
1075    // We always complain about this conversion.
1076    IncompatibleObjC = true;
1077    ConvertedType = ToType;
1078    return true;
1079  }
1080  // If we have pointers to functions or blocks, check whether the only
1081  // differences in the argument and result types are in Objective-C
1082  // pointer conversions. If so, we permit the conversion (but
1083  // complain about it).
1084  const FunctionProtoType *FromFunctionType
1085    = FromPointeeType->getAs<FunctionProtoType>();
1086  const FunctionProtoType *ToFunctionType
1087    = ToPointeeType->getAs<FunctionProtoType>();
1088  if (FromFunctionType && ToFunctionType) {
1089    // If the function types are exactly the same, this isn't an
1090    // Objective-C pointer conversion.
1091    if (Context.getCanonicalType(FromPointeeType)
1092          == Context.getCanonicalType(ToPointeeType))
1093      return false;
1094
1095    // Perform the quick checks that will tell us whether these
1096    // function types are obviously different.
1097    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1098        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1099        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1100      return false;
1101
1102    bool HasObjCConversion = false;
1103    if (Context.getCanonicalType(FromFunctionType->getResultType())
1104          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1105      // Okay, the types match exactly. Nothing to do.
1106    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1107                                       ToFunctionType->getResultType(),
1108                                       ConvertedType, IncompatibleObjC)) {
1109      // Okay, we have an Objective-C pointer conversion.
1110      HasObjCConversion = true;
1111    } else {
1112      // Function types are too different. Abort.
1113      return false;
1114    }
1115
1116    // Check argument types.
1117    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1118         ArgIdx != NumArgs; ++ArgIdx) {
1119      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1120      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1121      if (Context.getCanonicalType(FromArgType)
1122            == Context.getCanonicalType(ToArgType)) {
1123        // Okay, the types match exactly. Nothing to do.
1124      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1125                                         ConvertedType, IncompatibleObjC)) {
1126        // Okay, we have an Objective-C pointer conversion.
1127        HasObjCConversion = true;
1128      } else {
1129        // Argument types are too different. Abort.
1130        return false;
1131      }
1132    }
1133
1134    if (HasObjCConversion) {
1135      // We had an Objective-C conversion. Allow this pointer
1136      // conversion, but complain about it.
1137      ConvertedType = ToType;
1138      IncompatibleObjC = true;
1139      return true;
1140    }
1141  }
1142
1143  return false;
1144}
1145
1146/// CheckPointerConversion - Check the pointer conversion from the
1147/// expression From to the type ToType. This routine checks for
1148/// ambiguous or inaccessible derived-to-base pointer
1149/// conversions for which IsPointerConversion has already returned
1150/// true. It returns true and produces a diagnostic if there was an
1151/// error, or returns false otherwise.
1152bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1153                                  CastExpr::CastKind &Kind) {
1154  QualType FromType = From->getType();
1155
1156  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1157    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1158      QualType FromPointeeType = FromPtrType->getPointeeType(),
1159               ToPointeeType   = ToPtrType->getPointeeType();
1160
1161      if (FromPointeeType->isRecordType() &&
1162          ToPointeeType->isRecordType()) {
1163        // We must have a derived-to-base conversion. Check an
1164        // ambiguous or inaccessible conversion.
1165        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1166                                         From->getExprLoc(),
1167                                         From->getSourceRange()))
1168          return true;
1169
1170        // The conversion was successful.
1171        Kind = CastExpr::CK_DerivedToBase;
1172      }
1173    }
1174  if (const ObjCObjectPointerType *FromPtrType =
1175        FromType->getAs<ObjCObjectPointerType>())
1176    if (const ObjCObjectPointerType *ToPtrType =
1177          ToType->getAs<ObjCObjectPointerType>()) {
1178      // Objective-C++ conversions are always okay.
1179      // FIXME: We should have a different class of conversions for the
1180      // Objective-C++ implicit conversions.
1181      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1182        return false;
1183
1184  }
1185  return false;
1186}
1187
1188/// IsMemberPointerConversion - Determines whether the conversion of the
1189/// expression From, which has the (possibly adjusted) type FromType, can be
1190/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1191/// If so, returns true and places the converted type (that might differ from
1192/// ToType in its cv-qualifiers at some level) into ConvertedType.
1193bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1194                                     QualType ToType,
1195                                     bool InOverloadResolution,
1196                                     QualType &ConvertedType) {
1197  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1198  if (!ToTypePtr)
1199    return false;
1200
1201  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1202  if (From->isNullPointerConstant(Context,
1203                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1204                                        : Expr::NPC_ValueDependentIsNull)) {
1205    ConvertedType = ToType;
1206    return true;
1207  }
1208
1209  // Otherwise, both types have to be member pointers.
1210  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1211  if (!FromTypePtr)
1212    return false;
1213
1214  // A pointer to member of B can be converted to a pointer to member of D,
1215  // where D is derived from B (C++ 4.11p2).
1216  QualType FromClass(FromTypePtr->getClass(), 0);
1217  QualType ToClass(ToTypePtr->getClass(), 0);
1218  // FIXME: What happens when these are dependent? Is this function even called?
1219
1220  if (IsDerivedFrom(ToClass, FromClass)) {
1221    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1222                                                 ToClass.getTypePtr());
1223    return true;
1224  }
1225
1226  return false;
1227}
1228
1229/// CheckMemberPointerConversion - Check the member pointer conversion from the
1230/// expression From to the type ToType. This routine checks for ambiguous or
1231/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1232/// for which IsMemberPointerConversion has already returned true. It returns
1233/// true and produces a diagnostic if there was an error, or returns false
1234/// otherwise.
1235bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1236                                        CastExpr::CastKind &Kind) {
1237  QualType FromType = From->getType();
1238  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1239  if (!FromPtrType) {
1240    // This must be a null pointer to member pointer conversion
1241    assert(From->isNullPointerConstant(Context,
1242                                       Expr::NPC_ValueDependentIsNull) &&
1243           "Expr must be null pointer constant!");
1244    Kind = CastExpr::CK_NullToMemberPointer;
1245    return false;
1246  }
1247
1248  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1249  assert(ToPtrType && "No member pointer cast has a target type "
1250                      "that is not a member pointer.");
1251
1252  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1253  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1254
1255  // FIXME: What about dependent types?
1256  assert(FromClass->isRecordType() && "Pointer into non-class.");
1257  assert(ToClass->isRecordType() && "Pointer into non-class.");
1258
1259  BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1260                  /*DetectVirtual=*/true);
1261  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1262  assert(DerivationOkay &&
1263         "Should not have been called if derivation isn't OK.");
1264  (void)DerivationOkay;
1265
1266  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1267                                  getUnqualifiedType())) {
1268    // Derivation is ambiguous. Redo the check to find the exact paths.
1269    Paths.clear();
1270    Paths.setRecordingPaths(true);
1271    bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1272    assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1273    (void)StillOkay;
1274
1275    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1276    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1277      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1278    return true;
1279  }
1280
1281  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1282    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1283      << FromClass << ToClass << QualType(VBase, 0)
1284      << From->getSourceRange();
1285    return true;
1286  }
1287
1288  // Must be a base to derived member conversion.
1289  Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1290  return false;
1291}
1292
1293/// IsQualificationConversion - Determines whether the conversion from
1294/// an rvalue of type FromType to ToType is a qualification conversion
1295/// (C++ 4.4).
1296bool
1297Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
1298  FromType = Context.getCanonicalType(FromType);
1299  ToType = Context.getCanonicalType(ToType);
1300
1301  // If FromType and ToType are the same type, this is not a
1302  // qualification conversion.
1303  if (FromType == ToType)
1304    return false;
1305
1306  // (C++ 4.4p4):
1307  //   A conversion can add cv-qualifiers at levels other than the first
1308  //   in multi-level pointers, subject to the following rules: [...]
1309  bool PreviousToQualsIncludeConst = true;
1310  bool UnwrappedAnyPointer = false;
1311  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1312    // Within each iteration of the loop, we check the qualifiers to
1313    // determine if this still looks like a qualification
1314    // conversion. Then, if all is well, we unwrap one more level of
1315    // pointers or pointers-to-members and do it all again
1316    // until there are no more pointers or pointers-to-members left to
1317    // unwrap.
1318    UnwrappedAnyPointer = true;
1319
1320    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1321    //      2,j, and similarly for volatile.
1322    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1323      return false;
1324
1325    //   -- if the cv 1,j and cv 2,j are different, then const is in
1326    //      every cv for 0 < k < j.
1327    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1328        && !PreviousToQualsIncludeConst)
1329      return false;
1330
1331    // Keep track of whether all prior cv-qualifiers in the "to" type
1332    // include const.
1333    PreviousToQualsIncludeConst
1334      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1335  }
1336
1337  // We are left with FromType and ToType being the pointee types
1338  // after unwrapping the original FromType and ToType the same number
1339  // of types. If we unwrapped any pointers, and if FromType and
1340  // ToType have the same unqualified type (since we checked
1341  // qualifiers above), then this is a qualification conversion.
1342  return UnwrappedAnyPointer &&
1343    FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1344}
1345
1346/// \brief Given a function template or function, extract the function template
1347/// declaration (if any) and the underlying function declaration.
1348template<typename T>
1349static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1350                                   FunctionTemplateDecl *&FunctionTemplate) {
1351  FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1352  if (FunctionTemplate)
1353    Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1354  else
1355    Function = cast<T>(Orig);
1356}
1357
1358/// Determines whether there is a user-defined conversion sequence
1359/// (C++ [over.ics.user]) that converts expression From to the type
1360/// ToType. If such a conversion exists, User will contain the
1361/// user-defined conversion sequence that performs such a conversion
1362/// and this routine will return true. Otherwise, this routine returns
1363/// false and User is unspecified.
1364///
1365/// \param AllowConversionFunctions true if the conversion should
1366/// consider conversion functions at all. If false, only constructors
1367/// will be considered.
1368///
1369/// \param AllowExplicit  true if the conversion should consider C++0x
1370/// "explicit" conversion functions as well as non-explicit conversion
1371/// functions (C++0x [class.conv.fct]p2).
1372///
1373/// \param ForceRValue  true if the expression should be treated as an rvalue
1374/// for overload resolution.
1375Sema::OverloadingResult Sema::IsUserDefinedConversion(
1376                                   Expr *From, QualType ToType,
1377                                   UserDefinedConversionSequence& User,
1378                                   OverloadCandidateSet& CandidateSet,
1379                                   bool AllowConversionFunctions,
1380                                   bool AllowExplicit, bool ForceRValue) {
1381  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1382    if (CXXRecordDecl *ToRecordDecl
1383          = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1384      // C++ [over.match.ctor]p1:
1385      //   When objects of class type are direct-initialized (8.5), or
1386      //   copy-initialized from an expression of the same or a
1387      //   derived class type (8.5), overload resolution selects the
1388      //   constructor. [...] For copy-initialization, the candidate
1389      //   functions are all the converting constructors (12.3.1) of
1390      //   that class. The argument list is the expression-list within
1391      //   the parentheses of the initializer.
1392      DeclarationName ConstructorName
1393        = Context.DeclarationNames.getCXXConstructorName(
1394                          Context.getCanonicalType(ToType).getUnqualifiedType());
1395      DeclContext::lookup_iterator Con, ConEnd;
1396      for (llvm::tie(Con, ConEnd)
1397             = ToRecordDecl->lookup(ConstructorName);
1398           Con != ConEnd; ++Con) {
1399        // Find the constructor (which may be a template).
1400        CXXConstructorDecl *Constructor = 0;
1401        FunctionTemplateDecl *ConstructorTmpl
1402          = dyn_cast<FunctionTemplateDecl>(*Con);
1403        if (ConstructorTmpl)
1404          Constructor
1405            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1406        else
1407          Constructor = cast<CXXConstructorDecl>(*Con);
1408
1409        if (!Constructor->isInvalidDecl() &&
1410            Constructor->isConvertingConstructor(AllowExplicit)) {
1411          if (ConstructorTmpl)
1412            AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
1413                                         1, CandidateSet,
1414                                         /*SuppressUserConversions=*/true,
1415                                         ForceRValue);
1416          else
1417            AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1418                                 /*SuppressUserConversions=*/true, ForceRValue);
1419        }
1420      }
1421    }
1422  }
1423
1424  if (!AllowConversionFunctions) {
1425    // Don't allow any conversion functions to enter the overload set.
1426  } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1427                                 PDiag(0)
1428                                   << From->getSourceRange())) {
1429    // No conversion functions from incomplete types.
1430  } else if (const RecordType *FromRecordType
1431               = From->getType()->getAs<RecordType>()) {
1432    if (CXXRecordDecl *FromRecordDecl
1433         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1434      // Add all of the conversion functions as candidates.
1435      OverloadedFunctionDecl *Conversions
1436        = FromRecordDecl->getVisibleConversionFunctions();
1437      for (OverloadedFunctionDecl::function_iterator Func
1438             = Conversions->function_begin();
1439           Func != Conversions->function_end(); ++Func) {
1440        CXXConversionDecl *Conv;
1441        FunctionTemplateDecl *ConvTemplate;
1442        GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1443        if (ConvTemplate)
1444          Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1445        else
1446          Conv = dyn_cast<CXXConversionDecl>(*Func);
1447
1448        if (AllowExplicit || !Conv->isExplicit()) {
1449          if (ConvTemplate)
1450            AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1451                                           CandidateSet);
1452          else
1453            AddConversionCandidate(Conv, From, ToType, CandidateSet);
1454        }
1455      }
1456    }
1457  }
1458
1459  OverloadCandidateSet::iterator Best;
1460  switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1461    case OR_Success:
1462      // Record the standard conversion we used and the conversion function.
1463      if (CXXConstructorDecl *Constructor
1464            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1465        // C++ [over.ics.user]p1:
1466        //   If the user-defined conversion is specified by a
1467        //   constructor (12.3.1), the initial standard conversion
1468        //   sequence converts the source type to the type required by
1469        //   the argument of the constructor.
1470        //
1471        // FIXME: What about ellipsis conversions?
1472        QualType ThisType = Constructor->getThisType(Context);
1473        User.Before = Best->Conversions[0].Standard;
1474        User.ConversionFunction = Constructor;
1475        User.After.setAsIdentityConversion();
1476        User.After.FromTypePtr
1477          = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
1478        User.After.ToTypePtr = ToType.getAsOpaquePtr();
1479        return OR_Success;
1480      } else if (CXXConversionDecl *Conversion
1481                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1482        // C++ [over.ics.user]p1:
1483        //
1484        //   [...] If the user-defined conversion is specified by a
1485        //   conversion function (12.3.2), the initial standard
1486        //   conversion sequence converts the source type to the
1487        //   implicit object parameter of the conversion function.
1488        User.Before = Best->Conversions[0].Standard;
1489        User.ConversionFunction = Conversion;
1490
1491        // C++ [over.ics.user]p2:
1492        //   The second standard conversion sequence converts the
1493        //   result of the user-defined conversion to the target type
1494        //   for the sequence. Since an implicit conversion sequence
1495        //   is an initialization, the special rules for
1496        //   initialization by user-defined conversion apply when
1497        //   selecting the best user-defined conversion for a
1498        //   user-defined conversion sequence (see 13.3.3 and
1499        //   13.3.3.1).
1500        User.After = Best->FinalConversion;
1501        return OR_Success;
1502      } else {
1503        assert(false && "Not a constructor or conversion function?");
1504        return OR_No_Viable_Function;
1505      }
1506
1507    case OR_No_Viable_Function:
1508      return OR_No_Viable_Function;
1509    case OR_Deleted:
1510      // No conversion here! We're done.
1511      return OR_Deleted;
1512
1513    case OR_Ambiguous:
1514      return OR_Ambiguous;
1515    }
1516
1517  return OR_No_Viable_Function;
1518}
1519
1520bool
1521Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1522  ImplicitConversionSequence ICS;
1523  OverloadCandidateSet CandidateSet;
1524  OverloadingResult OvResult =
1525    IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1526                            CandidateSet, true, false, false);
1527  if (OvResult != OR_Ambiguous)
1528    return false;
1529  Diag(From->getSourceRange().getBegin(),
1530       diag::err_typecheck_ambiguous_condition)
1531  << From->getType() << ToType << From->getSourceRange();
1532    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1533  return true;
1534}
1535
1536/// CompareImplicitConversionSequences - Compare two implicit
1537/// conversion sequences to determine whether one is better than the
1538/// other or if they are indistinguishable (C++ 13.3.3.2).
1539ImplicitConversionSequence::CompareKind
1540Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1541                                         const ImplicitConversionSequence& ICS2)
1542{
1543  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1544  // conversion sequences (as defined in 13.3.3.1)
1545  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1546  //      conversion sequence than a user-defined conversion sequence or
1547  //      an ellipsis conversion sequence, and
1548  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1549  //      conversion sequence than an ellipsis conversion sequence
1550  //      (13.3.3.1.3).
1551  //
1552  if (ICS1.ConversionKind < ICS2.ConversionKind)
1553    return ImplicitConversionSequence::Better;
1554  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1555    return ImplicitConversionSequence::Worse;
1556
1557  // Two implicit conversion sequences of the same form are
1558  // indistinguishable conversion sequences unless one of the
1559  // following rules apply: (C++ 13.3.3.2p3):
1560  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1561    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1562  else if (ICS1.ConversionKind ==
1563             ImplicitConversionSequence::UserDefinedConversion) {
1564    // User-defined conversion sequence U1 is a better conversion
1565    // sequence than another user-defined conversion sequence U2 if
1566    // they contain the same user-defined conversion function or
1567    // constructor and if the second standard conversion sequence of
1568    // U1 is better than the second standard conversion sequence of
1569    // U2 (C++ 13.3.3.2p3).
1570    if (ICS1.UserDefined.ConversionFunction ==
1571          ICS2.UserDefined.ConversionFunction)
1572      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1573                                                ICS2.UserDefined.After);
1574  }
1575
1576  return ImplicitConversionSequence::Indistinguishable;
1577}
1578
1579/// CompareStandardConversionSequences - Compare two standard
1580/// conversion sequences to determine whether one is better than the
1581/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1582ImplicitConversionSequence::CompareKind
1583Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1584                                         const StandardConversionSequence& SCS2)
1585{
1586  // Standard conversion sequence S1 is a better conversion sequence
1587  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1588
1589  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1590  //     sequences in the canonical form defined by 13.3.3.1.1,
1591  //     excluding any Lvalue Transformation; the identity conversion
1592  //     sequence is considered to be a subsequence of any
1593  //     non-identity conversion sequence) or, if not that,
1594  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1595    // Neither is a proper subsequence of the other. Do nothing.
1596    ;
1597  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1598           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1599           (SCS1.Second == ICK_Identity &&
1600            SCS1.Third == ICK_Identity))
1601    // SCS1 is a proper subsequence of SCS2.
1602    return ImplicitConversionSequence::Better;
1603  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1604           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1605           (SCS2.Second == ICK_Identity &&
1606            SCS2.Third == ICK_Identity))
1607    // SCS2 is a proper subsequence of SCS1.
1608    return ImplicitConversionSequence::Worse;
1609
1610  //  -- the rank of S1 is better than the rank of S2 (by the rules
1611  //     defined below), or, if not that,
1612  ImplicitConversionRank Rank1 = SCS1.getRank();
1613  ImplicitConversionRank Rank2 = SCS2.getRank();
1614  if (Rank1 < Rank2)
1615    return ImplicitConversionSequence::Better;
1616  else if (Rank2 < Rank1)
1617    return ImplicitConversionSequence::Worse;
1618
1619  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1620  // are indistinguishable unless one of the following rules
1621  // applies:
1622
1623  //   A conversion that is not a conversion of a pointer, or
1624  //   pointer to member, to bool is better than another conversion
1625  //   that is such a conversion.
1626  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1627    return SCS2.isPointerConversionToBool()
1628             ? ImplicitConversionSequence::Better
1629             : ImplicitConversionSequence::Worse;
1630
1631  // C++ [over.ics.rank]p4b2:
1632  //
1633  //   If class B is derived directly or indirectly from class A,
1634  //   conversion of B* to A* is better than conversion of B* to
1635  //   void*, and conversion of A* to void* is better than conversion
1636  //   of B* to void*.
1637  bool SCS1ConvertsToVoid
1638    = SCS1.isPointerConversionToVoidPointer(Context);
1639  bool SCS2ConvertsToVoid
1640    = SCS2.isPointerConversionToVoidPointer(Context);
1641  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1642    // Exactly one of the conversion sequences is a conversion to
1643    // a void pointer; it's the worse conversion.
1644    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1645                              : ImplicitConversionSequence::Worse;
1646  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1647    // Neither conversion sequence converts to a void pointer; compare
1648    // their derived-to-base conversions.
1649    if (ImplicitConversionSequence::CompareKind DerivedCK
1650          = CompareDerivedToBaseConversions(SCS1, SCS2))
1651      return DerivedCK;
1652  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1653    // Both conversion sequences are conversions to void
1654    // pointers. Compare the source types to determine if there's an
1655    // inheritance relationship in their sources.
1656    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1657    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1658
1659    // Adjust the types we're converting from via the array-to-pointer
1660    // conversion, if we need to.
1661    if (SCS1.First == ICK_Array_To_Pointer)
1662      FromType1 = Context.getArrayDecayedType(FromType1);
1663    if (SCS2.First == ICK_Array_To_Pointer)
1664      FromType2 = Context.getArrayDecayedType(FromType2);
1665
1666    QualType FromPointee1
1667      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1668    QualType FromPointee2
1669      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1670
1671    if (IsDerivedFrom(FromPointee2, FromPointee1))
1672      return ImplicitConversionSequence::Better;
1673    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1674      return ImplicitConversionSequence::Worse;
1675
1676    // Objective-C++: If one interface is more specific than the
1677    // other, it is the better one.
1678    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1679    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1680    if (FromIface1 && FromIface1) {
1681      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1682        return ImplicitConversionSequence::Better;
1683      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1684        return ImplicitConversionSequence::Worse;
1685    }
1686  }
1687
1688  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1689  // bullet 3).
1690  if (ImplicitConversionSequence::CompareKind QualCK
1691        = CompareQualificationConversions(SCS1, SCS2))
1692    return QualCK;
1693
1694  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1695    // C++0x [over.ics.rank]p3b4:
1696    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1697    //      implicit object parameter of a non-static member function declared
1698    //      without a ref-qualifier, and S1 binds an rvalue reference to an
1699    //      rvalue and S2 binds an lvalue reference.
1700    // FIXME: We don't know if we're dealing with the implicit object parameter,
1701    // or if the member function in this case has a ref qualifier.
1702    // (Of course, we don't have ref qualifiers yet.)
1703    if (SCS1.RRefBinding != SCS2.RRefBinding)
1704      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1705                              : ImplicitConversionSequence::Worse;
1706
1707    // C++ [over.ics.rank]p3b4:
1708    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1709    //      which the references refer are the same type except for
1710    //      top-level cv-qualifiers, and the type to which the reference
1711    //      initialized by S2 refers is more cv-qualified than the type
1712    //      to which the reference initialized by S1 refers.
1713    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1714    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1715    T1 = Context.getCanonicalType(T1);
1716    T2 = Context.getCanonicalType(T2);
1717    if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1718      if (T2.isMoreQualifiedThan(T1))
1719        return ImplicitConversionSequence::Better;
1720      else if (T1.isMoreQualifiedThan(T2))
1721        return ImplicitConversionSequence::Worse;
1722    }
1723  }
1724
1725  return ImplicitConversionSequence::Indistinguishable;
1726}
1727
1728/// CompareQualificationConversions - Compares two standard conversion
1729/// sequences to determine whether they can be ranked based on their
1730/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1731ImplicitConversionSequence::CompareKind
1732Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1733                                      const StandardConversionSequence& SCS2) {
1734  // C++ 13.3.3.2p3:
1735  //  -- S1 and S2 differ only in their qualification conversion and
1736  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1737  //     cv-qualification signature of type T1 is a proper subset of
1738  //     the cv-qualification signature of type T2, and S1 is not the
1739  //     deprecated string literal array-to-pointer conversion (4.2).
1740  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1741      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1742    return ImplicitConversionSequence::Indistinguishable;
1743
1744  // FIXME: the example in the standard doesn't use a qualification
1745  // conversion (!)
1746  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1747  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1748  T1 = Context.getCanonicalType(T1);
1749  T2 = Context.getCanonicalType(T2);
1750
1751  // If the types are the same, we won't learn anything by unwrapped
1752  // them.
1753  if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1754    return ImplicitConversionSequence::Indistinguishable;
1755
1756  ImplicitConversionSequence::CompareKind Result
1757    = ImplicitConversionSequence::Indistinguishable;
1758  while (UnwrapSimilarPointerTypes(T1, T2)) {
1759    // Within each iteration of the loop, we check the qualifiers to
1760    // determine if this still looks like a qualification
1761    // conversion. Then, if all is well, we unwrap one more level of
1762    // pointers or pointers-to-members and do it all again
1763    // until there are no more pointers or pointers-to-members left
1764    // to unwrap. This essentially mimics what
1765    // IsQualificationConversion does, but here we're checking for a
1766    // strict subset of qualifiers.
1767    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1768      // The qualifiers are the same, so this doesn't tell us anything
1769      // about how the sequences rank.
1770      ;
1771    else if (T2.isMoreQualifiedThan(T1)) {
1772      // T1 has fewer qualifiers, so it could be the better sequence.
1773      if (Result == ImplicitConversionSequence::Worse)
1774        // Neither has qualifiers that are a subset of the other's
1775        // qualifiers.
1776        return ImplicitConversionSequence::Indistinguishable;
1777
1778      Result = ImplicitConversionSequence::Better;
1779    } else if (T1.isMoreQualifiedThan(T2)) {
1780      // T2 has fewer qualifiers, so it could be the better sequence.
1781      if (Result == ImplicitConversionSequence::Better)
1782        // Neither has qualifiers that are a subset of the other's
1783        // qualifiers.
1784        return ImplicitConversionSequence::Indistinguishable;
1785
1786      Result = ImplicitConversionSequence::Worse;
1787    } else {
1788      // Qualifiers are disjoint.
1789      return ImplicitConversionSequence::Indistinguishable;
1790    }
1791
1792    // If the types after this point are equivalent, we're done.
1793    if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1794      break;
1795  }
1796
1797  // Check that the winning standard conversion sequence isn't using
1798  // the deprecated string literal array to pointer conversion.
1799  switch (Result) {
1800  case ImplicitConversionSequence::Better:
1801    if (SCS1.Deprecated)
1802      Result = ImplicitConversionSequence::Indistinguishable;
1803    break;
1804
1805  case ImplicitConversionSequence::Indistinguishable:
1806    break;
1807
1808  case ImplicitConversionSequence::Worse:
1809    if (SCS2.Deprecated)
1810      Result = ImplicitConversionSequence::Indistinguishable;
1811    break;
1812  }
1813
1814  return Result;
1815}
1816
1817/// CompareDerivedToBaseConversions - Compares two standard conversion
1818/// sequences to determine whether they can be ranked based on their
1819/// various kinds of derived-to-base conversions (C++
1820/// [over.ics.rank]p4b3).  As part of these checks, we also look at
1821/// conversions between Objective-C interface types.
1822ImplicitConversionSequence::CompareKind
1823Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1824                                      const StandardConversionSequence& SCS2) {
1825  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1826  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1827  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1828  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1829
1830  // Adjust the types we're converting from via the array-to-pointer
1831  // conversion, if we need to.
1832  if (SCS1.First == ICK_Array_To_Pointer)
1833    FromType1 = Context.getArrayDecayedType(FromType1);
1834  if (SCS2.First == ICK_Array_To_Pointer)
1835    FromType2 = Context.getArrayDecayedType(FromType2);
1836
1837  // Canonicalize all of the types.
1838  FromType1 = Context.getCanonicalType(FromType1);
1839  ToType1 = Context.getCanonicalType(ToType1);
1840  FromType2 = Context.getCanonicalType(FromType2);
1841  ToType2 = Context.getCanonicalType(ToType2);
1842
1843  // C++ [over.ics.rank]p4b3:
1844  //
1845  //   If class B is derived directly or indirectly from class A and
1846  //   class C is derived directly or indirectly from B,
1847  //
1848  // For Objective-C, we let A, B, and C also be Objective-C
1849  // interfaces.
1850
1851  // Compare based on pointer conversions.
1852  if (SCS1.Second == ICK_Pointer_Conversion &&
1853      SCS2.Second == ICK_Pointer_Conversion &&
1854      /*FIXME: Remove if Objective-C id conversions get their own rank*/
1855      FromType1->isPointerType() && FromType2->isPointerType() &&
1856      ToType1->isPointerType() && ToType2->isPointerType()) {
1857    QualType FromPointee1
1858      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1859    QualType ToPointee1
1860      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1861    QualType FromPointee2
1862      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1863    QualType ToPointee2
1864      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1865
1866    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1867    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1868    const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1869    const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
1870
1871    //   -- conversion of C* to B* is better than conversion of C* to A*,
1872    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1873      if (IsDerivedFrom(ToPointee1, ToPointee2))
1874        return ImplicitConversionSequence::Better;
1875      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1876        return ImplicitConversionSequence::Worse;
1877
1878      if (ToIface1 && ToIface2) {
1879        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1880          return ImplicitConversionSequence::Better;
1881        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1882          return ImplicitConversionSequence::Worse;
1883      }
1884    }
1885
1886    //   -- conversion of B* to A* is better than conversion of C* to A*,
1887    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1888      if (IsDerivedFrom(FromPointee2, FromPointee1))
1889        return ImplicitConversionSequence::Better;
1890      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1891        return ImplicitConversionSequence::Worse;
1892
1893      if (FromIface1 && FromIface2) {
1894        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1895          return ImplicitConversionSequence::Better;
1896        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1897          return ImplicitConversionSequence::Worse;
1898      }
1899    }
1900  }
1901
1902  // Compare based on reference bindings.
1903  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1904      SCS1.Second == ICK_Derived_To_Base) {
1905    //   -- binding of an expression of type C to a reference of type
1906    //      B& is better than binding an expression of type C to a
1907    //      reference of type A&,
1908    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1909        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1910      if (IsDerivedFrom(ToType1, ToType2))
1911        return ImplicitConversionSequence::Better;
1912      else if (IsDerivedFrom(ToType2, ToType1))
1913        return ImplicitConversionSequence::Worse;
1914    }
1915
1916    //   -- binding of an expression of type B to a reference of type
1917    //      A& is better than binding an expression of type C to a
1918    //      reference of type A&,
1919    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1920        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1921      if (IsDerivedFrom(FromType2, FromType1))
1922        return ImplicitConversionSequence::Better;
1923      else if (IsDerivedFrom(FromType1, FromType2))
1924        return ImplicitConversionSequence::Worse;
1925    }
1926  }
1927
1928
1929  // FIXME: conversion of A::* to B::* is better than conversion of
1930  // A::* to C::*,
1931
1932  // FIXME: conversion of B::* to C::* is better than conversion of
1933  // A::* to C::*, and
1934
1935  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1936      SCS1.Second == ICK_Derived_To_Base) {
1937    //   -- conversion of C to B is better than conversion of C to A,
1938    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1939        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1940      if (IsDerivedFrom(ToType1, ToType2))
1941        return ImplicitConversionSequence::Better;
1942      else if (IsDerivedFrom(ToType2, ToType1))
1943        return ImplicitConversionSequence::Worse;
1944    }
1945
1946    //   -- conversion of B to A is better than conversion of C to A.
1947    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1948        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1949      if (IsDerivedFrom(FromType2, FromType1))
1950        return ImplicitConversionSequence::Better;
1951      else if (IsDerivedFrom(FromType1, FromType2))
1952        return ImplicitConversionSequence::Worse;
1953    }
1954  }
1955
1956  return ImplicitConversionSequence::Indistinguishable;
1957}
1958
1959/// TryCopyInitialization - Try to copy-initialize a value of type
1960/// ToType from the expression From. Return the implicit conversion
1961/// sequence required to pass this argument, which may be a bad
1962/// conversion sequence (meaning that the argument cannot be passed to
1963/// a parameter of this type). If @p SuppressUserConversions, then we
1964/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1965/// then we treat @p From as an rvalue, even if it is an lvalue.
1966ImplicitConversionSequence
1967Sema::TryCopyInitialization(Expr *From, QualType ToType,
1968                            bool SuppressUserConversions, bool ForceRValue,
1969                            bool InOverloadResolution) {
1970  if (ToType->isReferenceType()) {
1971    ImplicitConversionSequence ICS;
1972    CheckReferenceInit(From, ToType,
1973                       /*FIXME:*/From->getLocStart(),
1974                       SuppressUserConversions,
1975                       /*AllowExplicit=*/false,
1976                       ForceRValue,
1977                       &ICS);
1978    return ICS;
1979  } else {
1980    return TryImplicitConversion(From, ToType,
1981                                 SuppressUserConversions,
1982                                 /*AllowExplicit=*/false,
1983                                 ForceRValue,
1984                                 InOverloadResolution);
1985  }
1986}
1987
1988/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1989/// the expression @p From. Returns true (and emits a diagnostic) if there was
1990/// an error, returns false if the initialization succeeded. Elidable should
1991/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
1992/// differently in C++0x for this case.
1993bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1994                                     const char* Flavor, bool Elidable) {
1995  if (!getLangOptions().CPlusPlus) {
1996    // In C, argument passing is the same as performing an assignment.
1997    QualType FromType = From->getType();
1998
1999    AssignConvertType ConvTy =
2000      CheckSingleAssignmentConstraints(ToType, From);
2001    if (ConvTy != Compatible &&
2002        CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2003      ConvTy = Compatible;
2004
2005    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2006                                    FromType, From, Flavor);
2007  }
2008
2009  if (ToType->isReferenceType())
2010    return CheckReferenceInit(From, ToType,
2011                              /*FIXME:*/From->getLocStart(),
2012                              /*SuppressUserConversions=*/false,
2013                              /*AllowExplicit=*/false,
2014                              /*ForceRValue=*/false);
2015
2016  if (!PerformImplicitConversion(From, ToType, Flavor,
2017                                 /*AllowExplicit=*/false, Elidable))
2018    return false;
2019  if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
2020    return Diag(From->getSourceRange().getBegin(),
2021                diag::err_typecheck_convert_incompatible)
2022      << ToType << From->getType() << Flavor << From->getSourceRange();
2023  return true;
2024}
2025
2026/// TryObjectArgumentInitialization - Try to initialize the object
2027/// parameter of the given member function (@c Method) from the
2028/// expression @p From.
2029ImplicitConversionSequence
2030Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2031  QualType ClassType = Context.getTypeDeclType(Method->getParent());
2032  QualType ImplicitParamType
2033    = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
2034
2035  // Set up the conversion sequence as a "bad" conversion, to allow us
2036  // to exit early.
2037  ImplicitConversionSequence ICS;
2038  ICS.Standard.setAsIdentityConversion();
2039  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2040
2041  // We need to have an object of class type.
2042  QualType FromType = From->getType();
2043  if (const PointerType *PT = FromType->getAs<PointerType>())
2044    FromType = PT->getPointeeType();
2045
2046  assert(FromType->isRecordType());
2047
2048  // The implicit object parmeter is has the type "reference to cv X",
2049  // where X is the class of which the function is a member
2050  // (C++ [over.match.funcs]p4). However, when finding an implicit
2051  // conversion sequence for the argument, we are not allowed to
2052  // create temporaries or perform user-defined conversions
2053  // (C++ [over.match.funcs]p5). We perform a simplified version of
2054  // reference binding here, that allows class rvalues to bind to
2055  // non-constant references.
2056
2057  // First check the qualifiers. We don't care about lvalue-vs-rvalue
2058  // with the implicit object parameter (C++ [over.match.funcs]p5).
2059  QualType FromTypeCanon = Context.getCanonicalType(FromType);
2060  if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2061      !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2062    return ICS;
2063
2064  // Check that we have either the same type or a derived type. It
2065  // affects the conversion rank.
2066  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2067  if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2068    ICS.Standard.Second = ICK_Identity;
2069  else if (IsDerivedFrom(FromType, ClassType))
2070    ICS.Standard.Second = ICK_Derived_To_Base;
2071  else
2072    return ICS;
2073
2074  // Success. Mark this as a reference binding.
2075  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2076  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2077  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2078  ICS.Standard.ReferenceBinding = true;
2079  ICS.Standard.DirectBinding = true;
2080  ICS.Standard.RRefBinding = false;
2081  return ICS;
2082}
2083
2084/// PerformObjectArgumentInitialization - Perform initialization of
2085/// the implicit object parameter for the given Method with the given
2086/// expression.
2087bool
2088Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2089  QualType FromRecordType, DestType;
2090  QualType ImplicitParamRecordType  =
2091    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2092
2093  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
2094    FromRecordType = PT->getPointeeType();
2095    DestType = Method->getThisType(Context);
2096  } else {
2097    FromRecordType = From->getType();
2098    DestType = ImplicitParamRecordType;
2099  }
2100
2101  ImplicitConversionSequence ICS
2102    = TryObjectArgumentInitialization(From, Method);
2103  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2104    return Diag(From->getSourceRange().getBegin(),
2105                diag::err_implicit_object_parameter_init)
2106       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2107
2108  if (ICS.Standard.Second == ICK_Derived_To_Base &&
2109      CheckDerivedToBaseConversion(FromRecordType,
2110                                   ImplicitParamRecordType,
2111                                   From->getSourceRange().getBegin(),
2112                                   From->getSourceRange()))
2113    return true;
2114
2115  ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2116                    /*isLvalue=*/true);
2117  return false;
2118}
2119
2120/// TryContextuallyConvertToBool - Attempt to contextually convert the
2121/// expression From to bool (C++0x [conv]p3).
2122ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2123  return TryImplicitConversion(From, Context.BoolTy,
2124                               // FIXME: Are these flags correct?
2125                               /*SuppressUserConversions=*/false,
2126                               /*AllowExplicit=*/true,
2127                               /*ForceRValue=*/false,
2128                               /*InOverloadResolution=*/false);
2129}
2130
2131/// PerformContextuallyConvertToBool - Perform a contextual conversion
2132/// of the expression From to bool (C++0x [conv]p3).
2133bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2134  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2135  if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2136    return false;
2137
2138  if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2139    return  Diag(From->getSourceRange().getBegin(),
2140                 diag::err_typecheck_bool_condition)
2141                  << From->getType() << From->getSourceRange();
2142  return true;
2143}
2144
2145/// AddOverloadCandidate - Adds the given function to the set of
2146/// candidate functions, using the given function call arguments.  If
2147/// @p SuppressUserConversions, then don't allow user-defined
2148/// conversions via constructors or conversion operators.
2149/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2150/// hacky way to implement the overloading rules for elidable copy
2151/// initialization in C++0x (C++0x 12.8p15).
2152///
2153/// \para PartialOverloading true if we are performing "partial" overloading
2154/// based on an incomplete set of function arguments. This feature is used by
2155/// code completion.
2156void
2157Sema::AddOverloadCandidate(FunctionDecl *Function,
2158                           Expr **Args, unsigned NumArgs,
2159                           OverloadCandidateSet& CandidateSet,
2160                           bool SuppressUserConversions,
2161                           bool ForceRValue,
2162                           bool PartialOverloading) {
2163  const FunctionProtoType* Proto
2164    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
2165  assert(Proto && "Functions without a prototype cannot be overloaded");
2166  assert(!isa<CXXConversionDecl>(Function) &&
2167         "Use AddConversionCandidate for conversion functions");
2168  assert(!Function->getDescribedFunctionTemplate() &&
2169         "Use AddTemplateOverloadCandidate for function templates");
2170
2171  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2172    if (!isa<CXXConstructorDecl>(Method)) {
2173      // If we get here, it's because we're calling a member function
2174      // that is named without a member access expression (e.g.,
2175      // "this->f") that was either written explicitly or created
2176      // implicitly. This can happen with a qualified call to a member
2177      // function, e.g., X::f(). We use a NULL object as the implied
2178      // object argument (C++ [over.call.func]p3).
2179      AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
2180                         SuppressUserConversions, ForceRValue);
2181      return;
2182    }
2183    // We treat a constructor like a non-member function, since its object
2184    // argument doesn't participate in overload resolution.
2185  }
2186
2187  if (!CandidateSet.isNewCandidate(Function))
2188    return;
2189
2190  // Add this candidate
2191  CandidateSet.push_back(OverloadCandidate());
2192  OverloadCandidate& Candidate = CandidateSet.back();
2193  Candidate.Function = Function;
2194  Candidate.Viable = true;
2195  Candidate.IsSurrogate = false;
2196  Candidate.IgnoreObjectArgument = false;
2197
2198  unsigned NumArgsInProto = Proto->getNumArgs();
2199
2200  // (C++ 13.3.2p2): A candidate function having fewer than m
2201  // parameters is viable only if it has an ellipsis in its parameter
2202  // list (8.3.5).
2203  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2204      !Proto->isVariadic()) {
2205    Candidate.Viable = false;
2206    return;
2207  }
2208
2209  // (C++ 13.3.2p2): A candidate function having more than m parameters
2210  // is viable only if the (m+1)st parameter has a default argument
2211  // (8.3.6). For the purposes of overload resolution, the
2212  // parameter list is truncated on the right, so that there are
2213  // exactly m parameters.
2214  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2215  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
2216    // Not enough arguments.
2217    Candidate.Viable = false;
2218    return;
2219  }
2220
2221  // Determine the implicit conversion sequences for each of the
2222  // arguments.
2223  Candidate.Conversions.resize(NumArgs);
2224  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2225    if (ArgIdx < NumArgsInProto) {
2226      // (C++ 13.3.2p3): for F to be a viable function, there shall
2227      // exist for each argument an implicit conversion sequence
2228      // (13.3.3.1) that converts that argument to the corresponding
2229      // parameter of F.
2230      QualType ParamType = Proto->getArgType(ArgIdx);
2231      Candidate.Conversions[ArgIdx]
2232        = TryCopyInitialization(Args[ArgIdx], ParamType,
2233                                SuppressUserConversions, ForceRValue,
2234                                /*InOverloadResolution=*/true);
2235      if (Candidate.Conversions[ArgIdx].ConversionKind
2236            == ImplicitConversionSequence::BadConversion) {
2237      // 13.3.3.1-p10 If several different sequences of conversions exist that
2238      // each convert the argument to the parameter type, the implicit conversion
2239      // sequence associated with the parameter is defined to be the unique conversion
2240      // sequence designated the ambiguous conversion sequence. For the purpose of
2241      // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2242      // conversion sequence is treated as a user-defined sequence that is
2243      // indistinguishable from any other user-defined conversion sequence
2244        if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty())
2245          Candidate.Conversions[ArgIdx].ConversionKind =
2246            ImplicitConversionSequence::UserDefinedConversion;
2247        else {
2248          Candidate.Viable = false;
2249          break;
2250        }
2251      }
2252    } else {
2253      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2254      // argument for which there is no corresponding parameter is
2255      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2256      Candidate.Conversions[ArgIdx].ConversionKind
2257        = ImplicitConversionSequence::EllipsisConversion;
2258    }
2259  }
2260}
2261
2262/// \brief Add all of the function declarations in the given function set to
2263/// the overload canddiate set.
2264void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2265                                 Expr **Args, unsigned NumArgs,
2266                                 OverloadCandidateSet& CandidateSet,
2267                                 bool SuppressUserConversions) {
2268  for (FunctionSet::const_iterator F = Functions.begin(),
2269                                FEnd = Functions.end();
2270       F != FEnd; ++F) {
2271    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2272      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2273        AddMethodCandidate(cast<CXXMethodDecl>(FD),
2274                           Args[0], Args + 1, NumArgs - 1,
2275                           CandidateSet, SuppressUserConversions);
2276      else
2277        AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2278                             SuppressUserConversions);
2279    } else {
2280      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2281      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2282          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2283        AddMethodTemplateCandidate(FunTmpl,
2284                                   /*FIXME: explicit args */false, 0, 0,
2285                                   Args[0], Args + 1, NumArgs - 1,
2286                                   CandidateSet,
2287                                   SuppressUserConversions);
2288      else
2289        AddTemplateOverloadCandidate(FunTmpl,
2290                                     /*FIXME: explicit args */false, 0, 0,
2291                                     Args, NumArgs, CandidateSet,
2292                                     SuppressUserConversions);
2293    }
2294  }
2295}
2296
2297/// AddMethodCandidate - Adds the given C++ member function to the set
2298/// of candidate functions, using the given function call arguments
2299/// and the object argument (@c Object). For example, in a call
2300/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2301/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2302/// allow user-defined conversions via constructors or conversion
2303/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2304/// a slightly hacky way to implement the overloading rules for elidable copy
2305/// initialization in C++0x (C++0x 12.8p15).
2306void
2307Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2308                         Expr **Args, unsigned NumArgs,
2309                         OverloadCandidateSet& CandidateSet,
2310                         bool SuppressUserConversions, bool ForceRValue) {
2311  const FunctionProtoType* Proto
2312    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
2313  assert(Proto && "Methods without a prototype cannot be overloaded");
2314  assert(!isa<CXXConversionDecl>(Method) &&
2315         "Use AddConversionCandidate for conversion functions");
2316  assert(!isa<CXXConstructorDecl>(Method) &&
2317         "Use AddOverloadCandidate for constructors");
2318
2319  if (!CandidateSet.isNewCandidate(Method))
2320    return;
2321
2322  // Add this candidate
2323  CandidateSet.push_back(OverloadCandidate());
2324  OverloadCandidate& Candidate = CandidateSet.back();
2325  Candidate.Function = Method;
2326  Candidate.IsSurrogate = false;
2327  Candidate.IgnoreObjectArgument = false;
2328
2329  unsigned NumArgsInProto = Proto->getNumArgs();
2330
2331  // (C++ 13.3.2p2): A candidate function having fewer than m
2332  // parameters is viable only if it has an ellipsis in its parameter
2333  // list (8.3.5).
2334  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2335    Candidate.Viable = false;
2336    return;
2337  }
2338
2339  // (C++ 13.3.2p2): A candidate function having more than m parameters
2340  // is viable only if the (m+1)st parameter has a default argument
2341  // (8.3.6). For the purposes of overload resolution, the
2342  // parameter list is truncated on the right, so that there are
2343  // exactly m parameters.
2344  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2345  if (NumArgs < MinRequiredArgs) {
2346    // Not enough arguments.
2347    Candidate.Viable = false;
2348    return;
2349  }
2350
2351  Candidate.Viable = true;
2352  Candidate.Conversions.resize(NumArgs + 1);
2353
2354  if (Method->isStatic() || !Object)
2355    // The implicit object argument is ignored.
2356    Candidate.IgnoreObjectArgument = true;
2357  else {
2358    // Determine the implicit conversion sequence for the object
2359    // parameter.
2360    Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
2361    if (Candidate.Conversions[0].ConversionKind
2362          == ImplicitConversionSequence::BadConversion) {
2363      Candidate.Viable = false;
2364      return;
2365    }
2366  }
2367
2368  // Determine the implicit conversion sequences for each of the
2369  // arguments.
2370  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2371    if (ArgIdx < NumArgsInProto) {
2372      // (C++ 13.3.2p3): for F to be a viable function, there shall
2373      // exist for each argument an implicit conversion sequence
2374      // (13.3.3.1) that converts that argument to the corresponding
2375      // parameter of F.
2376      QualType ParamType = Proto->getArgType(ArgIdx);
2377      Candidate.Conversions[ArgIdx + 1]
2378        = TryCopyInitialization(Args[ArgIdx], ParamType,
2379                                SuppressUserConversions, ForceRValue,
2380                                /*InOverloadResolution=*/true);
2381      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2382            == ImplicitConversionSequence::BadConversion) {
2383        Candidate.Viable = false;
2384        break;
2385      }
2386    } else {
2387      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2388      // argument for which there is no corresponding parameter is
2389      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2390      Candidate.Conversions[ArgIdx + 1].ConversionKind
2391        = ImplicitConversionSequence::EllipsisConversion;
2392    }
2393  }
2394}
2395
2396/// \brief Add a C++ member function template as a candidate to the candidate
2397/// set, using template argument deduction to produce an appropriate member
2398/// function template specialization.
2399void
2400Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2401                                 bool HasExplicitTemplateArgs,
2402                                 const TemplateArgument *ExplicitTemplateArgs,
2403                                 unsigned NumExplicitTemplateArgs,
2404                                 Expr *Object, Expr **Args, unsigned NumArgs,
2405                                 OverloadCandidateSet& CandidateSet,
2406                                 bool SuppressUserConversions,
2407                                 bool ForceRValue) {
2408  if (!CandidateSet.isNewCandidate(MethodTmpl))
2409    return;
2410
2411  // C++ [over.match.funcs]p7:
2412  //   In each case where a candidate is a function template, candidate
2413  //   function template specializations are generated using template argument
2414  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2415  //   candidate functions in the usual way.113) A given name can refer to one
2416  //   or more function templates and also to a set of overloaded non-template
2417  //   functions. In such a case, the candidate functions generated from each
2418  //   function template are combined with the set of non-template candidate
2419  //   functions.
2420  TemplateDeductionInfo Info(Context);
2421  FunctionDecl *Specialization = 0;
2422  if (TemplateDeductionResult Result
2423      = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2424                                ExplicitTemplateArgs, NumExplicitTemplateArgs,
2425                                Args, NumArgs, Specialization, Info)) {
2426        // FIXME: Record what happened with template argument deduction, so
2427        // that we can give the user a beautiful diagnostic.
2428        (void)Result;
2429        return;
2430      }
2431
2432  // Add the function template specialization produced by template argument
2433  // deduction as a candidate.
2434  assert(Specialization && "Missing member function template specialization?");
2435  assert(isa<CXXMethodDecl>(Specialization) &&
2436         "Specialization is not a member function?");
2437  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
2438                     CandidateSet, SuppressUserConversions, ForceRValue);
2439}
2440
2441/// \brief Add a C++ function template specialization as a candidate
2442/// in the candidate set, using template argument deduction to produce
2443/// an appropriate function template specialization.
2444void
2445Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2446                                   bool HasExplicitTemplateArgs,
2447                                 const TemplateArgument *ExplicitTemplateArgs,
2448                                   unsigned NumExplicitTemplateArgs,
2449                                   Expr **Args, unsigned NumArgs,
2450                                   OverloadCandidateSet& CandidateSet,
2451                                   bool SuppressUserConversions,
2452                                   bool ForceRValue) {
2453  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2454    return;
2455
2456  // C++ [over.match.funcs]p7:
2457  //   In each case where a candidate is a function template, candidate
2458  //   function template specializations are generated using template argument
2459  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2460  //   candidate functions in the usual way.113) A given name can refer to one
2461  //   or more function templates and also to a set of overloaded non-template
2462  //   functions. In such a case, the candidate functions generated from each
2463  //   function template are combined with the set of non-template candidate
2464  //   functions.
2465  TemplateDeductionInfo Info(Context);
2466  FunctionDecl *Specialization = 0;
2467  if (TemplateDeductionResult Result
2468        = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2469                                  ExplicitTemplateArgs, NumExplicitTemplateArgs,
2470                                  Args, NumArgs, Specialization, Info)) {
2471    // FIXME: Record what happened with template argument deduction, so
2472    // that we can give the user a beautiful diagnostic.
2473    (void)Result;
2474    return;
2475  }
2476
2477  // Add the function template specialization produced by template argument
2478  // deduction as a candidate.
2479  assert(Specialization && "Missing function template specialization?");
2480  AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2481                       SuppressUserConversions, ForceRValue);
2482}
2483
2484/// AddConversionCandidate - Add a C++ conversion function as a
2485/// candidate in the candidate set (C++ [over.match.conv],
2486/// C++ [over.match.copy]). From is the expression we're converting from,
2487/// and ToType is the type that we're eventually trying to convert to
2488/// (which may or may not be the same type as the type that the
2489/// conversion function produces).
2490void
2491Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2492                             Expr *From, QualType ToType,
2493                             OverloadCandidateSet& CandidateSet) {
2494  assert(!Conversion->getDescribedFunctionTemplate() &&
2495         "Conversion function templates use AddTemplateConversionCandidate");
2496
2497  if (!CandidateSet.isNewCandidate(Conversion))
2498    return;
2499
2500  // Add this candidate
2501  CandidateSet.push_back(OverloadCandidate());
2502  OverloadCandidate& Candidate = CandidateSet.back();
2503  Candidate.Function = Conversion;
2504  Candidate.IsSurrogate = false;
2505  Candidate.IgnoreObjectArgument = false;
2506  Candidate.FinalConversion.setAsIdentityConversion();
2507  Candidate.FinalConversion.FromTypePtr
2508    = Conversion->getConversionType().getAsOpaquePtr();
2509  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2510
2511  // Determine the implicit conversion sequence for the implicit
2512  // object parameter.
2513  Candidate.Viable = true;
2514  Candidate.Conversions.resize(1);
2515  Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
2516  // Conversion functions to a different type in the base class is visible in
2517  // the derived class.  So, a derived to base conversion should not participate
2518  // in overload resolution.
2519  if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2520    Candidate.Conversions[0].Standard.Second = ICK_Identity;
2521  if (Candidate.Conversions[0].ConversionKind
2522      == ImplicitConversionSequence::BadConversion) {
2523    Candidate.Viable = false;
2524    return;
2525  }
2526
2527  // To determine what the conversion from the result of calling the
2528  // conversion function to the type we're eventually trying to
2529  // convert to (ToType), we need to synthesize a call to the
2530  // conversion function and attempt copy initialization from it. This
2531  // makes sure that we get the right semantics with respect to
2532  // lvalues/rvalues and the type. Fortunately, we can allocate this
2533  // call on the stack and we don't need its arguments to be
2534  // well-formed.
2535  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2536                            SourceLocation());
2537  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2538                                CastExpr::CK_Unknown,
2539                                &ConversionRef, false);
2540
2541  // Note that it is safe to allocate CallExpr on the stack here because
2542  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2543  // allocator).
2544  CallExpr Call(Context, &ConversionFn, 0, 0,
2545                Conversion->getConversionType().getNonReferenceType(),
2546                SourceLocation());
2547  ImplicitConversionSequence ICS =
2548    TryCopyInitialization(&Call, ToType,
2549                          /*SuppressUserConversions=*/true,
2550                          /*ForceRValue=*/false,
2551                          /*InOverloadResolution=*/false);
2552
2553  switch (ICS.ConversionKind) {
2554  case ImplicitConversionSequence::StandardConversion:
2555    Candidate.FinalConversion = ICS.Standard;
2556    break;
2557
2558  case ImplicitConversionSequence::BadConversion:
2559    Candidate.Viable = false;
2560    break;
2561
2562  default:
2563    assert(false &&
2564           "Can only end up with a standard conversion sequence or failure");
2565  }
2566}
2567
2568/// \brief Adds a conversion function template specialization
2569/// candidate to the overload set, using template argument deduction
2570/// to deduce the template arguments of the conversion function
2571/// template from the type that we are converting to (C++
2572/// [temp.deduct.conv]).
2573void
2574Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2575                                     Expr *From, QualType ToType,
2576                                     OverloadCandidateSet &CandidateSet) {
2577  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2578         "Only conversion function templates permitted here");
2579
2580  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2581    return;
2582
2583  TemplateDeductionInfo Info(Context);
2584  CXXConversionDecl *Specialization = 0;
2585  if (TemplateDeductionResult Result
2586        = DeduceTemplateArguments(FunctionTemplate, ToType,
2587                                  Specialization, Info)) {
2588    // FIXME: Record what happened with template argument deduction, so
2589    // that we can give the user a beautiful diagnostic.
2590    (void)Result;
2591    return;
2592  }
2593
2594  // Add the conversion function template specialization produced by
2595  // template argument deduction as a candidate.
2596  assert(Specialization && "Missing function template specialization?");
2597  AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2598}
2599
2600/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2601/// converts the given @c Object to a function pointer via the
2602/// conversion function @c Conversion, and then attempts to call it
2603/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2604/// the type of function that we'll eventually be calling.
2605void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2606                                 const FunctionProtoType *Proto,
2607                                 Expr *Object, Expr **Args, unsigned NumArgs,
2608                                 OverloadCandidateSet& CandidateSet) {
2609  if (!CandidateSet.isNewCandidate(Conversion))
2610    return;
2611
2612  CandidateSet.push_back(OverloadCandidate());
2613  OverloadCandidate& Candidate = CandidateSet.back();
2614  Candidate.Function = 0;
2615  Candidate.Surrogate = Conversion;
2616  Candidate.Viable = true;
2617  Candidate.IsSurrogate = true;
2618  Candidate.IgnoreObjectArgument = false;
2619  Candidate.Conversions.resize(NumArgs + 1);
2620
2621  // Determine the implicit conversion sequence for the implicit
2622  // object parameter.
2623  ImplicitConversionSequence ObjectInit
2624    = TryObjectArgumentInitialization(Object, Conversion);
2625  if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2626    Candidate.Viable = false;
2627    return;
2628  }
2629
2630  // The first conversion is actually a user-defined conversion whose
2631  // first conversion is ObjectInit's standard conversion (which is
2632  // effectively a reference binding). Record it as such.
2633  Candidate.Conversions[0].ConversionKind
2634    = ImplicitConversionSequence::UserDefinedConversion;
2635  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2636  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2637  Candidate.Conversions[0].UserDefined.After
2638    = Candidate.Conversions[0].UserDefined.Before;
2639  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2640
2641  // Find the
2642  unsigned NumArgsInProto = Proto->getNumArgs();
2643
2644  // (C++ 13.3.2p2): A candidate function having fewer than m
2645  // parameters is viable only if it has an ellipsis in its parameter
2646  // list (8.3.5).
2647  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2648    Candidate.Viable = false;
2649    return;
2650  }
2651
2652  // Function types don't have any default arguments, so just check if
2653  // we have enough arguments.
2654  if (NumArgs < NumArgsInProto) {
2655    // Not enough arguments.
2656    Candidate.Viable = false;
2657    return;
2658  }
2659
2660  // Determine the implicit conversion sequences for each of the
2661  // arguments.
2662  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2663    if (ArgIdx < NumArgsInProto) {
2664      // (C++ 13.3.2p3): for F to be a viable function, there shall
2665      // exist for each argument an implicit conversion sequence
2666      // (13.3.3.1) that converts that argument to the corresponding
2667      // parameter of F.
2668      QualType ParamType = Proto->getArgType(ArgIdx);
2669      Candidate.Conversions[ArgIdx + 1]
2670        = TryCopyInitialization(Args[ArgIdx], ParamType,
2671                                /*SuppressUserConversions=*/false,
2672                                /*ForceRValue=*/false,
2673                                /*InOverloadResolution=*/false);
2674      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2675            == ImplicitConversionSequence::BadConversion) {
2676        Candidate.Viable = false;
2677        break;
2678      }
2679    } else {
2680      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2681      // argument for which there is no corresponding parameter is
2682      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2683      Candidate.Conversions[ArgIdx + 1].ConversionKind
2684        = ImplicitConversionSequence::EllipsisConversion;
2685    }
2686  }
2687}
2688
2689// FIXME: This will eventually be removed, once we've migrated all of the
2690// operator overloading logic over to the scheme used by binary operators, which
2691// works for template instantiation.
2692void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2693                                 SourceLocation OpLoc,
2694                                 Expr **Args, unsigned NumArgs,
2695                                 OverloadCandidateSet& CandidateSet,
2696                                 SourceRange OpRange) {
2697  FunctionSet Functions;
2698
2699  QualType T1 = Args[0]->getType();
2700  QualType T2;
2701  if (NumArgs > 1)
2702    T2 = Args[1]->getType();
2703
2704  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2705  if (S)
2706    LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2707  ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2708  AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2709  AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2710  AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2711}
2712
2713/// \brief Add overload candidates for overloaded operators that are
2714/// member functions.
2715///
2716/// Add the overloaded operator candidates that are member functions
2717/// for the operator Op that was used in an operator expression such
2718/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2719/// CandidateSet will store the added overload candidates. (C++
2720/// [over.match.oper]).
2721void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2722                                       SourceLocation OpLoc,
2723                                       Expr **Args, unsigned NumArgs,
2724                                       OverloadCandidateSet& CandidateSet,
2725                                       SourceRange OpRange) {
2726  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2727
2728  // C++ [over.match.oper]p3:
2729  //   For a unary operator @ with an operand of a type whose
2730  //   cv-unqualified version is T1, and for a binary operator @ with
2731  //   a left operand of a type whose cv-unqualified version is T1 and
2732  //   a right operand of a type whose cv-unqualified version is T2,
2733  //   three sets of candidate functions, designated member
2734  //   candidates, non-member candidates and built-in candidates, are
2735  //   constructed as follows:
2736  QualType T1 = Args[0]->getType();
2737  QualType T2;
2738  if (NumArgs > 1)
2739    T2 = Args[1]->getType();
2740
2741  //     -- If T1 is a class type, the set of member candidates is the
2742  //        result of the qualified lookup of T1::operator@
2743  //        (13.3.1.1.1); otherwise, the set of member candidates is
2744  //        empty.
2745  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
2746    // Complete the type if it can be completed. Otherwise, we're done.
2747    if (RequireCompleteType(OpLoc, T1, PartialDiagnostic(0)))
2748      return;
2749
2750    LookupResult Operators = LookupQualifiedName(T1Rec->getDecl(), OpName,
2751                                                 LookupOrdinaryName, false);
2752    for (LookupResult::iterator Oper = Operators.begin(),
2753                             OperEnd = Operators.end();
2754         Oper != OperEnd;
2755         ++Oper)
2756      AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
2757                         Args+1, NumArgs - 1, CandidateSet,
2758                         /*SuppressUserConversions=*/false);
2759  }
2760}
2761
2762/// AddBuiltinCandidate - Add a candidate for a built-in
2763/// operator. ResultTy and ParamTys are the result and parameter types
2764/// of the built-in candidate, respectively. Args and NumArgs are the
2765/// arguments being passed to the candidate. IsAssignmentOperator
2766/// should be true when this built-in candidate is an assignment
2767/// operator. NumContextualBoolArguments is the number of arguments
2768/// (at the beginning of the argument list) that will be contextually
2769/// converted to bool.
2770void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2771                               Expr **Args, unsigned NumArgs,
2772                               OverloadCandidateSet& CandidateSet,
2773                               bool IsAssignmentOperator,
2774                               unsigned NumContextualBoolArguments) {
2775  // Add this candidate
2776  CandidateSet.push_back(OverloadCandidate());
2777  OverloadCandidate& Candidate = CandidateSet.back();
2778  Candidate.Function = 0;
2779  Candidate.IsSurrogate = false;
2780  Candidate.IgnoreObjectArgument = false;
2781  Candidate.BuiltinTypes.ResultTy = ResultTy;
2782  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2783    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2784
2785  // Determine the implicit conversion sequences for each of the
2786  // arguments.
2787  Candidate.Viable = true;
2788  Candidate.Conversions.resize(NumArgs);
2789  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2790    // C++ [over.match.oper]p4:
2791    //   For the built-in assignment operators, conversions of the
2792    //   left operand are restricted as follows:
2793    //     -- no temporaries are introduced to hold the left operand, and
2794    //     -- no user-defined conversions are applied to the left
2795    //        operand to achieve a type match with the left-most
2796    //        parameter of a built-in candidate.
2797    //
2798    // We block these conversions by turning off user-defined
2799    // conversions, since that is the only way that initialization of
2800    // a reference to a non-class type can occur from something that
2801    // is not of the same type.
2802    if (ArgIdx < NumContextualBoolArguments) {
2803      assert(ParamTys[ArgIdx] == Context.BoolTy &&
2804             "Contextual conversion to bool requires bool type");
2805      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2806    } else {
2807      Candidate.Conversions[ArgIdx]
2808        = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2809                                ArgIdx == 0 && IsAssignmentOperator,
2810                                /*ForceRValue=*/false,
2811                                /*InOverloadResolution=*/false);
2812    }
2813    if (Candidate.Conversions[ArgIdx].ConversionKind
2814        == ImplicitConversionSequence::BadConversion) {
2815      Candidate.Viable = false;
2816      break;
2817    }
2818  }
2819}
2820
2821/// BuiltinCandidateTypeSet - A set of types that will be used for the
2822/// candidate operator functions for built-in operators (C++
2823/// [over.built]). The types are separated into pointer types and
2824/// enumeration types.
2825class BuiltinCandidateTypeSet  {
2826  /// TypeSet - A set of types.
2827  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
2828
2829  /// PointerTypes - The set of pointer types that will be used in the
2830  /// built-in candidates.
2831  TypeSet PointerTypes;
2832
2833  /// MemberPointerTypes - The set of member pointer types that will be
2834  /// used in the built-in candidates.
2835  TypeSet MemberPointerTypes;
2836
2837  /// EnumerationTypes - The set of enumeration types that will be
2838  /// used in the built-in candidates.
2839  TypeSet EnumerationTypes;
2840
2841  /// Sema - The semantic analysis instance where we are building the
2842  /// candidate type set.
2843  Sema &SemaRef;
2844
2845  /// Context - The AST context in which we will build the type sets.
2846  ASTContext &Context;
2847
2848  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2849  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
2850
2851public:
2852  /// iterator - Iterates through the types that are part of the set.
2853  typedef TypeSet::iterator iterator;
2854
2855  BuiltinCandidateTypeSet(Sema &SemaRef)
2856    : SemaRef(SemaRef), Context(SemaRef.Context) { }
2857
2858  void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2859                             bool AllowExplicitConversions);
2860
2861  /// pointer_begin - First pointer type found;
2862  iterator pointer_begin() { return PointerTypes.begin(); }
2863
2864  /// pointer_end - Past the last pointer type found;
2865  iterator pointer_end() { return PointerTypes.end(); }
2866
2867  /// member_pointer_begin - First member pointer type found;
2868  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2869
2870  /// member_pointer_end - Past the last member pointer type found;
2871  iterator member_pointer_end() { return MemberPointerTypes.end(); }
2872
2873  /// enumeration_begin - First enumeration type found;
2874  iterator enumeration_begin() { return EnumerationTypes.begin(); }
2875
2876  /// enumeration_end - Past the last enumeration type found;
2877  iterator enumeration_end() { return EnumerationTypes.end(); }
2878};
2879
2880/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2881/// the set of pointer types along with any more-qualified variants of
2882/// that type. For example, if @p Ty is "int const *", this routine
2883/// will add "int const *", "int const volatile *", "int const
2884/// restrict *", and "int const volatile restrict *" to the set of
2885/// pointer types. Returns true if the add of @p Ty itself succeeded,
2886/// false otherwise.
2887///
2888/// FIXME: what to do about extended qualifiers?
2889bool
2890BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
2891
2892  // Insert this type.
2893  if (!PointerTypes.insert(Ty))
2894    return false;
2895
2896  const PointerType *PointerTy = Ty->getAs<PointerType>();
2897  assert(PointerTy && "type was not a pointer type!");
2898
2899  QualType PointeeTy = PointerTy->getPointeeType();
2900  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2901
2902  // Iterate through all strict supersets of BaseCVR.
2903  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2904    if ((CVR | BaseCVR) != CVR) continue;
2905
2906    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2907    PointerTypes.insert(Context.getPointerType(QPointeeTy));
2908  }
2909
2910  return true;
2911}
2912
2913/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2914/// to the set of pointer types along with any more-qualified variants of
2915/// that type. For example, if @p Ty is "int const *", this routine
2916/// will add "int const *", "int const volatile *", "int const
2917/// restrict *", and "int const volatile restrict *" to the set of
2918/// pointer types. Returns true if the add of @p Ty itself succeeded,
2919/// false otherwise.
2920///
2921/// FIXME: what to do about extended qualifiers?
2922bool
2923BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2924    QualType Ty) {
2925  // Insert this type.
2926  if (!MemberPointerTypes.insert(Ty))
2927    return false;
2928
2929  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
2930  assert(PointerTy && "type was not a member pointer type!");
2931
2932  QualType PointeeTy = PointerTy->getPointeeType();
2933  const Type *ClassTy = PointerTy->getClass();
2934
2935  // Iterate through all strict supersets of the pointee type's CVR
2936  // qualifiers.
2937  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2938  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2939    if ((CVR | BaseCVR) != CVR) continue;
2940
2941    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2942    MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
2943  }
2944
2945  return true;
2946}
2947
2948/// AddTypesConvertedFrom - Add each of the types to which the type @p
2949/// Ty can be implicit converted to the given set of @p Types. We're
2950/// primarily interested in pointer types and enumeration types. We also
2951/// take member pointer types, for the conditional operator.
2952/// AllowUserConversions is true if we should look at the conversion
2953/// functions of a class type, and AllowExplicitConversions if we
2954/// should also include the explicit conversion functions of a class
2955/// type.
2956void
2957BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2958                                               bool AllowUserConversions,
2959                                               bool AllowExplicitConversions) {
2960  // Only deal with canonical types.
2961  Ty = Context.getCanonicalType(Ty);
2962
2963  // Look through reference types; they aren't part of the type of an
2964  // expression for the purposes of conversions.
2965  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
2966    Ty = RefTy->getPointeeType();
2967
2968  // We don't care about qualifiers on the type.
2969  Ty = Ty.getUnqualifiedType();
2970
2971  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
2972    QualType PointeeTy = PointerTy->getPointeeType();
2973
2974    // Insert our type, and its more-qualified variants, into the set
2975    // of types.
2976    if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
2977      return;
2978
2979    // Add 'cv void*' to our set of types.
2980    if (!Ty->isVoidType()) {
2981      QualType QualVoid
2982        = Context.getCVRQualifiedType(Context.VoidTy,
2983                                   PointeeTy.getCVRQualifiers());
2984      AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2985    }
2986
2987    // If this is a pointer to a class type, add pointers to its bases
2988    // (with the same level of cv-qualification as the original
2989    // derived class, of course).
2990    if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
2991      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2992      for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2993           Base != ClassDecl->bases_end(); ++Base) {
2994        QualType BaseTy = Context.getCanonicalType(Base->getType());
2995        BaseTy = Context.getCVRQualifiedType(BaseTy.getUnqualifiedType(),
2996                                          PointeeTy.getCVRQualifiers());
2997
2998        // Add the pointer type, recursively, so that we get all of
2999        // the indirect base classes, too.
3000        AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
3001      }
3002    }
3003  } else if (Ty->isMemberPointerType()) {
3004    // Member pointers are far easier, since the pointee can't be converted.
3005    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3006      return;
3007  } else if (Ty->isEnumeralType()) {
3008    EnumerationTypes.insert(Ty);
3009  } else if (AllowUserConversions) {
3010    if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
3011      if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
3012        // No conversion functions in incomplete types.
3013        return;
3014      }
3015
3016      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3017      // FIXME: Visit conversion functions in the base classes, too.
3018      OverloadedFunctionDecl *Conversions
3019        = ClassDecl->getConversionFunctions();
3020      for (OverloadedFunctionDecl::function_iterator Func
3021             = Conversions->function_begin();
3022           Func != Conversions->function_end(); ++Func) {
3023        CXXConversionDecl *Conv;
3024        FunctionTemplateDecl *ConvTemplate;
3025        GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3026
3027        // Skip conversion function templates; they don't tell us anything
3028        // about which builtin types we can convert to.
3029        if (ConvTemplate)
3030          continue;
3031
3032        if (AllowExplicitConversions || !Conv->isExplicit())
3033          AddTypesConvertedFrom(Conv->getConversionType(), false, false);
3034      }
3035    }
3036  }
3037}
3038
3039/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3040/// the volatile- and non-volatile-qualified assignment operators for the
3041/// given type to the candidate set.
3042static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3043                                                   QualType T,
3044                                                   Expr **Args,
3045                                                   unsigned NumArgs,
3046                                    OverloadCandidateSet &CandidateSet) {
3047  QualType ParamTypes[2];
3048
3049  // T& operator=(T&, T)
3050  ParamTypes[0] = S.Context.getLValueReferenceType(T);
3051  ParamTypes[1] = T;
3052  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3053                        /*IsAssignmentOperator=*/true);
3054
3055  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3056    // volatile T& operator=(volatile T&, T)
3057    ParamTypes[0]
3058      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
3059    ParamTypes[1] = T;
3060    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3061                          /*IsAssignmentOperator=*/true);
3062  }
3063}
3064
3065/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3066/// operator overloads to the candidate set (C++ [over.built]), based
3067/// on the operator @p Op and the arguments given. For example, if the
3068/// operator is a binary '+', this routine might add "int
3069/// operator+(int, int)" to cover integer addition.
3070void
3071Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3072                                   Expr **Args, unsigned NumArgs,
3073                                   OverloadCandidateSet& CandidateSet) {
3074  // The set of "promoted arithmetic types", which are the arithmetic
3075  // types are that preserved by promotion (C++ [over.built]p2). Note
3076  // that the first few of these types are the promoted integral
3077  // types; these types need to be first.
3078  // FIXME: What about complex?
3079  const unsigned FirstIntegralType = 0;
3080  const unsigned LastIntegralType = 13;
3081  const unsigned FirstPromotedIntegralType = 7,
3082                 LastPromotedIntegralType = 13;
3083  const unsigned FirstPromotedArithmeticType = 7,
3084                 LastPromotedArithmeticType = 16;
3085  const unsigned NumArithmeticTypes = 16;
3086  QualType ArithmeticTypes[NumArithmeticTypes] = {
3087    Context.BoolTy, Context.CharTy, Context.WCharTy,
3088// FIXME:   Context.Char16Ty, Context.Char32Ty,
3089    Context.SignedCharTy, Context.ShortTy,
3090    Context.UnsignedCharTy, Context.UnsignedShortTy,
3091    Context.IntTy, Context.LongTy, Context.LongLongTy,
3092    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3093    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3094  };
3095
3096  // Find all of the types that the arguments can convert to, but only
3097  // if the operator we're looking at has built-in operator candidates
3098  // that make use of these types.
3099  BuiltinCandidateTypeSet CandidateTypes(*this);
3100  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3101      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3102      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3103      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3104      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3105      (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3106    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3107      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3108                                           true,
3109                                           (Op == OO_Exclaim ||
3110                                            Op == OO_AmpAmp ||
3111                                            Op == OO_PipePipe));
3112  }
3113
3114  bool isComparison = false;
3115  switch (Op) {
3116  case OO_None:
3117  case NUM_OVERLOADED_OPERATORS:
3118    assert(false && "Expected an overloaded operator");
3119    break;
3120
3121  case OO_Star: // '*' is either unary or binary
3122    if (NumArgs == 1)
3123      goto UnaryStar;
3124    else
3125      goto BinaryStar;
3126    break;
3127
3128  case OO_Plus: // '+' is either unary or binary
3129    if (NumArgs == 1)
3130      goto UnaryPlus;
3131    else
3132      goto BinaryPlus;
3133    break;
3134
3135  case OO_Minus: // '-' is either unary or binary
3136    if (NumArgs == 1)
3137      goto UnaryMinus;
3138    else
3139      goto BinaryMinus;
3140    break;
3141
3142  case OO_Amp: // '&' is either unary or binary
3143    if (NumArgs == 1)
3144      goto UnaryAmp;
3145    else
3146      goto BinaryAmp;
3147
3148  case OO_PlusPlus:
3149  case OO_MinusMinus:
3150    // C++ [over.built]p3:
3151    //
3152    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
3153    //   is either volatile or empty, there exist candidate operator
3154    //   functions of the form
3155    //
3156    //       VQ T&      operator++(VQ T&);
3157    //       T          operator++(VQ T&, int);
3158    //
3159    // C++ [over.built]p4:
3160    //
3161    //   For every pair (T, VQ), where T is an arithmetic type other
3162    //   than bool, and VQ is either volatile or empty, there exist
3163    //   candidate operator functions of the form
3164    //
3165    //       VQ T&      operator--(VQ T&);
3166    //       T          operator--(VQ T&, int);
3167    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3168         Arith < NumArithmeticTypes; ++Arith) {
3169      QualType ArithTy = ArithmeticTypes[Arith];
3170      QualType ParamTypes[2]
3171        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3172
3173      // Non-volatile version.
3174      if (NumArgs == 1)
3175        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3176      else
3177        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3178
3179      // Volatile version
3180      ParamTypes[0]
3181        = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3182      if (NumArgs == 1)
3183        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3184      else
3185        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3186    }
3187
3188    // C++ [over.built]p5:
3189    //
3190    //   For every pair (T, VQ), where T is a cv-qualified or
3191    //   cv-unqualified object type, and VQ is either volatile or
3192    //   empty, there exist candidate operator functions of the form
3193    //
3194    //       T*VQ&      operator++(T*VQ&);
3195    //       T*VQ&      operator--(T*VQ&);
3196    //       T*         operator++(T*VQ&, int);
3197    //       T*         operator--(T*VQ&, int);
3198    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3199         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3200      // Skip pointer types that aren't pointers to object types.
3201      if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3202        continue;
3203
3204      QualType ParamTypes[2] = {
3205        Context.getLValueReferenceType(*Ptr), Context.IntTy
3206      };
3207
3208      // Without volatile
3209      if (NumArgs == 1)
3210        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3211      else
3212        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3213
3214      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3215        // With volatile
3216        ParamTypes[0]
3217          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3218        if (NumArgs == 1)
3219          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3220        else
3221          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3222      }
3223    }
3224    break;
3225
3226  UnaryStar:
3227    // C++ [over.built]p6:
3228    //   For every cv-qualified or cv-unqualified object type T, there
3229    //   exist candidate operator functions of the form
3230    //
3231    //       T&         operator*(T*);
3232    //
3233    // C++ [over.built]p7:
3234    //   For every function type T, there exist candidate operator
3235    //   functions of the form
3236    //       T&         operator*(T*);
3237    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3238         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3239      QualType ParamTy = *Ptr;
3240      QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3241      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3242                          &ParamTy, Args, 1, CandidateSet);
3243    }
3244    break;
3245
3246  UnaryPlus:
3247    // C++ [over.built]p8:
3248    //   For every type T, there exist candidate operator functions of
3249    //   the form
3250    //
3251    //       T*         operator+(T*);
3252    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3253         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3254      QualType ParamTy = *Ptr;
3255      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3256    }
3257
3258    // Fall through
3259
3260  UnaryMinus:
3261    // C++ [over.built]p9:
3262    //  For every promoted arithmetic type T, there exist candidate
3263    //  operator functions of the form
3264    //
3265    //       T         operator+(T);
3266    //       T         operator-(T);
3267    for (unsigned Arith = FirstPromotedArithmeticType;
3268         Arith < LastPromotedArithmeticType; ++Arith) {
3269      QualType ArithTy = ArithmeticTypes[Arith];
3270      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3271    }
3272    break;
3273
3274  case OO_Tilde:
3275    // C++ [over.built]p10:
3276    //   For every promoted integral type T, there exist candidate
3277    //   operator functions of the form
3278    //
3279    //        T         operator~(T);
3280    for (unsigned Int = FirstPromotedIntegralType;
3281         Int < LastPromotedIntegralType; ++Int) {
3282      QualType IntTy = ArithmeticTypes[Int];
3283      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3284    }
3285    break;
3286
3287  case OO_New:
3288  case OO_Delete:
3289  case OO_Array_New:
3290  case OO_Array_Delete:
3291  case OO_Call:
3292    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3293    break;
3294
3295  case OO_Comma:
3296  UnaryAmp:
3297  case OO_Arrow:
3298    // C++ [over.match.oper]p3:
3299    //   -- For the operator ',', the unary operator '&', or the
3300    //      operator '->', the built-in candidates set is empty.
3301    break;
3302
3303  case OO_EqualEqual:
3304  case OO_ExclaimEqual:
3305    // C++ [over.match.oper]p16:
3306    //   For every pointer to member type T, there exist candidate operator
3307    //   functions of the form
3308    //
3309    //        bool operator==(T,T);
3310    //        bool operator!=(T,T);
3311    for (BuiltinCandidateTypeSet::iterator
3312           MemPtr = CandidateTypes.member_pointer_begin(),
3313           MemPtrEnd = CandidateTypes.member_pointer_end();
3314         MemPtr != MemPtrEnd;
3315         ++MemPtr) {
3316      QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3317      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3318    }
3319
3320    // Fall through
3321
3322  case OO_Less:
3323  case OO_Greater:
3324  case OO_LessEqual:
3325  case OO_GreaterEqual:
3326    // C++ [over.built]p15:
3327    //
3328    //   For every pointer or enumeration type T, there exist
3329    //   candidate operator functions of the form
3330    //
3331    //        bool       operator<(T, T);
3332    //        bool       operator>(T, T);
3333    //        bool       operator<=(T, T);
3334    //        bool       operator>=(T, T);
3335    //        bool       operator==(T, T);
3336    //        bool       operator!=(T, T);
3337    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3338         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3339      QualType ParamTypes[2] = { *Ptr, *Ptr };
3340      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3341    }
3342    for (BuiltinCandidateTypeSet::iterator Enum
3343           = CandidateTypes.enumeration_begin();
3344         Enum != CandidateTypes.enumeration_end(); ++Enum) {
3345      QualType ParamTypes[2] = { *Enum, *Enum };
3346      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3347    }
3348
3349    // Fall through.
3350    isComparison = true;
3351
3352  BinaryPlus:
3353  BinaryMinus:
3354    if (!isComparison) {
3355      // We didn't fall through, so we must have OO_Plus or OO_Minus.
3356
3357      // C++ [over.built]p13:
3358      //
3359      //   For every cv-qualified or cv-unqualified object type T
3360      //   there exist candidate operator functions of the form
3361      //
3362      //      T*         operator+(T*, ptrdiff_t);
3363      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
3364      //      T*         operator-(T*, ptrdiff_t);
3365      //      T*         operator+(ptrdiff_t, T*);
3366      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
3367      //
3368      // C++ [over.built]p14:
3369      //
3370      //   For every T, where T is a pointer to object type, there
3371      //   exist candidate operator functions of the form
3372      //
3373      //      ptrdiff_t  operator-(T, T);
3374      for (BuiltinCandidateTypeSet::iterator Ptr
3375             = CandidateTypes.pointer_begin();
3376           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3377        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3378
3379        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3380        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3381
3382        if (Op == OO_Plus) {
3383          // T* operator+(ptrdiff_t, T*);
3384          ParamTypes[0] = ParamTypes[1];
3385          ParamTypes[1] = *Ptr;
3386          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3387        } else {
3388          // ptrdiff_t operator-(T, T);
3389          ParamTypes[1] = *Ptr;
3390          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3391                              Args, 2, CandidateSet);
3392        }
3393      }
3394    }
3395    // Fall through
3396
3397  case OO_Slash:
3398  BinaryStar:
3399  Conditional:
3400    // C++ [over.built]p12:
3401    //
3402    //   For every pair of promoted arithmetic types L and R, there
3403    //   exist candidate operator functions of the form
3404    //
3405    //        LR         operator*(L, R);
3406    //        LR         operator/(L, R);
3407    //        LR         operator+(L, R);
3408    //        LR         operator-(L, R);
3409    //        bool       operator<(L, R);
3410    //        bool       operator>(L, R);
3411    //        bool       operator<=(L, R);
3412    //        bool       operator>=(L, R);
3413    //        bool       operator==(L, R);
3414    //        bool       operator!=(L, R);
3415    //
3416    //   where LR is the result of the usual arithmetic conversions
3417    //   between types L and R.
3418    //
3419    // C++ [over.built]p24:
3420    //
3421    //   For every pair of promoted arithmetic types L and R, there exist
3422    //   candidate operator functions of the form
3423    //
3424    //        LR       operator?(bool, L, R);
3425    //
3426    //   where LR is the result of the usual arithmetic conversions
3427    //   between types L and R.
3428    // Our candidates ignore the first parameter.
3429    for (unsigned Left = FirstPromotedArithmeticType;
3430         Left < LastPromotedArithmeticType; ++Left) {
3431      for (unsigned Right = FirstPromotedArithmeticType;
3432           Right < LastPromotedArithmeticType; ++Right) {
3433        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3434        QualType Result
3435          = isComparison
3436          ? Context.BoolTy
3437          : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3438        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3439      }
3440    }
3441    break;
3442
3443  case OO_Percent:
3444  BinaryAmp:
3445  case OO_Caret:
3446  case OO_Pipe:
3447  case OO_LessLess:
3448  case OO_GreaterGreater:
3449    // C++ [over.built]p17:
3450    //
3451    //   For every pair of promoted integral types L and R, there
3452    //   exist candidate operator functions of the form
3453    //
3454    //      LR         operator%(L, R);
3455    //      LR         operator&(L, R);
3456    //      LR         operator^(L, R);
3457    //      LR         operator|(L, R);
3458    //      L          operator<<(L, R);
3459    //      L          operator>>(L, R);
3460    //
3461    //   where LR is the result of the usual arithmetic conversions
3462    //   between types L and R.
3463    for (unsigned Left = FirstPromotedIntegralType;
3464         Left < LastPromotedIntegralType; ++Left) {
3465      for (unsigned Right = FirstPromotedIntegralType;
3466           Right < LastPromotedIntegralType; ++Right) {
3467        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3468        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3469            ? LandR[0]
3470            : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3471        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3472      }
3473    }
3474    break;
3475
3476  case OO_Equal:
3477    // C++ [over.built]p20:
3478    //
3479    //   For every pair (T, VQ), where T is an enumeration or
3480    //   pointer to member type and VQ is either volatile or
3481    //   empty, there exist candidate operator functions of the form
3482    //
3483    //        VQ T&      operator=(VQ T&, T);
3484    for (BuiltinCandidateTypeSet::iterator
3485           Enum = CandidateTypes.enumeration_begin(),
3486           EnumEnd = CandidateTypes.enumeration_end();
3487         Enum != EnumEnd; ++Enum)
3488      AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3489                                             CandidateSet);
3490    for (BuiltinCandidateTypeSet::iterator
3491           MemPtr = CandidateTypes.member_pointer_begin(),
3492         MemPtrEnd = CandidateTypes.member_pointer_end();
3493         MemPtr != MemPtrEnd; ++MemPtr)
3494      AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3495                                             CandidateSet);
3496      // Fall through.
3497
3498  case OO_PlusEqual:
3499  case OO_MinusEqual:
3500    // C++ [over.built]p19:
3501    //
3502    //   For every pair (T, VQ), where T is any type and VQ is either
3503    //   volatile or empty, there exist candidate operator functions
3504    //   of the form
3505    //
3506    //        T*VQ&      operator=(T*VQ&, T*);
3507    //
3508    // C++ [over.built]p21:
3509    //
3510    //   For every pair (T, VQ), where T is a cv-qualified or
3511    //   cv-unqualified object type and VQ is either volatile or
3512    //   empty, there exist candidate operator functions of the form
3513    //
3514    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
3515    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
3516    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3517         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3518      QualType ParamTypes[2];
3519      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3520
3521      // non-volatile version
3522      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3523      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3524                          /*IsAssigmentOperator=*/Op == OO_Equal);
3525
3526      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3527        // volatile version
3528        ParamTypes[0]
3529          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3530        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3531                            /*IsAssigmentOperator=*/Op == OO_Equal);
3532      }
3533    }
3534    // Fall through.
3535
3536  case OO_StarEqual:
3537  case OO_SlashEqual:
3538    // C++ [over.built]p18:
3539    //
3540    //   For every triple (L, VQ, R), where L is an arithmetic type,
3541    //   VQ is either volatile or empty, and R is a promoted
3542    //   arithmetic type, there exist candidate operator functions of
3543    //   the form
3544    //
3545    //        VQ L&      operator=(VQ L&, R);
3546    //        VQ L&      operator*=(VQ L&, R);
3547    //        VQ L&      operator/=(VQ L&, R);
3548    //        VQ L&      operator+=(VQ L&, R);
3549    //        VQ L&      operator-=(VQ L&, R);
3550    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3551      for (unsigned Right = FirstPromotedArithmeticType;
3552           Right < LastPromotedArithmeticType; ++Right) {
3553        QualType ParamTypes[2];
3554        ParamTypes[1] = ArithmeticTypes[Right];
3555
3556        // Add this built-in operator as a candidate (VQ is empty).
3557        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3558        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3559                            /*IsAssigmentOperator=*/Op == OO_Equal);
3560
3561        // Add this built-in operator as a candidate (VQ is 'volatile').
3562        ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3563        ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3564        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3565                            /*IsAssigmentOperator=*/Op == OO_Equal);
3566      }
3567    }
3568    break;
3569
3570  case OO_PercentEqual:
3571  case OO_LessLessEqual:
3572  case OO_GreaterGreaterEqual:
3573  case OO_AmpEqual:
3574  case OO_CaretEqual:
3575  case OO_PipeEqual:
3576    // C++ [over.built]p22:
3577    //
3578    //   For every triple (L, VQ, R), where L is an integral type, VQ
3579    //   is either volatile or empty, and R is a promoted integral
3580    //   type, there exist candidate operator functions of the form
3581    //
3582    //        VQ L&       operator%=(VQ L&, R);
3583    //        VQ L&       operator<<=(VQ L&, R);
3584    //        VQ L&       operator>>=(VQ L&, R);
3585    //        VQ L&       operator&=(VQ L&, R);
3586    //        VQ L&       operator^=(VQ L&, R);
3587    //        VQ L&       operator|=(VQ L&, R);
3588    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3589      for (unsigned Right = FirstPromotedIntegralType;
3590           Right < LastPromotedIntegralType; ++Right) {
3591        QualType ParamTypes[2];
3592        ParamTypes[1] = ArithmeticTypes[Right];
3593
3594        // Add this built-in operator as a candidate (VQ is empty).
3595        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3596        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3597
3598        // Add this built-in operator as a candidate (VQ is 'volatile').
3599        ParamTypes[0] = ArithmeticTypes[Left];
3600        ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3601        ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3602        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3603      }
3604    }
3605    break;
3606
3607  case OO_Exclaim: {
3608    // C++ [over.operator]p23:
3609    //
3610    //   There also exist candidate operator functions of the form
3611    //
3612    //        bool        operator!(bool);
3613    //        bool        operator&&(bool, bool);     [BELOW]
3614    //        bool        operator||(bool, bool);     [BELOW]
3615    QualType ParamTy = Context.BoolTy;
3616    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3617                        /*IsAssignmentOperator=*/false,
3618                        /*NumContextualBoolArguments=*/1);
3619    break;
3620  }
3621
3622  case OO_AmpAmp:
3623  case OO_PipePipe: {
3624    // C++ [over.operator]p23:
3625    //
3626    //   There also exist candidate operator functions of the form
3627    //
3628    //        bool        operator!(bool);            [ABOVE]
3629    //        bool        operator&&(bool, bool);
3630    //        bool        operator||(bool, bool);
3631    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3632    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3633                        /*IsAssignmentOperator=*/false,
3634                        /*NumContextualBoolArguments=*/2);
3635    break;
3636  }
3637
3638  case OO_Subscript:
3639    // C++ [over.built]p13:
3640    //
3641    //   For every cv-qualified or cv-unqualified object type T there
3642    //   exist candidate operator functions of the form
3643    //
3644    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
3645    //        T&         operator[](T*, ptrdiff_t);
3646    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
3647    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
3648    //        T&         operator[](ptrdiff_t, T*);
3649    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3650         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3651      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3652      QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
3653      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3654
3655      // T& operator[](T*, ptrdiff_t)
3656      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3657
3658      // T& operator[](ptrdiff_t, T*);
3659      ParamTypes[0] = ParamTypes[1];
3660      ParamTypes[1] = *Ptr;
3661      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3662    }
3663    break;
3664
3665  case OO_ArrowStar:
3666    // FIXME: No support for pointer-to-members yet.
3667    break;
3668
3669  case OO_Conditional:
3670    // Note that we don't consider the first argument, since it has been
3671    // contextually converted to bool long ago. The candidates below are
3672    // therefore added as binary.
3673    //
3674    // C++ [over.built]p24:
3675    //   For every type T, where T is a pointer or pointer-to-member type,
3676    //   there exist candidate operator functions of the form
3677    //
3678    //        T        operator?(bool, T, T);
3679    //
3680    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3681         E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3682      QualType ParamTypes[2] = { *Ptr, *Ptr };
3683      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3684    }
3685    for (BuiltinCandidateTypeSet::iterator Ptr =
3686           CandidateTypes.member_pointer_begin(),
3687         E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3688      QualType ParamTypes[2] = { *Ptr, *Ptr };
3689      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3690    }
3691    goto Conditional;
3692  }
3693}
3694
3695/// \brief Add function candidates found via argument-dependent lookup
3696/// to the set of overloading candidates.
3697///
3698/// This routine performs argument-dependent name lookup based on the
3699/// given function name (which may also be an operator name) and adds
3700/// all of the overload candidates found by ADL to the overload
3701/// candidate set (C++ [basic.lookup.argdep]).
3702void
3703Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3704                                           Expr **Args, unsigned NumArgs,
3705                                           bool HasExplicitTemplateArgs,
3706                                const TemplateArgument *ExplicitTemplateArgs,
3707                                           unsigned NumExplicitTemplateArgs,
3708                                           OverloadCandidateSet& CandidateSet,
3709                                           bool PartialOverloading) {
3710  FunctionSet Functions;
3711
3712  // FIXME: Should we be trafficking in canonical function decls throughout?
3713
3714  // Record all of the function candidates that we've already
3715  // added to the overload set, so that we don't add those same
3716  // candidates a second time.
3717  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3718                                   CandEnd = CandidateSet.end();
3719       Cand != CandEnd; ++Cand)
3720    if (Cand->Function) {
3721      Functions.insert(Cand->Function);
3722      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3723        Functions.insert(FunTmpl);
3724    }
3725
3726  // FIXME: Pass in the explicit template arguments?
3727  ArgumentDependentLookup(Name, Args, NumArgs, Functions);
3728
3729  // Erase all of the candidates we already knew about.
3730  // FIXME: This is suboptimal. Is there a better way?
3731  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3732                                   CandEnd = CandidateSet.end();
3733       Cand != CandEnd; ++Cand)
3734    if (Cand->Function) {
3735      Functions.erase(Cand->Function);
3736      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3737        Functions.erase(FunTmpl);
3738    }
3739
3740  // For each of the ADL candidates we found, add it to the overload
3741  // set.
3742  for (FunctionSet::iterator Func = Functions.begin(),
3743                          FuncEnd = Functions.end();
3744       Func != FuncEnd; ++Func) {
3745    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3746      if (HasExplicitTemplateArgs)
3747        continue;
3748
3749      AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3750                           false, false, PartialOverloading);
3751    } else
3752      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
3753                                   HasExplicitTemplateArgs,
3754                                   ExplicitTemplateArgs,
3755                                   NumExplicitTemplateArgs,
3756                                   Args, NumArgs, CandidateSet);
3757  }
3758}
3759
3760/// isBetterOverloadCandidate - Determines whether the first overload
3761/// candidate is a better candidate than the second (C++ 13.3.3p1).
3762bool
3763Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
3764                                const OverloadCandidate& Cand2) {
3765  // Define viable functions to be better candidates than non-viable
3766  // functions.
3767  if (!Cand2.Viable)
3768    return Cand1.Viable;
3769  else if (!Cand1.Viable)
3770    return false;
3771
3772  // C++ [over.match.best]p1:
3773  //
3774  //   -- if F is a static member function, ICS1(F) is defined such
3775  //      that ICS1(F) is neither better nor worse than ICS1(G) for
3776  //      any function G, and, symmetrically, ICS1(G) is neither
3777  //      better nor worse than ICS1(F).
3778  unsigned StartArg = 0;
3779  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3780    StartArg = 1;
3781
3782  // C++ [over.match.best]p1:
3783  //   A viable function F1 is defined to be a better function than another
3784  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
3785  //   conversion sequence than ICSi(F2), and then...
3786  unsigned NumArgs = Cand1.Conversions.size();
3787  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3788  bool HasBetterConversion = false;
3789  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
3790    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3791                                               Cand2.Conversions[ArgIdx])) {
3792    case ImplicitConversionSequence::Better:
3793      // Cand1 has a better conversion sequence.
3794      HasBetterConversion = true;
3795      break;
3796
3797    case ImplicitConversionSequence::Worse:
3798      // Cand1 can't be better than Cand2.
3799      return false;
3800
3801    case ImplicitConversionSequence::Indistinguishable:
3802      // Do nothing.
3803      break;
3804    }
3805  }
3806
3807  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
3808  //       ICSj(F2), or, if not that,
3809  if (HasBetterConversion)
3810    return true;
3811
3812  //     - F1 is a non-template function and F2 is a function template
3813  //       specialization, or, if not that,
3814  if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3815      Cand2.Function && Cand2.Function->getPrimaryTemplate())
3816    return true;
3817
3818  //   -- F1 and F2 are function template specializations, and the function
3819  //      template for F1 is more specialized than the template for F2
3820  //      according to the partial ordering rules described in 14.5.5.2, or,
3821  //      if not that,
3822  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3823      Cand2.Function && Cand2.Function->getPrimaryTemplate())
3824    if (FunctionTemplateDecl *BetterTemplate
3825          = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3826                                       Cand2.Function->getPrimaryTemplate(),
3827                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3828                                                             : TPOC_Call))
3829      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
3830
3831  //   -- the context is an initialization by user-defined conversion
3832  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
3833  //      from the return type of F1 to the destination type (i.e.,
3834  //      the type of the entity being initialized) is a better
3835  //      conversion sequence than the standard conversion sequence
3836  //      from the return type of F2 to the destination type.
3837  if (Cand1.Function && Cand2.Function &&
3838      isa<CXXConversionDecl>(Cand1.Function) &&
3839      isa<CXXConversionDecl>(Cand2.Function)) {
3840    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3841                                               Cand2.FinalConversion)) {
3842    case ImplicitConversionSequence::Better:
3843      // Cand1 has a better conversion sequence.
3844      return true;
3845
3846    case ImplicitConversionSequence::Worse:
3847      // Cand1 can't be better than Cand2.
3848      return false;
3849
3850    case ImplicitConversionSequence::Indistinguishable:
3851      // Do nothing
3852      break;
3853    }
3854  }
3855
3856  return false;
3857}
3858
3859/// \brief Computes the best viable function (C++ 13.3.3)
3860/// within an overload candidate set.
3861///
3862/// \param CandidateSet the set of candidate functions.
3863///
3864/// \param Loc the location of the function name (or operator symbol) for
3865/// which overload resolution occurs.
3866///
3867/// \param Best f overload resolution was successful or found a deleted
3868/// function, Best points to the candidate function found.
3869///
3870/// \returns The result of overload resolution.
3871Sema::OverloadingResult
3872Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
3873                         SourceLocation Loc,
3874                         OverloadCandidateSet::iterator& Best) {
3875  // Find the best viable function.
3876  Best = CandidateSet.end();
3877  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3878       Cand != CandidateSet.end(); ++Cand) {
3879    if (Cand->Viable) {
3880      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3881        Best = Cand;
3882    }
3883  }
3884
3885  // If we didn't find any viable functions, abort.
3886  if (Best == CandidateSet.end())
3887    return OR_No_Viable_Function;
3888
3889  // Make sure that this function is better than every other viable
3890  // function. If not, we have an ambiguity.
3891  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3892       Cand != CandidateSet.end(); ++Cand) {
3893    if (Cand->Viable &&
3894        Cand != Best &&
3895        !isBetterOverloadCandidate(*Best, *Cand)) {
3896      Best = CandidateSet.end();
3897      return OR_Ambiguous;
3898    }
3899  }
3900
3901  // Best is the best viable function.
3902  if (Best->Function &&
3903      (Best->Function->isDeleted() ||
3904       Best->Function->getAttr<UnavailableAttr>()))
3905    return OR_Deleted;
3906
3907  // C++ [basic.def.odr]p2:
3908  //   An overloaded function is used if it is selected by overload resolution
3909  //   when referred to from a potentially-evaluated expression. [Note: this
3910  //   covers calls to named functions (5.2.2), operator overloading
3911  //   (clause 13), user-defined conversions (12.3.2), allocation function for
3912  //   placement new (5.3.4), as well as non-default initialization (8.5).
3913  if (Best->Function)
3914    MarkDeclarationReferenced(Loc, Best->Function);
3915  return OR_Success;
3916}
3917
3918/// PrintOverloadCandidates - When overload resolution fails, prints
3919/// diagnostic messages containing the candidates in the candidate
3920/// set. If OnlyViable is true, only viable candidates will be printed.
3921void
3922Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
3923                              bool OnlyViable) {
3924  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3925                             LastCand = CandidateSet.end();
3926  for (; Cand != LastCand; ++Cand) {
3927    if (Cand->Viable || !OnlyViable) {
3928      if (Cand->Function) {
3929        if (Cand->Function->isDeleted() ||
3930            Cand->Function->getAttr<UnavailableAttr>()) {
3931          // Deleted or "unavailable" function.
3932          Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3933            << Cand->Function->isDeleted();
3934        } else if (FunctionTemplateDecl *FunTmpl
3935                     = Cand->Function->getPrimaryTemplate()) {
3936          // Function template specialization
3937          // FIXME: Give a better reason!
3938          Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
3939            << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
3940                              *Cand->Function->getTemplateSpecializationArgs());
3941        } else {
3942          // Normal function
3943          bool errReported = false;
3944          if (!Cand->Viable && Cand->Conversions.size() > 0) {
3945            for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
3946              const ImplicitConversionSequence &Conversion =
3947                                                        Cand->Conversions[i];
3948              if ((Conversion.ConversionKind !=
3949                   ImplicitConversionSequence::BadConversion) ||
3950                  Conversion.ConversionFunctionSet.size() == 0)
3951                continue;
3952              Diag(Cand->Function->getLocation(),
3953                   diag::err_ovl_candidate_not_viable) << (i+1);
3954              errReported = true;
3955              for (int j = Conversion.ConversionFunctionSet.size()-1;
3956                   j >= 0; j--) {
3957                FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
3958                Diag(Func->getLocation(), diag::err_ovl_candidate);
3959              }
3960            }
3961          }
3962          if (!errReported)
3963            Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
3964        }
3965      } else if (Cand->IsSurrogate) {
3966        // Desugar the type of the surrogate down to a function type,
3967        // retaining as many typedefs as possible while still showing
3968        // the function type (and, therefore, its parameter types).
3969        QualType FnType = Cand->Surrogate->getConversionType();
3970        bool isLValueReference = false;
3971        bool isRValueReference = false;
3972        bool isPointer = false;
3973        if (const LValueReferenceType *FnTypeRef =
3974              FnType->getAs<LValueReferenceType>()) {
3975          FnType = FnTypeRef->getPointeeType();
3976          isLValueReference = true;
3977        } else if (const RValueReferenceType *FnTypeRef =
3978                     FnType->getAs<RValueReferenceType>()) {
3979          FnType = FnTypeRef->getPointeeType();
3980          isRValueReference = true;
3981        }
3982        if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
3983          FnType = FnTypePtr->getPointeeType();
3984          isPointer = true;
3985        }
3986        // Desugar down to a function type.
3987        FnType = QualType(FnType->getAs<FunctionType>(), 0);
3988        // Reconstruct the pointer/reference as appropriate.
3989        if (isPointer) FnType = Context.getPointerType(FnType);
3990        if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
3991        if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
3992
3993        Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
3994          << FnType;
3995      } else {
3996        // FIXME: We need to get the identifier in here
3997        // FIXME: Do we want the error message to point at the operator?
3998        // (built-ins won't have a location)
3999        QualType FnType
4000          = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
4001                                    Cand->BuiltinTypes.ParamTypes,
4002                                    Cand->Conversions.size(),
4003                                    false, 0);
4004
4005        Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
4006      }
4007    }
4008  }
4009}
4010
4011/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4012/// an overloaded function (C++ [over.over]), where @p From is an
4013/// expression with overloaded function type and @p ToType is the type
4014/// we're trying to resolve to. For example:
4015///
4016/// @code
4017/// int f(double);
4018/// int f(int);
4019///
4020/// int (*pfd)(double) = f; // selects f(double)
4021/// @endcode
4022///
4023/// This routine returns the resulting FunctionDecl if it could be
4024/// resolved, and NULL otherwise. When @p Complain is true, this
4025/// routine will emit diagnostics if there is an error.
4026FunctionDecl *
4027Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
4028                                         bool Complain) {
4029  QualType FunctionType = ToType;
4030  bool IsMember = false;
4031  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
4032    FunctionType = ToTypePtr->getPointeeType();
4033  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
4034    FunctionType = ToTypeRef->getPointeeType();
4035  else if (const MemberPointerType *MemTypePtr =
4036                    ToType->getAs<MemberPointerType>()) {
4037    FunctionType = MemTypePtr->getPointeeType();
4038    IsMember = true;
4039  }
4040
4041  // We only look at pointers or references to functions.
4042  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
4043  if (!FunctionType->isFunctionType())
4044    return 0;
4045
4046  // Find the actual overloaded function declaration.
4047  OverloadedFunctionDecl *Ovl = 0;
4048
4049  // C++ [over.over]p1:
4050  //   [...] [Note: any redundant set of parentheses surrounding the
4051  //   overloaded function name is ignored (5.1). ]
4052  Expr *OvlExpr = From->IgnoreParens();
4053
4054  // C++ [over.over]p1:
4055  //   [...] The overloaded function name can be preceded by the &
4056  //   operator.
4057  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4058    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4059      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4060  }
4061
4062  // Try to dig out the overloaded function.
4063  FunctionTemplateDecl *FunctionTemplate = 0;
4064  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
4065    Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
4066    FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
4067  }
4068
4069  // If there's no overloaded function declaration or function template,
4070  // we're done.
4071  if (!Ovl && !FunctionTemplate)
4072    return 0;
4073
4074  OverloadIterator Fun;
4075  if (Ovl)
4076    Fun = Ovl;
4077  else
4078    Fun = FunctionTemplate;
4079
4080  // Look through all of the overloaded functions, searching for one
4081  // whose type matches exactly.
4082  llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
4083  bool FoundNonTemplateFunction = false;
4084  for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
4085    // C++ [over.over]p3:
4086    //   Non-member functions and static member functions match
4087    //   targets of type "pointer-to-function" or "reference-to-function."
4088    //   Nonstatic member functions match targets of
4089    //   type "pointer-to-member-function."
4090    // Note that according to DR 247, the containing class does not matter.
4091
4092    if (FunctionTemplateDecl *FunctionTemplate
4093          = dyn_cast<FunctionTemplateDecl>(*Fun)) {
4094      if (CXXMethodDecl *Method
4095            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
4096        // Skip non-static function templates when converting to pointer, and
4097        // static when converting to member pointer.
4098        if (Method->isStatic() == IsMember)
4099          continue;
4100      } else if (IsMember)
4101        continue;
4102
4103      // C++ [over.over]p2:
4104      //   If the name is a function template, template argument deduction is
4105      //   done (14.8.2.2), and if the argument deduction succeeds, the
4106      //   resulting template argument list is used to generate a single
4107      //   function template specialization, which is added to the set of
4108      //   overloaded functions considered.
4109      // FIXME: We don't really want to build the specialization here, do we?
4110      FunctionDecl *Specialization = 0;
4111      TemplateDeductionInfo Info(Context);
4112      if (TemplateDeductionResult Result
4113            = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
4114                                      /*FIXME:*/0, /*FIXME:*/0,
4115                                      FunctionType, Specialization, Info)) {
4116        // FIXME: make a note of the failed deduction for diagnostics.
4117        (void)Result;
4118      } else {
4119        // FIXME: If the match isn't exact, shouldn't we just drop this as
4120        // a candidate? Find a testcase before changing the code.
4121        assert(FunctionType
4122                 == Context.getCanonicalType(Specialization->getType()));
4123        Matches.insert(
4124                cast<FunctionDecl>(Specialization->getCanonicalDecl()));
4125      }
4126    }
4127
4128    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4129      // Skip non-static functions when converting to pointer, and static
4130      // when converting to member pointer.
4131      if (Method->isStatic() == IsMember)
4132        continue;
4133    } else if (IsMember)
4134      continue;
4135
4136    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
4137      if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
4138        Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
4139        FoundNonTemplateFunction = true;
4140      }
4141    }
4142  }
4143
4144  // If there were 0 or 1 matches, we're done.
4145  if (Matches.empty())
4146    return 0;
4147  else if (Matches.size() == 1)
4148    return *Matches.begin();
4149
4150  // C++ [over.over]p4:
4151  //   If more than one function is selected, [...]
4152  typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
4153  if (!FoundNonTemplateFunction) {
4154    //   [...] and any given function template specialization F1 is
4155    //   eliminated if the set contains a second function template
4156    //   specialization whose function template is more specialized
4157    //   than the function template of F1 according to the partial
4158    //   ordering rules of 14.5.5.2.
4159
4160    // The algorithm specified above is quadratic. We instead use a
4161    // two-pass algorithm (similar to the one used to identify the
4162    // best viable function in an overload set) that identifies the
4163    // best function template (if it exists).
4164    llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4165                                                         Matches.end());
4166    return getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4167                              TPOC_Other, From->getLocStart(),
4168                              PartialDiagnostic(0),
4169                            PartialDiagnostic(diag::err_addr_ovl_ambiguous)
4170                              << TemplateMatches[0]->getDeclName(),
4171                       PartialDiagnostic(diag::err_ovl_template_candidate));
4172  }
4173
4174  //   [...] any function template specializations in the set are
4175  //   eliminated if the set also contains a non-template function, [...]
4176  llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4177  for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4178    if ((*M)->getPrimaryTemplate() == 0)
4179      RemainingMatches.push_back(*M);
4180
4181  // [...] After such eliminations, if any, there shall remain exactly one
4182  // selected function.
4183  if (RemainingMatches.size() == 1)
4184    return RemainingMatches.front();
4185
4186  // FIXME: We should probably return the same thing that BestViableFunction
4187  // returns (even if we issue the diagnostics here).
4188  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4189    << RemainingMatches[0]->getDeclName();
4190  for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4191    Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
4192  return 0;
4193}
4194
4195/// \brief Add a single candidate to the overload set.
4196static void AddOverloadedCallCandidate(Sema &S,
4197                                       AnyFunctionDecl Callee,
4198                                       bool &ArgumentDependentLookup,
4199                                       bool HasExplicitTemplateArgs,
4200                                 const TemplateArgument *ExplicitTemplateArgs,
4201                                       unsigned NumExplicitTemplateArgs,
4202                                       Expr **Args, unsigned NumArgs,
4203                                       OverloadCandidateSet &CandidateSet,
4204                                       bool PartialOverloading) {
4205  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4206    assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4207    S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4208                           PartialOverloading);
4209
4210    if (Func->getDeclContext()->isRecord() ||
4211        Func->getDeclContext()->isFunctionOrMethod())
4212      ArgumentDependentLookup = false;
4213    return;
4214  }
4215
4216  FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4217  S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4218                                 ExplicitTemplateArgs,
4219                                 NumExplicitTemplateArgs,
4220                                 Args, NumArgs, CandidateSet);
4221
4222  if (FuncTemplate->getDeclContext()->isRecord())
4223    ArgumentDependentLookup = false;
4224}
4225
4226/// \brief Add the overload candidates named by callee and/or found by argument
4227/// dependent lookup to the given overload set.
4228void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4229                                       DeclarationName &UnqualifiedName,
4230                                       bool &ArgumentDependentLookup,
4231                                       bool HasExplicitTemplateArgs,
4232                                  const TemplateArgument *ExplicitTemplateArgs,
4233                                       unsigned NumExplicitTemplateArgs,
4234                                       Expr **Args, unsigned NumArgs,
4235                                       OverloadCandidateSet &CandidateSet,
4236                                       bool PartialOverloading) {
4237  // Add the functions denoted by Callee to the set of candidate
4238  // functions. While we're doing so, track whether argument-dependent
4239  // lookup still applies, per:
4240  //
4241  // C++0x [basic.lookup.argdep]p3:
4242  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
4243  //   and let Y be the lookup set produced by argument dependent
4244  //   lookup (defined as follows). If X contains
4245  //
4246  //     -- a declaration of a class member, or
4247  //
4248  //     -- a block-scope function declaration that is not a
4249  //        using-declaration (FIXME: check for using declaration), or
4250  //
4251  //     -- a declaration that is neither a function or a function
4252  //        template
4253  //
4254  //   then Y is empty.
4255  if (!Callee) {
4256    // Nothing to do.
4257  } else if (OverloadedFunctionDecl *Ovl
4258               = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4259    for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4260                                                FuncEnd = Ovl->function_end();
4261         Func != FuncEnd; ++Func)
4262      AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4263                                 HasExplicitTemplateArgs,
4264                                 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4265                                 Args, NumArgs, CandidateSet,
4266                                 PartialOverloading);
4267  } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4268    AddOverloadedCallCandidate(*this,
4269                               AnyFunctionDecl::getFromNamedDecl(Callee),
4270                               ArgumentDependentLookup,
4271                               HasExplicitTemplateArgs,
4272                               ExplicitTemplateArgs, NumExplicitTemplateArgs,
4273                               Args, NumArgs, CandidateSet,
4274                               PartialOverloading);
4275  // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4276  // checking dynamically.
4277
4278  if (Callee)
4279    UnqualifiedName = Callee->getDeclName();
4280
4281  if (ArgumentDependentLookup)
4282    AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4283                                         HasExplicitTemplateArgs,
4284                                         ExplicitTemplateArgs,
4285                                         NumExplicitTemplateArgs,
4286                                         CandidateSet,
4287                                         PartialOverloading);
4288}
4289
4290/// ResolveOverloadedCallFn - Given the call expression that calls Fn
4291/// (which eventually refers to the declaration Func) and the call
4292/// arguments Args/NumArgs, attempt to resolve the function call down
4293/// to a specific function. If overload resolution succeeds, returns
4294/// the function declaration produced by overload
4295/// resolution. Otherwise, emits diagnostics, deletes all of the
4296/// arguments and Fn, and returns NULL.
4297FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
4298                                            DeclarationName UnqualifiedName,
4299                                            bool HasExplicitTemplateArgs,
4300                                 const TemplateArgument *ExplicitTemplateArgs,
4301                                            unsigned NumExplicitTemplateArgs,
4302                                            SourceLocation LParenLoc,
4303                                            Expr **Args, unsigned NumArgs,
4304                                            SourceLocation *CommaLocs,
4305                                            SourceLocation RParenLoc,
4306                                            bool &ArgumentDependentLookup) {
4307  OverloadCandidateSet CandidateSet;
4308
4309  // Add the functions denoted by Callee to the set of candidate
4310  // functions.
4311  AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4312                              HasExplicitTemplateArgs, ExplicitTemplateArgs,
4313                              NumExplicitTemplateArgs, Args, NumArgs,
4314                              CandidateSet);
4315  OverloadCandidateSet::iterator Best;
4316  switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
4317  case OR_Success:
4318    return Best->Function;
4319
4320  case OR_No_Viable_Function:
4321    Diag(Fn->getSourceRange().getBegin(),
4322         diag::err_ovl_no_viable_function_in_call)
4323      << UnqualifiedName << Fn->getSourceRange();
4324    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4325    break;
4326
4327  case OR_Ambiguous:
4328    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
4329      << UnqualifiedName << Fn->getSourceRange();
4330    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4331    break;
4332
4333  case OR_Deleted:
4334    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4335      << Best->Function->isDeleted()
4336      << UnqualifiedName
4337      << Fn->getSourceRange();
4338    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4339    break;
4340  }
4341
4342  // Overload resolution failed. Destroy all of the subexpressions and
4343  // return NULL.
4344  Fn->Destroy(Context);
4345  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4346    Args[Arg]->Destroy(Context);
4347  return 0;
4348}
4349
4350/// \brief Create a unary operation that may resolve to an overloaded
4351/// operator.
4352///
4353/// \param OpLoc The location of the operator itself (e.g., '*').
4354///
4355/// \param OpcIn The UnaryOperator::Opcode that describes this
4356/// operator.
4357///
4358/// \param Functions The set of non-member functions that will be
4359/// considered by overload resolution. The caller needs to build this
4360/// set based on the context using, e.g.,
4361/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4362/// set should not contain any member functions; those will be added
4363/// by CreateOverloadedUnaryOp().
4364///
4365/// \param input The input argument.
4366Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4367                                                     unsigned OpcIn,
4368                                                     FunctionSet &Functions,
4369                                                     ExprArg input) {
4370  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4371  Expr *Input = (Expr *)input.get();
4372
4373  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4374  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4375  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4376
4377  Expr *Args[2] = { Input, 0 };
4378  unsigned NumArgs = 1;
4379
4380  // For post-increment and post-decrement, add the implicit '0' as
4381  // the second argument, so that we know this is a post-increment or
4382  // post-decrement.
4383  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4384    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4385    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4386                                           SourceLocation());
4387    NumArgs = 2;
4388  }
4389
4390  if (Input->isTypeDependent()) {
4391    OverloadedFunctionDecl *Overloads
4392      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4393    for (FunctionSet::iterator Func = Functions.begin(),
4394                            FuncEnd = Functions.end();
4395         Func != FuncEnd; ++Func)
4396      Overloads->addOverload(*Func);
4397
4398    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4399                                                OpLoc, false, false);
4400
4401    input.release();
4402    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4403                                                   &Args[0], NumArgs,
4404                                                   Context.DependentTy,
4405                                                   OpLoc));
4406  }
4407
4408  // Build an empty overload set.
4409  OverloadCandidateSet CandidateSet;
4410
4411  // Add the candidates from the given function set.
4412  AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4413
4414  // Add operator candidates that are member functions.
4415  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4416
4417  // Add builtin operator candidates.
4418  AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4419
4420  // Perform overload resolution.
4421  OverloadCandidateSet::iterator Best;
4422  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4423  case OR_Success: {
4424    // We found a built-in operator or an overloaded operator.
4425    FunctionDecl *FnDecl = Best->Function;
4426
4427    if (FnDecl) {
4428      // We matched an overloaded operator. Build a call to that
4429      // operator.
4430
4431      // Convert the arguments.
4432      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4433        if (PerformObjectArgumentInitialization(Input, Method))
4434          return ExprError();
4435      } else {
4436        // Convert the arguments.
4437        if (PerformCopyInitialization(Input,
4438                                      FnDecl->getParamDecl(0)->getType(),
4439                                      "passing"))
4440          return ExprError();
4441      }
4442
4443      // Determine the result type
4444      QualType ResultTy
4445        = FnDecl->getType()->getAs<FunctionType>()->getResultType();
4446      ResultTy = ResultTy.getNonReferenceType();
4447
4448      // Build the actual expression node.
4449      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4450                                               SourceLocation());
4451      UsualUnaryConversions(FnExpr);
4452
4453      input.release();
4454
4455      Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4456                                                   &Input, 1, ResultTy, OpLoc);
4457      return MaybeBindToTemporary(CE);
4458    } else {
4459      // We matched a built-in operator. Convert the arguments, then
4460      // break out so that we will build the appropriate built-in
4461      // operator node.
4462        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4463                                      Best->Conversions[0], "passing"))
4464          return ExprError();
4465
4466        break;
4467      }
4468    }
4469
4470    case OR_No_Viable_Function:
4471      // No viable function; fall through to handling this as a
4472      // built-in operator, which will produce an error message for us.
4473      break;
4474
4475    case OR_Ambiguous:
4476      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4477          << UnaryOperator::getOpcodeStr(Opc)
4478          << Input->getSourceRange();
4479      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4480      return ExprError();
4481
4482    case OR_Deleted:
4483      Diag(OpLoc, diag::err_ovl_deleted_oper)
4484        << Best->Function->isDeleted()
4485        << UnaryOperator::getOpcodeStr(Opc)
4486        << Input->getSourceRange();
4487      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4488      return ExprError();
4489    }
4490
4491  // Either we found no viable overloaded operator or we matched a
4492  // built-in operator. In either case, fall through to trying to
4493  // build a built-in operation.
4494  input.release();
4495  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4496}
4497
4498/// \brief Create a binary operation that may resolve to an overloaded
4499/// operator.
4500///
4501/// \param OpLoc The location of the operator itself (e.g., '+').
4502///
4503/// \param OpcIn The BinaryOperator::Opcode that describes this
4504/// operator.
4505///
4506/// \param Functions The set of non-member functions that will be
4507/// considered by overload resolution. The caller needs to build this
4508/// set based on the context using, e.g.,
4509/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4510/// set should not contain any member functions; those will be added
4511/// by CreateOverloadedBinOp().
4512///
4513/// \param LHS Left-hand argument.
4514/// \param RHS Right-hand argument.
4515Sema::OwningExprResult
4516Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4517                            unsigned OpcIn,
4518                            FunctionSet &Functions,
4519                            Expr *LHS, Expr *RHS) {
4520  Expr *Args[2] = { LHS, RHS };
4521  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
4522
4523  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4524  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4525  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4526
4527  // If either side is type-dependent, create an appropriate dependent
4528  // expression.
4529  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4530    // .* cannot be overloaded.
4531    if (Opc == BinaryOperator::PtrMemD)
4532      return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4533                                                Context.DependentTy, OpLoc));
4534
4535    OverloadedFunctionDecl *Overloads
4536      = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4537    for (FunctionSet::iterator Func = Functions.begin(),
4538                            FuncEnd = Functions.end();
4539         Func != FuncEnd; ++Func)
4540      Overloads->addOverload(*Func);
4541
4542    DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4543                                                OpLoc, false, false);
4544
4545    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4546                                                   Args, 2,
4547                                                   Context.DependentTy,
4548                                                   OpLoc));
4549  }
4550
4551  // If this is the .* operator, which is not overloadable, just
4552  // create a built-in binary operator.
4553  if (Opc == BinaryOperator::PtrMemD)
4554    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4555
4556  // If this is one of the assignment operators, we only perform
4557  // overload resolution if the left-hand side is a class or
4558  // enumeration type (C++ [expr.ass]p3).
4559  if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
4560      !Args[0]->getType()->isOverloadableType())
4561    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4562
4563  // Build an empty overload set.
4564  OverloadCandidateSet CandidateSet;
4565
4566  // Add the candidates from the given function set.
4567  AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4568
4569  // Add operator candidates that are member functions.
4570  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4571
4572  // Add builtin operator candidates.
4573  AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4574
4575  // Perform overload resolution.
4576  OverloadCandidateSet::iterator Best;
4577  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4578    case OR_Success: {
4579      // We found a built-in operator or an overloaded operator.
4580      FunctionDecl *FnDecl = Best->Function;
4581
4582      if (FnDecl) {
4583        // We matched an overloaded operator. Build a call to that
4584        // operator.
4585
4586        // Convert the arguments.
4587        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4588          if (PerformObjectArgumentInitialization(Args[0], Method) ||
4589              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
4590                                        "passing"))
4591            return ExprError();
4592        } else {
4593          // Convert the arguments.
4594          if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
4595                                        "passing") ||
4596              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
4597                                        "passing"))
4598            return ExprError();
4599        }
4600
4601        // Determine the result type
4602        QualType ResultTy
4603          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
4604        ResultTy = ResultTy.getNonReferenceType();
4605
4606        // Build the actual expression node.
4607        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4608                                                 OpLoc);
4609        UsualUnaryConversions(FnExpr);
4610
4611        Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4612                                                     Args, 2, ResultTy, OpLoc);
4613        return MaybeBindToTemporary(CE);
4614      } else {
4615        // We matched a built-in operator. Convert the arguments, then
4616        // break out so that we will build the appropriate built-in
4617        // operator node.
4618        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
4619                                      Best->Conversions[0], "passing") ||
4620            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
4621                                      Best->Conversions[1], "passing"))
4622          return ExprError();
4623
4624        break;
4625      }
4626    }
4627
4628    case OR_No_Viable_Function:
4629      // For class as left operand for assignment or compound assigment operator
4630      // do not fall through to handling in built-in, but report that no overloaded
4631      // assignment operator found
4632      if (Args[0]->getType()->isRecordType() && Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
4633        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
4634             << BinaryOperator::getOpcodeStr(Opc)
4635             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4636        return ExprError();
4637      }
4638      // No viable function; fall through to handling this as a
4639      // built-in operator, which will produce an error message for us.
4640      break;
4641
4642    case OR_Ambiguous:
4643      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4644          << BinaryOperator::getOpcodeStr(Opc)
4645          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4646      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4647      return ExprError();
4648
4649    case OR_Deleted:
4650      Diag(OpLoc, diag::err_ovl_deleted_oper)
4651        << Best->Function->isDeleted()
4652        << BinaryOperator::getOpcodeStr(Opc)
4653        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
4654      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4655      return ExprError();
4656    }
4657
4658  // Either we found no viable overloaded operator or we matched a
4659  // built-in operator. In either case, try to build a built-in
4660  // operation.
4661  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4662}
4663
4664/// BuildCallToMemberFunction - Build a call to a member
4665/// function. MemExpr is the expression that refers to the member
4666/// function (and includes the object parameter), Args/NumArgs are the
4667/// arguments to the function call (not including the object
4668/// parameter). The caller needs to validate that the member
4669/// expression refers to a member function or an overloaded member
4670/// function.
4671Sema::ExprResult
4672Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4673                                SourceLocation LParenLoc, Expr **Args,
4674                                unsigned NumArgs, SourceLocation *CommaLocs,
4675                                SourceLocation RParenLoc) {
4676  // Dig out the member expression. This holds both the object
4677  // argument and the member function we're referring to.
4678  MemberExpr *MemExpr = 0;
4679  if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4680    MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4681  else
4682    MemExpr = dyn_cast<MemberExpr>(MemExprE);
4683  assert(MemExpr && "Building member call without member expression");
4684
4685  // Extract the object argument.
4686  Expr *ObjectArg = MemExpr->getBase();
4687
4688  CXXMethodDecl *Method = 0;
4689  if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4690      isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
4691    // Add overload candidates
4692    OverloadCandidateSet CandidateSet;
4693    DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
4694
4695    for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4696         Func != FuncEnd; ++Func) {
4697      if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
4698        AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
4699                           /*SuppressUserConversions=*/false);
4700      else
4701        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4702                                   MemExpr->hasExplicitTemplateArgumentList(),
4703                                   MemExpr->getTemplateArgs(),
4704                                   MemExpr->getNumTemplateArgs(),
4705                                   ObjectArg, Args, NumArgs,
4706                                   CandidateSet,
4707                                   /*SuppressUsedConversions=*/false);
4708    }
4709
4710    OverloadCandidateSet::iterator Best;
4711    switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
4712    case OR_Success:
4713      Method = cast<CXXMethodDecl>(Best->Function);
4714      break;
4715
4716    case OR_No_Viable_Function:
4717      Diag(MemExpr->getSourceRange().getBegin(),
4718           diag::err_ovl_no_viable_member_function_in_call)
4719        << DeclName << MemExprE->getSourceRange();
4720      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4721      // FIXME: Leaking incoming expressions!
4722      return true;
4723
4724    case OR_Ambiguous:
4725      Diag(MemExpr->getSourceRange().getBegin(),
4726           diag::err_ovl_ambiguous_member_call)
4727        << DeclName << MemExprE->getSourceRange();
4728      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4729      // FIXME: Leaking incoming expressions!
4730      return true;
4731
4732    case OR_Deleted:
4733      Diag(MemExpr->getSourceRange().getBegin(),
4734           diag::err_ovl_deleted_member_call)
4735        << Best->Function->isDeleted()
4736        << DeclName << MemExprE->getSourceRange();
4737      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4738      // FIXME: Leaking incoming expressions!
4739      return true;
4740    }
4741
4742    FixOverloadedFunctionReference(MemExpr, Method);
4743  } else {
4744    Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4745  }
4746
4747  assert(Method && "Member call to something that isn't a method?");
4748  ExprOwningPtr<CXXMemberCallExpr>
4749    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
4750                                                  NumArgs,
4751                                  Method->getResultType().getNonReferenceType(),
4752                                  RParenLoc));
4753
4754  // Convert the object argument (for a non-static member function call).
4755  if (!Method->isStatic() &&
4756      PerformObjectArgumentInitialization(ObjectArg, Method))
4757    return true;
4758  MemExpr->setBase(ObjectArg);
4759
4760  // Convert the rest of the arguments
4761  const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
4762  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
4763                              RParenLoc))
4764    return true;
4765
4766  if (CheckFunctionCall(Method, TheCall.get()))
4767    return true;
4768
4769  return MaybeBindToTemporary(TheCall.release()).release();
4770}
4771
4772/// BuildCallToObjectOfClassType - Build a call to an object of class
4773/// type (C++ [over.call.object]), which can end up invoking an
4774/// overloaded function call operator (@c operator()) or performing a
4775/// user-defined conversion on the object argument.
4776Sema::ExprResult
4777Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
4778                                   SourceLocation LParenLoc,
4779                                   Expr **Args, unsigned NumArgs,
4780                                   SourceLocation *CommaLocs,
4781                                   SourceLocation RParenLoc) {
4782  assert(Object->getType()->isRecordType() && "Requires object type argument");
4783  const RecordType *Record = Object->getType()->getAs<RecordType>();
4784
4785  // C++ [over.call.object]p1:
4786  //  If the primary-expression E in the function call syntax
4787  //  evaluates to a class object of type "cv T", then the set of
4788  //  candidate functions includes at least the function call
4789  //  operators of T. The function call operators of T are obtained by
4790  //  ordinary lookup of the name operator() in the context of
4791  //  (E).operator().
4792  OverloadCandidateSet CandidateSet;
4793  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
4794  DeclContext::lookup_const_iterator Oper, OperEnd;
4795  for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
4796       Oper != OperEnd; ++Oper)
4797    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
4798                       CandidateSet, /*SuppressUserConversions=*/false);
4799
4800  // C++ [over.call.object]p2:
4801  //   In addition, for each conversion function declared in T of the
4802  //   form
4803  //
4804  //        operator conversion-type-id () cv-qualifier;
4805  //
4806  //   where cv-qualifier is the same cv-qualification as, or a
4807  //   greater cv-qualification than, cv, and where conversion-type-id
4808  //   denotes the type "pointer to function of (P1,...,Pn) returning
4809  //   R", or the type "reference to pointer to function of
4810  //   (P1,...,Pn) returning R", or the type "reference to function
4811  //   of (P1,...,Pn) returning R", a surrogate call function [...]
4812  //   is also considered as a candidate function. Similarly,
4813  //   surrogate call functions are added to the set of candidate
4814  //   functions for each conversion function declared in an
4815  //   accessible base class provided the function is not hidden
4816  //   within T by another intervening declaration.
4817
4818  if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4819    // FIXME: Look in base classes for more conversion operators!
4820    OverloadedFunctionDecl *Conversions
4821      = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
4822    for (OverloadedFunctionDecl::function_iterator
4823           Func = Conversions->function_begin(),
4824           FuncEnd = Conversions->function_end();
4825         Func != FuncEnd; ++Func) {
4826      CXXConversionDecl *Conv;
4827      FunctionTemplateDecl *ConvTemplate;
4828      GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
4829
4830      // Skip over templated conversion functions; they aren't
4831      // surrogates.
4832      if (ConvTemplate)
4833        continue;
4834
4835      // Strip the reference type (if any) and then the pointer type (if
4836      // any) to get down to what might be a function type.
4837      QualType ConvType = Conv->getConversionType().getNonReferenceType();
4838      if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4839        ConvType = ConvPtrType->getPointeeType();
4840
4841      if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
4842        AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4843    }
4844  }
4845
4846  // Perform overload resolution.
4847  OverloadCandidateSet::iterator Best;
4848  switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
4849  case OR_Success:
4850    // Overload resolution succeeded; we'll build the appropriate call
4851    // below.
4852    break;
4853
4854  case OR_No_Viable_Function:
4855    Diag(Object->getSourceRange().getBegin(),
4856         diag::err_ovl_no_viable_object_call)
4857      << Object->getType() << Object->getSourceRange();
4858    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4859    break;
4860
4861  case OR_Ambiguous:
4862    Diag(Object->getSourceRange().getBegin(),
4863         diag::err_ovl_ambiguous_object_call)
4864      << Object->getType() << Object->getSourceRange();
4865    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4866    break;
4867
4868  case OR_Deleted:
4869    Diag(Object->getSourceRange().getBegin(),
4870         diag::err_ovl_deleted_object_call)
4871      << Best->Function->isDeleted()
4872      << Object->getType() << Object->getSourceRange();
4873    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4874    break;
4875  }
4876
4877  if (Best == CandidateSet.end()) {
4878    // We had an error; delete all of the subexpressions and return
4879    // the error.
4880    Object->Destroy(Context);
4881    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4882      Args[ArgIdx]->Destroy(Context);
4883    return true;
4884  }
4885
4886  if (Best->Function == 0) {
4887    // Since there is no function declaration, this is one of the
4888    // surrogate candidates. Dig out the conversion function.
4889    CXXConversionDecl *Conv
4890      = cast<CXXConversionDecl>(
4891                         Best->Conversions[0].UserDefined.ConversionFunction);
4892
4893    // We selected one of the surrogate functions that converts the
4894    // object parameter to a function pointer. Perform the conversion
4895    // on the object argument, then let ActOnCallExpr finish the job.
4896
4897    // Create an implicit member expr to refer to the conversion operator.
4898    MemberExpr *ME =
4899      new (Context) MemberExpr(Object, /*IsArrow=*/false, Conv,
4900                               SourceLocation(), Conv->getType());
4901    QualType ResultType = Conv->getConversionType().getNonReferenceType();
4902    CXXMemberCallExpr *CE =
4903      new (Context) CXXMemberCallExpr(Context, ME, 0, 0,
4904                                      ResultType,
4905                                      SourceLocation());
4906
4907    return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
4908                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4909                         CommaLocs, RParenLoc).release();
4910  }
4911
4912  // We found an overloaded operator(). Build a CXXOperatorCallExpr
4913  // that calls this method, using Object for the implicit object
4914  // parameter and passing along the remaining arguments.
4915  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
4916  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
4917
4918  unsigned NumArgsInProto = Proto->getNumArgs();
4919  unsigned NumArgsToCheck = NumArgs;
4920
4921  // Build the full argument list for the method call (the
4922  // implicit object parameter is placed at the beginning of the
4923  // list).
4924  Expr **MethodArgs;
4925  if (NumArgs < NumArgsInProto) {
4926    NumArgsToCheck = NumArgsInProto;
4927    MethodArgs = new Expr*[NumArgsInProto + 1];
4928  } else {
4929    MethodArgs = new Expr*[NumArgs + 1];
4930  }
4931  MethodArgs[0] = Object;
4932  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4933    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
4934
4935  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
4936                                          SourceLocation());
4937  UsualUnaryConversions(NewFn);
4938
4939  // Once we've built TheCall, all of the expressions are properly
4940  // owned.
4941  QualType ResultTy = Method->getResultType().getNonReferenceType();
4942  ExprOwningPtr<CXXOperatorCallExpr>
4943    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
4944                                                    MethodArgs, NumArgs + 1,
4945                                                    ResultTy, RParenLoc));
4946  delete [] MethodArgs;
4947
4948  // We may have default arguments. If so, we need to allocate more
4949  // slots in the call for them.
4950  if (NumArgs < NumArgsInProto)
4951    TheCall->setNumArgs(Context, NumArgsInProto + 1);
4952  else if (NumArgs > NumArgsInProto)
4953    NumArgsToCheck = NumArgsInProto;
4954
4955  bool IsError = false;
4956
4957  // Initialize the implicit object parameter.
4958  IsError |= PerformObjectArgumentInitialization(Object, Method);
4959  TheCall->setArg(0, Object);
4960
4961
4962  // Check the argument types.
4963  for (unsigned i = 0; i != NumArgsToCheck; i++) {
4964    Expr *Arg;
4965    if (i < NumArgs) {
4966      Arg = Args[i];
4967
4968      // Pass the argument.
4969      QualType ProtoArgType = Proto->getArgType(i);
4970      IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
4971    } else {
4972      Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
4973    }
4974
4975    TheCall->setArg(i + 1, Arg);
4976  }
4977
4978  // If this is a variadic call, handle args passed through "...".
4979  if (Proto->isVariadic()) {
4980    // Promote the arguments (C99 6.5.2.2p7).
4981    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
4982      Expr *Arg = Args[i];
4983      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
4984      TheCall->setArg(i + 1, Arg);
4985    }
4986  }
4987
4988  if (IsError) return true;
4989
4990  if (CheckFunctionCall(Method, TheCall.get()))
4991    return true;
4992
4993  return MaybeBindToTemporary(TheCall.release()).release();
4994}
4995
4996/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
4997///  (if one exists), where @c Base is an expression of class type and
4998/// @c Member is the name of the member we're trying to find.
4999Sema::OwningExprResult
5000Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5001  Expr *Base = static_cast<Expr *>(BaseIn.get());
5002  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
5003
5004  // C++ [over.ref]p1:
5005  //
5006  //   [...] An expression x->m is interpreted as (x.operator->())->m
5007  //   for a class object x of type T if T::operator->() exists and if
5008  //   the operator is selected as the best match function by the
5009  //   overload resolution mechanism (13.3).
5010  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5011  OverloadCandidateSet CandidateSet;
5012  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
5013
5014  LookupResult R = LookupQualifiedName(BaseRecord->getDecl(), OpName,
5015                                       LookupOrdinaryName);
5016
5017  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5018       Oper != OperEnd; ++Oper)
5019    AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
5020                       /*SuppressUserConversions=*/false);
5021
5022  // Perform overload resolution.
5023  OverloadCandidateSet::iterator Best;
5024  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5025  case OR_Success:
5026    // Overload resolution succeeded; we'll build the call below.
5027    break;
5028
5029  case OR_No_Viable_Function:
5030    if (CandidateSet.empty())
5031      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5032        << Base->getType() << Base->getSourceRange();
5033    else
5034      Diag(OpLoc, diag::err_ovl_no_viable_oper)
5035        << "operator->" << Base->getSourceRange();
5036    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5037    return ExprError();
5038
5039  case OR_Ambiguous:
5040    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5041      << "->" << Base->getSourceRange();
5042    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5043    return ExprError();
5044
5045  case OR_Deleted:
5046    Diag(OpLoc,  diag::err_ovl_deleted_oper)
5047      << Best->Function->isDeleted()
5048      << "->" << Base->getSourceRange();
5049    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5050    return ExprError();
5051  }
5052
5053  // Convert the object parameter.
5054  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5055  if (PerformObjectArgumentInitialization(Base, Method))
5056    return ExprError();
5057
5058  // No concerns about early exits now.
5059  BaseIn.release();
5060
5061  // Build the operator call.
5062  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5063                                           SourceLocation());
5064  UsualUnaryConversions(FnExpr);
5065  Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
5066                                 Method->getResultType().getNonReferenceType(),
5067                                 OpLoc);
5068  return Owned(Base);
5069}
5070
5071/// FixOverloadedFunctionReference - E is an expression that refers to
5072/// a C++ overloaded function (possibly with some parentheses and
5073/// perhaps a '&' around it). We have resolved the overloaded function
5074/// to the function declaration Fn, so patch up the expression E to
5075/// refer (possibly indirectly) to Fn.
5076void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5077  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5078    FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5079    E->setType(PE->getSubExpr()->getType());
5080  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
5081    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
5082           "Can only take the address of an overloaded function");
5083    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5084      if (Method->isStatic()) {
5085        // Do nothing: static member functions aren't any different
5086        // from non-member functions.
5087      } else if (QualifiedDeclRefExpr *DRE
5088                 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
5089        // We have taken the address of a pointer to member
5090        // function. Perform the computation here so that we get the
5091        // appropriate pointer to member type.
5092        DRE->setDecl(Fn);
5093        DRE->setType(Fn->getType());
5094        QualType ClassType
5095          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5096        E->setType(Context.getMemberPointerType(Fn->getType(),
5097                                                ClassType.getTypePtr()));
5098        return;
5099      }
5100    }
5101    FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5102    E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
5103  } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
5104    assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
5105            isa<FunctionTemplateDecl>(DR->getDecl())) &&
5106           "Expected overloaded function or function template");
5107    DR->setDecl(Fn);
5108    E->setType(Fn->getType());
5109  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5110    MemExpr->setMemberDecl(Fn);
5111    E->setType(Fn->getType());
5112  } else {
5113    assert(false && "Invalid reference to overloaded function");
5114  }
5115}
5116
5117} // end namespace clang
5118