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