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