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