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