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