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