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