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