SemaOverload.cpp revision 208600
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 "SemaInit.h"
17#include "clang/Basic/Diagnostic.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/AST/ASTContext.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprCXX.h"
23#include "clang/AST/TypeOrdering.h"
24#include "clang/Basic/PartialDiagnostic.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/STLExtras.h"
27#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
33ImplicitConversionCategory
34GetConversionCategory(ImplicitConversionKind Kind) {
35  static const ImplicitConversionCategory
36    Category[(int)ICK_Num_Conversion_Kinds] = {
37    ICC_Identity,
38    ICC_Lvalue_Transformation,
39    ICC_Lvalue_Transformation,
40    ICC_Lvalue_Transformation,
41    ICC_Identity,
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    ICC_Conversion,
57    ICC_Conversion
58  };
59  return Category[(int)Kind];
60}
61
62/// GetConversionRank - Retrieve the implicit conversion rank
63/// corresponding to the given implicit conversion kind.
64ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
65  static const ImplicitConversionRank
66    Rank[(int)ICK_Num_Conversion_Kinds] = {
67    ICR_Exact_Match,
68    ICR_Exact_Match,
69    ICR_Exact_Match,
70    ICR_Exact_Match,
71    ICR_Exact_Match,
72    ICR_Exact_Match,
73    ICR_Promotion,
74    ICR_Promotion,
75    ICR_Promotion,
76    ICR_Conversion,
77    ICR_Conversion,
78    ICR_Conversion,
79    ICR_Conversion,
80    ICR_Conversion,
81    ICR_Conversion,
82    ICR_Conversion,
83    ICR_Conversion,
84    ICR_Conversion,
85    ICR_Conversion,
86    ICR_Conversion,
87    ICR_Complex_Real_Conversion
88  };
89  return Rank[(int)Kind];
90}
91
92/// GetImplicitConversionName - Return the name of this kind of
93/// implicit conversion.
94const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
95  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
96    "No conversion",
97    "Lvalue-to-rvalue",
98    "Array-to-pointer",
99    "Function-to-pointer",
100    "Noreturn adjustment",
101    "Qualification",
102    "Integral promotion",
103    "Floating point promotion",
104    "Complex promotion",
105    "Integral conversion",
106    "Floating conversion",
107    "Complex conversion",
108    "Floating-integral conversion",
109    "Pointer conversion",
110    "Pointer-to-member conversion",
111    "Boolean conversion",
112    "Compatible-types conversion",
113    "Derived-to-base conversion",
114    "Vector conversion",
115    "Vector splat",
116    "Complex-real conversion"
117  };
118  return Name[Kind];
119}
120
121/// StandardConversionSequence - Set the standard conversion
122/// sequence to the identity conversion.
123void StandardConversionSequence::setAsIdentityConversion() {
124  First = ICK_Identity;
125  Second = ICK_Identity;
126  Third = ICK_Identity;
127  DeprecatedStringLiteralToCharPtr = false;
128  ReferenceBinding = false;
129  DirectBinding = false;
130  RRefBinding = false;
131  CopyConstructor = 0;
132}
133
134/// getRank - Retrieve the rank of this standard conversion sequence
135/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
136/// implicit conversions.
137ImplicitConversionRank StandardConversionSequence::getRank() const {
138  ImplicitConversionRank Rank = ICR_Exact_Match;
139  if  (GetConversionRank(First) > Rank)
140    Rank = GetConversionRank(First);
141  if  (GetConversionRank(Second) > Rank)
142    Rank = GetConversionRank(Second);
143  if  (GetConversionRank(Third) > Rank)
144    Rank = GetConversionRank(Third);
145  return Rank;
146}
147
148/// isPointerConversionToBool - Determines whether this conversion is
149/// a conversion of a pointer or pointer-to-member to bool. This is
150/// used as part of the ranking of standard conversion sequences
151/// (C++ 13.3.3.2p4).
152bool StandardConversionSequence::isPointerConversionToBool() const {
153  // Note that FromType has not necessarily been transformed by the
154  // array-to-pointer or function-to-pointer implicit conversions, so
155  // check for their presence as well as checking whether FromType is
156  // a pointer.
157  if (getToType(1)->isBooleanType() &&
158      (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
159       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
160    return true;
161
162  return false;
163}
164
165/// isPointerConversionToVoidPointer - Determines whether this
166/// conversion is a conversion of a pointer to a void pointer. This is
167/// used as part of the ranking of standard conversion sequences (C++
168/// 13.3.3.2p4).
169bool
170StandardConversionSequence::
171isPointerConversionToVoidPointer(ASTContext& Context) const {
172  QualType FromType = getFromType();
173  QualType ToType = getToType(1);
174
175  // Note that FromType has not necessarily been transformed by the
176  // array-to-pointer implicit conversion, so check for its presence
177  // and redo the conversion to get a pointer.
178  if (First == ICK_Array_To_Pointer)
179    FromType = Context.getArrayDecayedType(FromType);
180
181  if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
182    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
183      return ToPtrType->getPointeeType()->isVoidType();
184
185  return false;
186}
187
188/// DebugPrint - Print this standard conversion sequence to standard
189/// error. Useful for debugging overloading issues.
190void StandardConversionSequence::DebugPrint() const {
191  llvm::raw_ostream &OS = llvm::errs();
192  bool PrintedSomething = false;
193  if (First != ICK_Identity) {
194    OS << GetImplicitConversionName(First);
195    PrintedSomething = true;
196  }
197
198  if (Second != ICK_Identity) {
199    if (PrintedSomething) {
200      OS << " -> ";
201    }
202    OS << GetImplicitConversionName(Second);
203
204    if (CopyConstructor) {
205      OS << " (by copy constructor)";
206    } else if (DirectBinding) {
207      OS << " (direct reference binding)";
208    } else if (ReferenceBinding) {
209      OS << " (reference binding)";
210    }
211    PrintedSomething = true;
212  }
213
214  if (Third != ICK_Identity) {
215    if (PrintedSomething) {
216      OS << " -> ";
217    }
218    OS << GetImplicitConversionName(Third);
219    PrintedSomething = true;
220  }
221
222  if (!PrintedSomething) {
223    OS << "No conversions required";
224  }
225}
226
227/// DebugPrint - Print this user-defined conversion sequence to standard
228/// error. Useful for debugging overloading issues.
229void UserDefinedConversionSequence::DebugPrint() const {
230  llvm::raw_ostream &OS = llvm::errs();
231  if (Before.First || Before.Second || Before.Third) {
232    Before.DebugPrint();
233    OS << " -> ";
234  }
235  OS << '\'' << ConversionFunction << '\'';
236  if (After.First || After.Second || After.Third) {
237    OS << " -> ";
238    After.DebugPrint();
239  }
240}
241
242/// DebugPrint - Print this implicit conversion sequence to standard
243/// error. Useful for debugging overloading issues.
244void ImplicitConversionSequence::DebugPrint() const {
245  llvm::raw_ostream &OS = llvm::errs();
246  switch (ConversionKind) {
247  case StandardConversion:
248    OS << "Standard conversion: ";
249    Standard.DebugPrint();
250    break;
251  case UserDefinedConversion:
252    OS << "User-defined conversion: ";
253    UserDefined.DebugPrint();
254    break;
255  case EllipsisConversion:
256    OS << "Ellipsis conversion";
257    break;
258  case AmbiguousConversion:
259    OS << "Ambiguous conversion";
260    break;
261  case BadConversion:
262    OS << "Bad conversion";
263    break;
264  }
265
266  OS << "\n";
267}
268
269void AmbiguousConversionSequence::construct() {
270  new (&conversions()) ConversionSet();
271}
272
273void AmbiguousConversionSequence::destruct() {
274  conversions().~ConversionSet();
275}
276
277void
278AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
279  FromTypePtr = O.FromTypePtr;
280  ToTypePtr = O.ToTypePtr;
281  new (&conversions()) ConversionSet(O.conversions());
282}
283
284namespace {
285  // Structure used by OverloadCandidate::DeductionFailureInfo to store
286  // template parameter and template argument information.
287  struct DFIParamWithArguments {
288    TemplateParameter Param;
289    TemplateArgument FirstArg;
290    TemplateArgument SecondArg;
291  };
292}
293
294/// \brief Convert from Sema's representation of template deduction information
295/// to the form used in overload-candidate information.
296OverloadCandidate::DeductionFailureInfo
297static MakeDeductionFailureInfo(ASTContext &Context,
298                                Sema::TemplateDeductionResult TDK,
299                                Sema::TemplateDeductionInfo &Info) {
300  OverloadCandidate::DeductionFailureInfo Result;
301  Result.Result = static_cast<unsigned>(TDK);
302  Result.Data = 0;
303  switch (TDK) {
304  case Sema::TDK_Success:
305  case Sema::TDK_InstantiationDepth:
306  case Sema::TDK_TooManyArguments:
307  case Sema::TDK_TooFewArguments:
308    break;
309
310  case Sema::TDK_Incomplete:
311  case Sema::TDK_InvalidExplicitArguments:
312    Result.Data = Info.Param.getOpaqueValue();
313    break;
314
315  case Sema::TDK_Inconsistent:
316  case Sema::TDK_InconsistentQuals: {
317    // FIXME: Should allocate from normal heap so that we can free this later.
318    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
319    Saved->Param = Info.Param;
320    Saved->FirstArg = Info.FirstArg;
321    Saved->SecondArg = Info.SecondArg;
322    Result.Data = Saved;
323    break;
324  }
325
326  case Sema::TDK_SubstitutionFailure:
327    Result.Data = Info.take();
328    break;
329
330  case Sema::TDK_NonDeducedMismatch:
331  case Sema::TDK_FailedOverloadResolution:
332    break;
333  }
334
335  return Result;
336}
337
338void OverloadCandidate::DeductionFailureInfo::Destroy() {
339  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
340  case Sema::TDK_Success:
341  case Sema::TDK_InstantiationDepth:
342  case Sema::TDK_Incomplete:
343  case Sema::TDK_TooManyArguments:
344  case Sema::TDK_TooFewArguments:
345  case Sema::TDK_InvalidExplicitArguments:
346    break;
347
348  case Sema::TDK_Inconsistent:
349  case Sema::TDK_InconsistentQuals:
350    // FIXME: Destroy the data?
351    Data = 0;
352    break;
353
354  case Sema::TDK_SubstitutionFailure:
355    // FIXME: Destroy the template arugment list?
356    Data = 0;
357    break;
358
359  // Unhandled
360  case Sema::TDK_NonDeducedMismatch:
361  case Sema::TDK_FailedOverloadResolution:
362    break;
363  }
364}
365
366TemplateParameter
367OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
368  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
369  case Sema::TDK_Success:
370  case Sema::TDK_InstantiationDepth:
371  case Sema::TDK_TooManyArguments:
372  case Sema::TDK_TooFewArguments:
373  case Sema::TDK_SubstitutionFailure:
374    return TemplateParameter();
375
376  case Sema::TDK_Incomplete:
377  case Sema::TDK_InvalidExplicitArguments:
378    return TemplateParameter::getFromOpaqueValue(Data);
379
380  case Sema::TDK_Inconsistent:
381  case Sema::TDK_InconsistentQuals:
382    return static_cast<DFIParamWithArguments*>(Data)->Param;
383
384  // Unhandled
385  case Sema::TDK_NonDeducedMismatch:
386  case Sema::TDK_FailedOverloadResolution:
387    break;
388  }
389
390  return TemplateParameter();
391}
392
393TemplateArgumentList *
394OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
395  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
396    case Sema::TDK_Success:
397    case Sema::TDK_InstantiationDepth:
398    case Sema::TDK_TooManyArguments:
399    case Sema::TDK_TooFewArguments:
400    case Sema::TDK_Incomplete:
401    case Sema::TDK_InvalidExplicitArguments:
402    case Sema::TDK_Inconsistent:
403    case Sema::TDK_InconsistentQuals:
404      return 0;
405
406    case Sema::TDK_SubstitutionFailure:
407      return static_cast<TemplateArgumentList*>(Data);
408
409    // Unhandled
410    case Sema::TDK_NonDeducedMismatch:
411    case Sema::TDK_FailedOverloadResolution:
412      break;
413  }
414
415  return 0;
416}
417
418const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
419  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
420  case Sema::TDK_Success:
421  case Sema::TDK_InstantiationDepth:
422  case Sema::TDK_Incomplete:
423  case Sema::TDK_TooManyArguments:
424  case Sema::TDK_TooFewArguments:
425  case Sema::TDK_InvalidExplicitArguments:
426  case Sema::TDK_SubstitutionFailure:
427    return 0;
428
429  case Sema::TDK_Inconsistent:
430  case Sema::TDK_InconsistentQuals:
431    return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
432
433  // Unhandled
434  case Sema::TDK_NonDeducedMismatch:
435  case Sema::TDK_FailedOverloadResolution:
436    break;
437  }
438
439  return 0;
440}
441
442const TemplateArgument *
443OverloadCandidate::DeductionFailureInfo::getSecondArg() {
444  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
445  case Sema::TDK_Success:
446  case Sema::TDK_InstantiationDepth:
447  case Sema::TDK_Incomplete:
448  case Sema::TDK_TooManyArguments:
449  case Sema::TDK_TooFewArguments:
450  case Sema::TDK_InvalidExplicitArguments:
451  case Sema::TDK_SubstitutionFailure:
452    return 0;
453
454  case Sema::TDK_Inconsistent:
455  case Sema::TDK_InconsistentQuals:
456    return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
457
458  // Unhandled
459  case Sema::TDK_NonDeducedMismatch:
460  case Sema::TDK_FailedOverloadResolution:
461    break;
462  }
463
464  return 0;
465}
466
467void OverloadCandidateSet::clear() {
468  inherited::clear();
469  Functions.clear();
470}
471
472// IsOverload - Determine whether the given New declaration is an
473// overload of the declarations in Old. This routine returns false if
474// New and Old cannot be overloaded, e.g., if New has the same
475// signature as some function in Old (C++ 1.3.10) or if the Old
476// declarations aren't functions (or function templates) at all. When
477// it does return false, MatchedDecl will point to the decl that New
478// cannot be overloaded with.  This decl may be a UsingShadowDecl on
479// top of the underlying declaration.
480//
481// Example: Given the following input:
482//
483//   void f(int, float); // #1
484//   void f(int, int); // #2
485//   int f(int, int); // #3
486//
487// When we process #1, there is no previous declaration of "f",
488// so IsOverload will not be used.
489//
490// When we process #2, Old contains only the FunctionDecl for #1.  By
491// comparing the parameter types, we see that #1 and #2 are overloaded
492// (since they have different signatures), so this routine returns
493// false; MatchedDecl is unchanged.
494//
495// When we process #3, Old is an overload set containing #1 and #2. We
496// compare the signatures of #3 to #1 (they're overloaded, so we do
497// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
498// identical (return types of functions are not part of the
499// signature), IsOverload returns false and MatchedDecl will be set to
500// point to the FunctionDecl for #2.
501Sema::OverloadKind
502Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
503                    NamedDecl *&Match) {
504  for (LookupResult::iterator I = Old.begin(), E = Old.end();
505         I != E; ++I) {
506    NamedDecl *OldD = (*I)->getUnderlyingDecl();
507    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
508      if (!IsOverload(New, OldT->getTemplatedDecl())) {
509        Match = *I;
510        return Ovl_Match;
511      }
512    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
513      if (!IsOverload(New, OldF)) {
514        Match = *I;
515        return Ovl_Match;
516      }
517    } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
518      // We can overload with these, which can show up when doing
519      // redeclaration checks for UsingDecls.
520      assert(Old.getLookupKind() == LookupUsingDeclName);
521    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
522      // Optimistically assume that an unresolved using decl will
523      // overload; if it doesn't, we'll have to diagnose during
524      // template instantiation.
525    } else {
526      // (C++ 13p1):
527      //   Only function declarations can be overloaded; object and type
528      //   declarations cannot be overloaded.
529      Match = *I;
530      return Ovl_NonFunction;
531    }
532  }
533
534  return Ovl_Overload;
535}
536
537bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
538  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
539  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
540
541  // C++ [temp.fct]p2:
542  //   A function template can be overloaded with other function templates
543  //   and with normal (non-template) functions.
544  if ((OldTemplate == 0) != (NewTemplate == 0))
545    return true;
546
547  // Is the function New an overload of the function Old?
548  QualType OldQType = Context.getCanonicalType(Old->getType());
549  QualType NewQType = Context.getCanonicalType(New->getType());
550
551  // Compare the signatures (C++ 1.3.10) of the two functions to
552  // determine whether they are overloads. If we find any mismatch
553  // in the signature, they are overloads.
554
555  // If either of these functions is a K&R-style function (no
556  // prototype), then we consider them to have matching signatures.
557  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
558      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
559    return false;
560
561  FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
562  FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
563
564  // The signature of a function includes the types of its
565  // parameters (C++ 1.3.10), which includes the presence or absence
566  // of the ellipsis; see C++ DR 357).
567  if (OldQType != NewQType &&
568      (OldType->getNumArgs() != NewType->getNumArgs() ||
569       OldType->isVariadic() != NewType->isVariadic() ||
570       !FunctionArgTypesAreEqual(OldType, NewType)))
571    return true;
572
573  // C++ [temp.over.link]p4:
574  //   The signature of a function template consists of its function
575  //   signature, its return type and its template parameter list. The names
576  //   of the template parameters are significant only for establishing the
577  //   relationship between the template parameters and the rest of the
578  //   signature.
579  //
580  // We check the return type and template parameter lists for function
581  // templates first; the remaining checks follow.
582  if (NewTemplate &&
583      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
584                                       OldTemplate->getTemplateParameters(),
585                                       false, TPL_TemplateMatch) ||
586       OldType->getResultType() != NewType->getResultType()))
587    return true;
588
589  // If the function is a class member, its signature includes the
590  // cv-qualifiers (if any) on the function itself.
591  //
592  // As part of this, also check whether one of the member functions
593  // is static, in which case they are not overloads (C++
594  // 13.1p2). While not part of the definition of the signature,
595  // this check is important to determine whether these functions
596  // can be overloaded.
597  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
598  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
599  if (OldMethod && NewMethod &&
600      !OldMethod->isStatic() && !NewMethod->isStatic() &&
601      OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
602    return true;
603
604  // The signatures match; this is not an overload.
605  return false;
606}
607
608/// TryImplicitConversion - Attempt to perform an implicit conversion
609/// from the given expression (Expr) to the given type (ToType). This
610/// function returns an implicit conversion sequence that can be used
611/// to perform the initialization. Given
612///
613///   void f(float f);
614///   void g(int i) { f(i); }
615///
616/// this routine would produce an implicit conversion sequence to
617/// describe the initialization of f from i, which will be a standard
618/// conversion sequence containing an lvalue-to-rvalue conversion (C++
619/// 4.1) followed by a floating-integral conversion (C++ 4.9).
620//
621/// Note that this routine only determines how the conversion can be
622/// performed; it does not actually perform the conversion. As such,
623/// it will not produce any diagnostics if no conversion is available,
624/// but will instead return an implicit conversion sequence of kind
625/// "BadConversion".
626///
627/// If @p SuppressUserConversions, then user-defined conversions are
628/// not permitted.
629/// If @p AllowExplicit, then explicit user-defined conversions are
630/// permitted.
631ImplicitConversionSequence
632Sema::TryImplicitConversion(Expr* From, QualType ToType,
633                            bool SuppressUserConversions,
634                            bool AllowExplicit,
635                            bool InOverloadResolution) {
636  ImplicitConversionSequence ICS;
637  if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
638    ICS.setStandard();
639    return ICS;
640  }
641
642  if (!getLangOptions().CPlusPlus) {
643    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
644    return ICS;
645  }
646
647  if (SuppressUserConversions) {
648    // C++ [over.ics.user]p4:
649    //   A conversion of an expression of class type to the same class
650    //   type is given Exact Match rank, and a conversion of an
651    //   expression of class type to a base class of that type is
652    //   given Conversion rank, in spite of the fact that a copy/move
653    //   constructor (i.e., a user-defined conversion function) is
654    //   called for those cases.
655    QualType FromType = From->getType();
656    if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
657        !(Context.hasSameUnqualifiedType(FromType, ToType) ||
658          IsDerivedFrom(FromType, ToType))) {
659      // We're not in the case above, so there is no conversion that
660      // we can perform.
661      ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
662      return ICS;
663    }
664
665    ICS.setStandard();
666    ICS.Standard.setAsIdentityConversion();
667    ICS.Standard.setFromType(FromType);
668    ICS.Standard.setAllToTypes(ToType);
669
670    // We don't actually check at this point whether there is a valid
671    // copy/move constructor, since overloading just assumes that it
672    // exists. When we actually perform initialization, we'll find the
673    // appropriate constructor to copy the returned object, if needed.
674    ICS.Standard.CopyConstructor = 0;
675
676    // Determine whether this is considered a derived-to-base conversion.
677    if (!Context.hasSameUnqualifiedType(FromType, ToType))
678      ICS.Standard.Second = ICK_Derived_To_Base;
679
680    return ICS;
681  }
682
683  // Attempt user-defined conversion.
684  OverloadCandidateSet Conversions(From->getExprLoc());
685  OverloadingResult UserDefResult
686    = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
687                              AllowExplicit);
688
689  if (UserDefResult == OR_Success) {
690    ICS.setUserDefined();
691    // C++ [over.ics.user]p4:
692    //   A conversion of an expression of class type to the same class
693    //   type is given Exact Match rank, and a conversion of an
694    //   expression of class type to a base class of that type is
695    //   given Conversion rank, in spite of the fact that a copy
696    //   constructor (i.e., a user-defined conversion function) is
697    //   called for those cases.
698    if (CXXConstructorDecl *Constructor
699          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
700      QualType FromCanon
701        = Context.getCanonicalType(From->getType().getUnqualifiedType());
702      QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
703      if (Constructor->isCopyConstructor() &&
704          (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
705        // Turn this into a "standard" conversion sequence, so that it
706        // gets ranked with standard conversion sequences.
707        ICS.setStandard();
708        ICS.Standard.setAsIdentityConversion();
709        ICS.Standard.setFromType(From->getType());
710        ICS.Standard.setAllToTypes(ToType);
711        ICS.Standard.CopyConstructor = Constructor;
712        if (ToCanon != FromCanon)
713          ICS.Standard.Second = ICK_Derived_To_Base;
714      }
715    }
716
717    // C++ [over.best.ics]p4:
718    //   However, when considering the argument of a user-defined
719    //   conversion function that is a candidate by 13.3.1.3 when
720    //   invoked for the copying of the temporary in the second step
721    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
722    //   13.3.1.6 in all cases, only standard conversion sequences and
723    //   ellipsis conversion sequences are allowed.
724    if (SuppressUserConversions && ICS.isUserDefined()) {
725      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
726    }
727  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
728    ICS.setAmbiguous();
729    ICS.Ambiguous.setFromType(From->getType());
730    ICS.Ambiguous.setToType(ToType);
731    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
732         Cand != Conversions.end(); ++Cand)
733      if (Cand->Viable)
734        ICS.Ambiguous.addConversion(Cand->Function);
735  } else {
736    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
737  }
738
739  return ICS;
740}
741
742/// PerformImplicitConversion - Perform an implicit conversion of the
743/// expression From to the type ToType. Returns true if there was an
744/// error, false otherwise. The expression From is replaced with the
745/// converted expression. Flavor is the kind of conversion we're
746/// performing, used in the error message. If @p AllowExplicit,
747/// explicit user-defined conversions are permitted.
748bool
749Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
750                                AssignmentAction Action, bool AllowExplicit) {
751  ImplicitConversionSequence ICS;
752  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
753}
754
755bool
756Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
757                                AssignmentAction Action, bool AllowExplicit,
758                                ImplicitConversionSequence& ICS) {
759  ICS = TryImplicitConversion(From, ToType,
760                              /*SuppressUserConversions=*/false,
761                              AllowExplicit,
762                              /*InOverloadResolution=*/false);
763  return PerformImplicitConversion(From, ToType, ICS, Action);
764}
765
766/// \brief Determine whether the conversion from FromType to ToType is a valid
767/// conversion that strips "noreturn" off the nested function type.
768static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
769                                 QualType ToType, QualType &ResultTy) {
770  if (Context.hasSameUnqualifiedType(FromType, ToType))
771    return false;
772
773  // Strip the noreturn off the type we're converting from; noreturn can
774  // safely be removed.
775  FromType = Context.getNoReturnType(FromType, false);
776  if (!Context.hasSameUnqualifiedType(FromType, ToType))
777    return false;
778
779  ResultTy = FromType;
780  return true;
781}
782
783/// \brief Determine whether the conversion from FromType to ToType is a valid
784/// vector conversion.
785///
786/// \param ICK Will be set to the vector conversion kind, if this is a vector
787/// conversion.
788static bool IsVectorConversion(ASTContext &Context, QualType FromType,
789                               QualType ToType, ImplicitConversionKind &ICK) {
790  // We need at least one of these types to be a vector type to have a vector
791  // conversion.
792  if (!ToType->isVectorType() && !FromType->isVectorType())
793    return false;
794
795  // Identical types require no conversions.
796  if (Context.hasSameUnqualifiedType(FromType, ToType))
797    return false;
798
799  // There are no conversions between extended vector types, only identity.
800  if (ToType->isExtVectorType()) {
801    // There are no conversions between extended vector types other than the
802    // identity conversion.
803    if (FromType->isExtVectorType())
804      return false;
805
806    // Vector splat from any arithmetic type to a vector.
807    if (!FromType->isVectorType() && FromType->isArithmeticType()) {
808      ICK = ICK_Vector_Splat;
809      return true;
810    }
811  }
812
813  // If lax vector conversions are permitted and the vector types are of the
814  // same size, we can perform the conversion.
815  if (Context.getLangOptions().LaxVectorConversions &&
816      FromType->isVectorType() && ToType->isVectorType() &&
817      Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
818    ICK = ICK_Vector_Conversion;
819    return true;
820  }
821
822  return false;
823}
824
825/// IsStandardConversion - Determines whether there is a standard
826/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
827/// expression From to the type ToType. Standard conversion sequences
828/// only consider non-class types; for conversions that involve class
829/// types, use TryImplicitConversion. If a conversion exists, SCS will
830/// contain the standard conversion sequence required to perform this
831/// conversion and this routine will return true. Otherwise, this
832/// routine will return false and the value of SCS is unspecified.
833bool
834Sema::IsStandardConversion(Expr* From, QualType ToType,
835                           bool InOverloadResolution,
836                           StandardConversionSequence &SCS) {
837  QualType FromType = From->getType();
838
839  // Standard conversions (C++ [conv])
840  SCS.setAsIdentityConversion();
841  SCS.DeprecatedStringLiteralToCharPtr = false;
842  SCS.IncompatibleObjC = false;
843  SCS.setFromType(FromType);
844  SCS.CopyConstructor = 0;
845
846  // There are no standard conversions for class types in C++, so
847  // abort early. When overloading in C, however, we do permit
848  if (FromType->isRecordType() || ToType->isRecordType()) {
849    if (getLangOptions().CPlusPlus)
850      return false;
851
852    // When we're overloading in C, we allow, as standard conversions,
853  }
854
855  // The first conversion can be an lvalue-to-rvalue conversion,
856  // array-to-pointer conversion, or function-to-pointer conversion
857  // (C++ 4p1).
858
859  if (FromType == Context.OverloadTy) {
860    DeclAccessPair AccessPair;
861    if (FunctionDecl *Fn
862          = ResolveAddressOfOverloadedFunction(From, ToType, false,
863                                               AccessPair)) {
864      // We were able to resolve the address of the overloaded function,
865      // so we can convert to the type of that function.
866      FromType = Fn->getType();
867      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
868        if (!Method->isStatic()) {
869          Type *ClassType
870            = Context.getTypeDeclType(Method->getParent()).getTypePtr();
871          FromType = Context.getMemberPointerType(FromType, ClassType);
872        }
873      }
874
875      // If the "from" expression takes the address of the overloaded
876      // function, update the type of the resulting expression accordingly.
877      if (FromType->getAs<FunctionType>())
878        if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
879          if (UnOp->getOpcode() == UnaryOperator::AddrOf)
880            FromType = Context.getPointerType(FromType);
881
882      // Check that we've computed the proper type after overload resolution.
883      assert(Context.hasSameType(FromType,
884              FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
885    } else {
886      return false;
887    }
888  }
889  // Lvalue-to-rvalue conversion (C++ 4.1):
890  //   An lvalue (3.10) of a non-function, non-array type T can be
891  //   converted to an rvalue.
892  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
893  if (argIsLvalue == Expr::LV_Valid &&
894      !FromType->isFunctionType() && !FromType->isArrayType() &&
895      Context.getCanonicalType(FromType) != Context.OverloadTy) {
896    SCS.First = ICK_Lvalue_To_Rvalue;
897
898    // If T is a non-class type, the type of the rvalue is the
899    // cv-unqualified version of T. Otherwise, the type of the rvalue
900    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
901    // just strip the qualifiers because they don't matter.
902    FromType = FromType.getUnqualifiedType();
903  } else if (FromType->isArrayType()) {
904    // Array-to-pointer conversion (C++ 4.2)
905    SCS.First = ICK_Array_To_Pointer;
906
907    // An lvalue or rvalue of type "array of N T" or "array of unknown
908    // bound of T" can be converted to an rvalue of type "pointer to
909    // T" (C++ 4.2p1).
910    FromType = Context.getArrayDecayedType(FromType);
911
912    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
913      // This conversion is deprecated. (C++ D.4).
914      SCS.DeprecatedStringLiteralToCharPtr = true;
915
916      // For the purpose of ranking in overload resolution
917      // (13.3.3.1.1), this conversion is considered an
918      // array-to-pointer conversion followed by a qualification
919      // conversion (4.4). (C++ 4.2p2)
920      SCS.Second = ICK_Identity;
921      SCS.Third = ICK_Qualification;
922      SCS.setAllToTypes(FromType);
923      return true;
924    }
925  } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
926    // Function-to-pointer conversion (C++ 4.3).
927    SCS.First = ICK_Function_To_Pointer;
928
929    // An lvalue of function type T can be converted to an rvalue of
930    // type "pointer to T." The result is a pointer to the
931    // function. (C++ 4.3p1).
932    FromType = Context.getPointerType(FromType);
933  } else {
934    // We don't require any conversions for the first step.
935    SCS.First = ICK_Identity;
936  }
937  SCS.setToType(0, FromType);
938
939  // The second conversion can be an integral promotion, floating
940  // point promotion, integral conversion, floating point conversion,
941  // floating-integral conversion, pointer conversion,
942  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
943  // For overloading in C, this can also be a "compatible-type"
944  // conversion.
945  bool IncompatibleObjC = false;
946  ImplicitConversionKind SecondICK = ICK_Identity;
947  if (Context.hasSameUnqualifiedType(FromType, ToType)) {
948    // The unqualified versions of the types are the same: there's no
949    // conversion to do.
950    SCS.Second = ICK_Identity;
951  } else if (IsIntegralPromotion(From, FromType, ToType)) {
952    // Integral promotion (C++ 4.5).
953    SCS.Second = ICK_Integral_Promotion;
954    FromType = ToType.getUnqualifiedType();
955  } else if (IsFloatingPointPromotion(FromType, ToType)) {
956    // Floating point promotion (C++ 4.6).
957    SCS.Second = ICK_Floating_Promotion;
958    FromType = ToType.getUnqualifiedType();
959  } else if (IsComplexPromotion(FromType, ToType)) {
960    // Complex promotion (Clang extension)
961    SCS.Second = ICK_Complex_Promotion;
962    FromType = ToType.getUnqualifiedType();
963  } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
964           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
965    // Integral conversions (C++ 4.7).
966    SCS.Second = ICK_Integral_Conversion;
967    FromType = ToType.getUnqualifiedType();
968  } else if (FromType->isComplexType() && ToType->isComplexType()) {
969    // Complex conversions (C99 6.3.1.6)
970    SCS.Second = ICK_Complex_Conversion;
971    FromType = ToType.getUnqualifiedType();
972  } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
973             (ToType->isComplexType() && FromType->isArithmeticType())) {
974    // Complex-real conversions (C99 6.3.1.7)
975    SCS.Second = ICK_Complex_Real;
976    FromType = ToType.getUnqualifiedType();
977  } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
978    // Floating point conversions (C++ 4.8).
979    SCS.Second = ICK_Floating_Conversion;
980    FromType = ToType.getUnqualifiedType();
981  } else if ((FromType->isFloatingType() &&
982              ToType->isIntegralType() && (!ToType->isBooleanType() &&
983                                           !ToType->isEnumeralType())) ||
984             ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
985              ToType->isFloatingType())) {
986    // Floating-integral conversions (C++ 4.9).
987    SCS.Second = ICK_Floating_Integral;
988    FromType = ToType.getUnqualifiedType();
989  } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
990                                 FromType, IncompatibleObjC)) {
991    // Pointer conversions (C++ 4.10).
992    SCS.Second = ICK_Pointer_Conversion;
993    SCS.IncompatibleObjC = IncompatibleObjC;
994  } else if (IsMemberPointerConversion(From, FromType, ToType,
995                                       InOverloadResolution, FromType)) {
996    // Pointer to member conversions (4.11).
997    SCS.Second = ICK_Pointer_Member;
998  } else if (ToType->isBooleanType() &&
999             (FromType->isArithmeticType() ||
1000              FromType->isEnumeralType() ||
1001              FromType->isAnyPointerType() ||
1002              FromType->isBlockPointerType() ||
1003              FromType->isMemberPointerType() ||
1004              FromType->isNullPtrType())) {
1005    // Boolean conversions (C++ 4.12).
1006    SCS.Second = ICK_Boolean_Conversion;
1007    FromType = Context.BoolTy;
1008  } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1009    SCS.Second = SecondICK;
1010    FromType = ToType.getUnqualifiedType();
1011  } else if (!getLangOptions().CPlusPlus &&
1012             Context.typesAreCompatible(ToType, FromType)) {
1013    // Compatible conversions (Clang extension for C function overloading)
1014    SCS.Second = ICK_Compatible_Conversion;
1015    FromType = ToType.getUnqualifiedType();
1016  } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1017    // Treat a conversion that strips "noreturn" as an identity conversion.
1018    SCS.Second = ICK_NoReturn_Adjustment;
1019  } else {
1020    // No second conversion required.
1021    SCS.Second = ICK_Identity;
1022  }
1023  SCS.setToType(1, FromType);
1024
1025  QualType CanonFrom;
1026  QualType CanonTo;
1027  // The third conversion can be a qualification conversion (C++ 4p1).
1028  if (IsQualificationConversion(FromType, ToType)) {
1029    SCS.Third = ICK_Qualification;
1030    FromType = ToType;
1031    CanonFrom = Context.getCanonicalType(FromType);
1032    CanonTo = Context.getCanonicalType(ToType);
1033  } else {
1034    // No conversion required
1035    SCS.Third = ICK_Identity;
1036
1037    // C++ [over.best.ics]p6:
1038    //   [...] Any difference in top-level cv-qualification is
1039    //   subsumed by the initialization itself and does not constitute
1040    //   a conversion. [...]
1041    CanonFrom = Context.getCanonicalType(FromType);
1042    CanonTo = Context.getCanonicalType(ToType);
1043    if (CanonFrom.getLocalUnqualifiedType()
1044                                       == CanonTo.getLocalUnqualifiedType() &&
1045        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1046         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
1047      FromType = ToType;
1048      CanonFrom = CanonTo;
1049    }
1050  }
1051  SCS.setToType(2, FromType);
1052
1053  // If we have not converted the argument type to the parameter type,
1054  // this is a bad conversion sequence.
1055  if (CanonFrom != CanonTo)
1056    return false;
1057
1058  return true;
1059}
1060
1061/// IsIntegralPromotion - Determines whether the conversion from the
1062/// expression From (whose potentially-adjusted type is FromType) to
1063/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1064/// sets PromotedType to the promoted type.
1065bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1066  const BuiltinType *To = ToType->getAs<BuiltinType>();
1067  // All integers are built-in.
1068  if (!To) {
1069    return false;
1070  }
1071
1072  // An rvalue of type char, signed char, unsigned char, short int, or
1073  // unsigned short int can be converted to an rvalue of type int if
1074  // int can represent all the values of the source type; otherwise,
1075  // the source rvalue can be converted to an rvalue of type unsigned
1076  // int (C++ 4.5p1).
1077  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1078      !FromType->isEnumeralType()) {
1079    if (// We can promote any signed, promotable integer type to an int
1080        (FromType->isSignedIntegerType() ||
1081         // We can promote any unsigned integer type whose size is
1082         // less than int to an int.
1083         (!FromType->isSignedIntegerType() &&
1084          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1085      return To->getKind() == BuiltinType::Int;
1086    }
1087
1088    return To->getKind() == BuiltinType::UInt;
1089  }
1090
1091  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1092  // can be converted to an rvalue of the first of the following types
1093  // that can represent all the values of its underlying type: int,
1094  // unsigned int, long, or unsigned long (C++ 4.5p2).
1095
1096  // We pre-calculate the promotion type for enum types.
1097  if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1098    if (ToType->isIntegerType())
1099      return Context.hasSameUnqualifiedType(ToType,
1100                                FromEnumType->getDecl()->getPromotionType());
1101
1102  if (FromType->isWideCharType() && ToType->isIntegerType()) {
1103    // Determine whether the type we're converting from is signed or
1104    // unsigned.
1105    bool FromIsSigned;
1106    uint64_t FromSize = Context.getTypeSize(FromType);
1107
1108    // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1109    FromIsSigned = true;
1110
1111    // The types we'll try to promote to, in the appropriate
1112    // order. Try each of these types.
1113    QualType PromoteTypes[6] = {
1114      Context.IntTy, Context.UnsignedIntTy,
1115      Context.LongTy, Context.UnsignedLongTy ,
1116      Context.LongLongTy, Context.UnsignedLongLongTy
1117    };
1118    for (int Idx = 0; Idx < 6; ++Idx) {
1119      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1120      if (FromSize < ToSize ||
1121          (FromSize == ToSize &&
1122           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1123        // We found the type that we can promote to. If this is the
1124        // type we wanted, we have a promotion. Otherwise, no
1125        // promotion.
1126        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1127      }
1128    }
1129  }
1130
1131  // An rvalue for an integral bit-field (9.6) can be converted to an
1132  // rvalue of type int if int can represent all the values of the
1133  // bit-field; otherwise, it can be converted to unsigned int if
1134  // unsigned int can represent all the values of the bit-field. If
1135  // the bit-field is larger yet, no integral promotion applies to
1136  // it. If the bit-field has an enumerated type, it is treated as any
1137  // other value of that type for promotion purposes (C++ 4.5p3).
1138  // FIXME: We should delay checking of bit-fields until we actually perform the
1139  // conversion.
1140  using llvm::APSInt;
1141  if (From)
1142    if (FieldDecl *MemberDecl = From->getBitField()) {
1143      APSInt BitWidth;
1144      if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1145          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1146        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1147        ToSize = Context.getTypeSize(ToType);
1148
1149        // Are we promoting to an int from a bitfield that fits in an int?
1150        if (BitWidth < ToSize ||
1151            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1152          return To->getKind() == BuiltinType::Int;
1153        }
1154
1155        // Are we promoting to an unsigned int from an unsigned bitfield
1156        // that fits into an unsigned int?
1157        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1158          return To->getKind() == BuiltinType::UInt;
1159        }
1160
1161        return false;
1162      }
1163    }
1164
1165  // An rvalue of type bool can be converted to an rvalue of type int,
1166  // with false becoming zero and true becoming one (C++ 4.5p4).
1167  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1168    return true;
1169  }
1170
1171  return false;
1172}
1173
1174/// IsFloatingPointPromotion - Determines whether the conversion from
1175/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1176/// returns true and sets PromotedType to the promoted type.
1177bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1178  /// An rvalue of type float can be converted to an rvalue of type
1179  /// double. (C++ 4.6p1).
1180  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1181    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1182      if (FromBuiltin->getKind() == BuiltinType::Float &&
1183          ToBuiltin->getKind() == BuiltinType::Double)
1184        return true;
1185
1186      // C99 6.3.1.5p1:
1187      //   When a float is promoted to double or long double, or a
1188      //   double is promoted to long double [...].
1189      if (!getLangOptions().CPlusPlus &&
1190          (FromBuiltin->getKind() == BuiltinType::Float ||
1191           FromBuiltin->getKind() == BuiltinType::Double) &&
1192          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1193        return true;
1194    }
1195
1196  return false;
1197}
1198
1199/// \brief Determine if a conversion is a complex promotion.
1200///
1201/// A complex promotion is defined as a complex -> complex conversion
1202/// where the conversion between the underlying real types is a
1203/// floating-point or integral promotion.
1204bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1205  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1206  if (!FromComplex)
1207    return false;
1208
1209  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1210  if (!ToComplex)
1211    return false;
1212
1213  return IsFloatingPointPromotion(FromComplex->getElementType(),
1214                                  ToComplex->getElementType()) ||
1215    IsIntegralPromotion(0, FromComplex->getElementType(),
1216                        ToComplex->getElementType());
1217}
1218
1219/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1220/// the pointer type FromPtr to a pointer to type ToPointee, with the
1221/// same type qualifiers as FromPtr has on its pointee type. ToType,
1222/// if non-empty, will be a pointer to ToType that may or may not have
1223/// the right set of qualifiers on its pointee.
1224static QualType
1225BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
1226                                   QualType ToPointee, QualType ToType,
1227                                   ASTContext &Context) {
1228  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1229  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1230  Qualifiers Quals = CanonFromPointee.getQualifiers();
1231
1232  // Exact qualifier match -> return the pointer type we're converting to.
1233  if (CanonToPointee.getLocalQualifiers() == Quals) {
1234    // ToType is exactly what we need. Return it.
1235    if (!ToType.isNull())
1236      return ToType.getUnqualifiedType();
1237
1238    // Build a pointer to ToPointee. It has the right qualifiers
1239    // already.
1240    return Context.getPointerType(ToPointee);
1241  }
1242
1243  // Just build a canonical type that has the right qualifiers.
1244  return Context.getPointerType(
1245         Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1246                                  Quals));
1247}
1248
1249/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1250/// the FromType, which is an objective-c pointer, to ToType, which may or may
1251/// not have the right set of qualifiers.
1252static QualType
1253BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1254                                             QualType ToType,
1255                                             ASTContext &Context) {
1256  QualType CanonFromType = Context.getCanonicalType(FromType);
1257  QualType CanonToType = Context.getCanonicalType(ToType);
1258  Qualifiers Quals = CanonFromType.getQualifiers();
1259
1260  // Exact qualifier match -> return the pointer type we're converting to.
1261  if (CanonToType.getLocalQualifiers() == Quals)
1262    return ToType;
1263
1264  // Just build a canonical type that has the right qualifiers.
1265  return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1266}
1267
1268static bool isNullPointerConstantForConversion(Expr *Expr,
1269                                               bool InOverloadResolution,
1270                                               ASTContext &Context) {
1271  // Handle value-dependent integral null pointer constants correctly.
1272  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1273  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1274      Expr->getType()->isIntegralType())
1275    return !InOverloadResolution;
1276
1277  return Expr->isNullPointerConstant(Context,
1278                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1279                                        : Expr::NPC_ValueDependentIsNull);
1280}
1281
1282/// IsPointerConversion - Determines whether the conversion of the
1283/// expression From, which has the (possibly adjusted) type FromType,
1284/// can be converted to the type ToType via a pointer conversion (C++
1285/// 4.10). If so, returns true and places the converted type (that
1286/// might differ from ToType in its cv-qualifiers at some level) into
1287/// ConvertedType.
1288///
1289/// This routine also supports conversions to and from block pointers
1290/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1291/// pointers to interfaces. FIXME: Once we've determined the
1292/// appropriate overloading rules for Objective-C, we may want to
1293/// split the Objective-C checks into a different routine; however,
1294/// GCC seems to consider all of these conversions to be pointer
1295/// conversions, so for now they live here. IncompatibleObjC will be
1296/// set if the conversion is an allowed Objective-C conversion that
1297/// should result in a warning.
1298bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1299                               bool InOverloadResolution,
1300                               QualType& ConvertedType,
1301                               bool &IncompatibleObjC) {
1302  IncompatibleObjC = false;
1303  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1304    return true;
1305
1306  // Conversion from a null pointer constant to any Objective-C pointer type.
1307  if (ToType->isObjCObjectPointerType() &&
1308      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1309    ConvertedType = ToType;
1310    return true;
1311  }
1312
1313  // Blocks: Block pointers can be converted to void*.
1314  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1315      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1316    ConvertedType = ToType;
1317    return true;
1318  }
1319  // Blocks: A null pointer constant can be converted to a block
1320  // pointer type.
1321  if (ToType->isBlockPointerType() &&
1322      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1323    ConvertedType = ToType;
1324    return true;
1325  }
1326
1327  // If the left-hand-side is nullptr_t, the right side can be a null
1328  // pointer constant.
1329  if (ToType->isNullPtrType() &&
1330      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1331    ConvertedType = ToType;
1332    return true;
1333  }
1334
1335  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1336  if (!ToTypePtr)
1337    return false;
1338
1339  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1340  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1341    ConvertedType = ToType;
1342    return true;
1343  }
1344
1345  // Beyond this point, both types need to be pointers
1346  // , including objective-c pointers.
1347  QualType ToPointeeType = ToTypePtr->getPointeeType();
1348  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1349    ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1350                                                       ToType, Context);
1351    return true;
1352
1353  }
1354  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1355  if (!FromTypePtr)
1356    return false;
1357
1358  QualType FromPointeeType = FromTypePtr->getPointeeType();
1359
1360  // An rvalue of type "pointer to cv T," where T is an object type,
1361  // can be converted to an rvalue of type "pointer to cv void" (C++
1362  // 4.10p2).
1363  if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
1364    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1365                                                       ToPointeeType,
1366                                                       ToType, Context);
1367    return true;
1368  }
1369
1370  // When we're overloading in C, we allow a special kind of pointer
1371  // conversion for compatible-but-not-identical pointee types.
1372  if (!getLangOptions().CPlusPlus &&
1373      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1374    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1375                                                       ToPointeeType,
1376                                                       ToType, Context);
1377    return true;
1378  }
1379
1380  // C++ [conv.ptr]p3:
1381  //
1382  //   An rvalue of type "pointer to cv D," where D is a class type,
1383  //   can be converted to an rvalue of type "pointer to cv B," where
1384  //   B is a base class (clause 10) of D. If B is an inaccessible
1385  //   (clause 11) or ambiguous (10.2) base class of D, a program that
1386  //   necessitates this conversion is ill-formed. The result of the
1387  //   conversion is a pointer to the base class sub-object of the
1388  //   derived class object. The null pointer value is converted to
1389  //   the null pointer value of the destination type.
1390  //
1391  // Note that we do not check for ambiguity or inaccessibility
1392  // here. That is handled by CheckPointerConversion.
1393  if (getLangOptions().CPlusPlus &&
1394      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1395      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1396      !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1397      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1398    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1399                                                       ToPointeeType,
1400                                                       ToType, Context);
1401    return true;
1402  }
1403
1404  return false;
1405}
1406
1407/// isObjCPointerConversion - Determines whether this is an
1408/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1409/// with the same arguments and return values.
1410bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1411                                   QualType& ConvertedType,
1412                                   bool &IncompatibleObjC) {
1413  if (!getLangOptions().ObjC1)
1414    return false;
1415
1416  // First, we handle all conversions on ObjC object pointer types.
1417  const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
1418  const ObjCObjectPointerType *FromObjCPtr =
1419    FromType->getAs<ObjCObjectPointerType>();
1420
1421  if (ToObjCPtr && FromObjCPtr) {
1422    // Objective C++: We're able to convert between "id" or "Class" and a
1423    // pointer to any interface (in both directions).
1424    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1425      ConvertedType = ToType;
1426      return true;
1427    }
1428    // Conversions with Objective-C's id<...>.
1429    if ((FromObjCPtr->isObjCQualifiedIdType() ||
1430         ToObjCPtr->isObjCQualifiedIdType()) &&
1431        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1432                                                  /*compare=*/false)) {
1433      ConvertedType = ToType;
1434      return true;
1435    }
1436    // Objective C++: We're able to convert from a pointer to an
1437    // interface to a pointer to a different interface.
1438    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1439      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1440      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1441      if (getLangOptions().CPlusPlus && LHS && RHS &&
1442          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1443                                                FromObjCPtr->getPointeeType()))
1444        return false;
1445      ConvertedType = ToType;
1446      return true;
1447    }
1448
1449    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1450      // Okay: this is some kind of implicit downcast of Objective-C
1451      // interfaces, which is permitted. However, we're going to
1452      // complain about it.
1453      IncompatibleObjC = true;
1454      ConvertedType = FromType;
1455      return true;
1456    }
1457  }
1458  // Beyond this point, both types need to be C pointers or block pointers.
1459  QualType ToPointeeType;
1460  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1461    ToPointeeType = ToCPtr->getPointeeType();
1462  else if (const BlockPointerType *ToBlockPtr =
1463            ToType->getAs<BlockPointerType>()) {
1464    // Objective C++: We're able to convert from a pointer to any object
1465    // to a block pointer type.
1466    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1467      ConvertedType = ToType;
1468      return true;
1469    }
1470    ToPointeeType = ToBlockPtr->getPointeeType();
1471  }
1472  else if (FromType->getAs<BlockPointerType>() &&
1473           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1474    // Objective C++: We're able to convert from a block pointer type to a
1475    // pointer to any object.
1476    ConvertedType = ToType;
1477    return true;
1478  }
1479  else
1480    return false;
1481
1482  QualType FromPointeeType;
1483  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1484    FromPointeeType = FromCPtr->getPointeeType();
1485  else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
1486    FromPointeeType = FromBlockPtr->getPointeeType();
1487  else
1488    return false;
1489
1490  // If we have pointers to pointers, recursively check whether this
1491  // is an Objective-C conversion.
1492  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1493      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1494                              IncompatibleObjC)) {
1495    // We always complain about this conversion.
1496    IncompatibleObjC = true;
1497    ConvertedType = ToType;
1498    return true;
1499  }
1500  // Allow conversion of pointee being objective-c pointer to another one;
1501  // as in I* to id.
1502  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1503      ToPointeeType->getAs<ObjCObjectPointerType>() &&
1504      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1505                              IncompatibleObjC)) {
1506    ConvertedType = ToType;
1507    return true;
1508  }
1509
1510  // If we have pointers to functions or blocks, check whether the only
1511  // differences in the argument and result types are in Objective-C
1512  // pointer conversions. If so, we permit the conversion (but
1513  // complain about it).
1514  const FunctionProtoType *FromFunctionType
1515    = FromPointeeType->getAs<FunctionProtoType>();
1516  const FunctionProtoType *ToFunctionType
1517    = ToPointeeType->getAs<FunctionProtoType>();
1518  if (FromFunctionType && ToFunctionType) {
1519    // If the function types are exactly the same, this isn't an
1520    // Objective-C pointer conversion.
1521    if (Context.getCanonicalType(FromPointeeType)
1522          == Context.getCanonicalType(ToPointeeType))
1523      return false;
1524
1525    // Perform the quick checks that will tell us whether these
1526    // function types are obviously different.
1527    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1528        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1529        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1530      return false;
1531
1532    bool HasObjCConversion = false;
1533    if (Context.getCanonicalType(FromFunctionType->getResultType())
1534          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1535      // Okay, the types match exactly. Nothing to do.
1536    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1537                                       ToFunctionType->getResultType(),
1538                                       ConvertedType, IncompatibleObjC)) {
1539      // Okay, we have an Objective-C pointer conversion.
1540      HasObjCConversion = true;
1541    } else {
1542      // Function types are too different. Abort.
1543      return false;
1544    }
1545
1546    // Check argument types.
1547    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1548         ArgIdx != NumArgs; ++ArgIdx) {
1549      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1550      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1551      if (Context.getCanonicalType(FromArgType)
1552            == Context.getCanonicalType(ToArgType)) {
1553        // Okay, the types match exactly. Nothing to do.
1554      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1555                                         ConvertedType, IncompatibleObjC)) {
1556        // Okay, we have an Objective-C pointer conversion.
1557        HasObjCConversion = true;
1558      } else {
1559        // Argument types are too different. Abort.
1560        return false;
1561      }
1562    }
1563
1564    if (HasObjCConversion) {
1565      // We had an Objective-C conversion. Allow this pointer
1566      // conversion, but complain about it.
1567      ConvertedType = ToType;
1568      IncompatibleObjC = true;
1569      return true;
1570    }
1571  }
1572
1573  return false;
1574}
1575
1576/// FunctionArgTypesAreEqual - This routine checks two function proto types
1577/// for equlity of their argument types. Caller has already checked that
1578/// they have same number of arguments. This routine assumes that Objective-C
1579/// pointer types which only differ in their protocol qualifiers are equal.
1580bool Sema::FunctionArgTypesAreEqual(FunctionProtoType*  OldType,
1581                            FunctionProtoType*  NewType){
1582  if (!getLangOptions().ObjC1)
1583    return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1584                      NewType->arg_type_begin());
1585
1586  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1587       N = NewType->arg_type_begin(),
1588       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1589    QualType ToType = (*O);
1590    QualType FromType = (*N);
1591    if (ToType != FromType) {
1592      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1593        if (const PointerType *PTFr = FromType->getAs<PointerType>())
1594          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1595               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1596              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1597               PTFr->getPointeeType()->isObjCQualifiedClassType()))
1598            continue;
1599      }
1600      else if (const ObjCObjectPointerType *PTTo =
1601                 ToType->getAs<ObjCObjectPointerType>()) {
1602        if (const ObjCObjectPointerType *PTFr =
1603              FromType->getAs<ObjCObjectPointerType>())
1604          if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1605            continue;
1606      }
1607      return false;
1608    }
1609  }
1610  return true;
1611}
1612
1613/// CheckPointerConversion - Check the pointer conversion from the
1614/// expression From to the type ToType. This routine checks for
1615/// ambiguous or inaccessible derived-to-base pointer
1616/// conversions for which IsPointerConversion has already returned
1617/// true. It returns true and produces a diagnostic if there was an
1618/// error, or returns false otherwise.
1619bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1620                                  CastExpr::CastKind &Kind,
1621                                  CXXBaseSpecifierArray& BasePath,
1622                                  bool IgnoreBaseAccess) {
1623  QualType FromType = From->getType();
1624
1625  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1626    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1627      QualType FromPointeeType = FromPtrType->getPointeeType(),
1628               ToPointeeType   = ToPtrType->getPointeeType();
1629
1630      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1631          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
1632        // We must have a derived-to-base conversion. Check an
1633        // ambiguous or inaccessible conversion.
1634        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1635                                         From->getExprLoc(),
1636                                         From->getSourceRange(), &BasePath,
1637                                         IgnoreBaseAccess))
1638          return true;
1639
1640        // The conversion was successful.
1641        Kind = CastExpr::CK_DerivedToBase;
1642      }
1643    }
1644  if (const ObjCObjectPointerType *FromPtrType =
1645        FromType->getAs<ObjCObjectPointerType>())
1646    if (const ObjCObjectPointerType *ToPtrType =
1647          ToType->getAs<ObjCObjectPointerType>()) {
1648      // Objective-C++ conversions are always okay.
1649      // FIXME: We should have a different class of conversions for the
1650      // Objective-C++ implicit conversions.
1651      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1652        return false;
1653
1654  }
1655  return false;
1656}
1657
1658/// IsMemberPointerConversion - Determines whether the conversion of the
1659/// expression From, which has the (possibly adjusted) type FromType, can be
1660/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1661/// If so, returns true and places the converted type (that might differ from
1662/// ToType in its cv-qualifiers at some level) into ConvertedType.
1663bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1664                                     QualType ToType,
1665                                     bool InOverloadResolution,
1666                                     QualType &ConvertedType) {
1667  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1668  if (!ToTypePtr)
1669    return false;
1670
1671  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1672  if (From->isNullPointerConstant(Context,
1673                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1674                                        : Expr::NPC_ValueDependentIsNull)) {
1675    ConvertedType = ToType;
1676    return true;
1677  }
1678
1679  // Otherwise, both types have to be member pointers.
1680  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1681  if (!FromTypePtr)
1682    return false;
1683
1684  // A pointer to member of B can be converted to a pointer to member of D,
1685  // where D is derived from B (C++ 4.11p2).
1686  QualType FromClass(FromTypePtr->getClass(), 0);
1687  QualType ToClass(ToTypePtr->getClass(), 0);
1688  // FIXME: What happens when these are dependent? Is this function even called?
1689
1690  if (IsDerivedFrom(ToClass, FromClass)) {
1691    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1692                                                 ToClass.getTypePtr());
1693    return true;
1694  }
1695
1696  return false;
1697}
1698
1699/// CheckMemberPointerConversion - Check the member pointer conversion from the
1700/// expression From to the type ToType. This routine checks for ambiguous or
1701/// virtual or inaccessible base-to-derived member pointer conversions
1702/// for which IsMemberPointerConversion has already returned true. It returns
1703/// true and produces a diagnostic if there was an error, or returns false
1704/// otherwise.
1705bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1706                                        CastExpr::CastKind &Kind,
1707                                        CXXBaseSpecifierArray &BasePath,
1708                                        bool IgnoreBaseAccess) {
1709  QualType FromType = From->getType();
1710  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1711  if (!FromPtrType) {
1712    // This must be a null pointer to member pointer conversion
1713    assert(From->isNullPointerConstant(Context,
1714                                       Expr::NPC_ValueDependentIsNull) &&
1715           "Expr must be null pointer constant!");
1716    Kind = CastExpr::CK_NullToMemberPointer;
1717    return false;
1718  }
1719
1720  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1721  assert(ToPtrType && "No member pointer cast has a target type "
1722                      "that is not a member pointer.");
1723
1724  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1725  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1726
1727  // FIXME: What about dependent types?
1728  assert(FromClass->isRecordType() && "Pointer into non-class.");
1729  assert(ToClass->isRecordType() && "Pointer into non-class.");
1730
1731  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1732                     /*DetectVirtual=*/true);
1733  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1734  assert(DerivationOkay &&
1735         "Should not have been called if derivation isn't OK.");
1736  (void)DerivationOkay;
1737
1738  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1739                                  getUnqualifiedType())) {
1740    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1741    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1742      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1743    return true;
1744  }
1745
1746  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1747    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1748      << FromClass << ToClass << QualType(VBase, 0)
1749      << From->getSourceRange();
1750    return true;
1751  }
1752
1753  if (!IgnoreBaseAccess)
1754    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1755                         Paths.front(),
1756                         diag::err_downcast_from_inaccessible_base);
1757
1758  // Must be a base to derived member conversion.
1759  BuildBasePathArray(Paths, BasePath);
1760  Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1761  return false;
1762}
1763
1764/// IsQualificationConversion - Determines whether the conversion from
1765/// an rvalue of type FromType to ToType is a qualification conversion
1766/// (C++ 4.4).
1767bool
1768Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
1769  FromType = Context.getCanonicalType(FromType);
1770  ToType = Context.getCanonicalType(ToType);
1771
1772  // If FromType and ToType are the same type, this is not a
1773  // qualification conversion.
1774  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
1775    return false;
1776
1777  // (C++ 4.4p4):
1778  //   A conversion can add cv-qualifiers at levels other than the first
1779  //   in multi-level pointers, subject to the following rules: [...]
1780  bool PreviousToQualsIncludeConst = true;
1781  bool UnwrappedAnyPointer = false;
1782  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1783    // Within each iteration of the loop, we check the qualifiers to
1784    // determine if this still looks like a qualification
1785    // conversion. Then, if all is well, we unwrap one more level of
1786    // pointers or pointers-to-members and do it all again
1787    // until there are no more pointers or pointers-to-members left to
1788    // unwrap.
1789    UnwrappedAnyPointer = true;
1790
1791    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1792    //      2,j, and similarly for volatile.
1793    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1794      return false;
1795
1796    //   -- if the cv 1,j and cv 2,j are different, then const is in
1797    //      every cv for 0 < k < j.
1798    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1799        && !PreviousToQualsIncludeConst)
1800      return false;
1801
1802    // Keep track of whether all prior cv-qualifiers in the "to" type
1803    // include const.
1804    PreviousToQualsIncludeConst
1805      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1806  }
1807
1808  // We are left with FromType and ToType being the pointee types
1809  // after unwrapping the original FromType and ToType the same number
1810  // of types. If we unwrapped any pointers, and if FromType and
1811  // ToType have the same unqualified type (since we checked
1812  // qualifiers above), then this is a qualification conversion.
1813  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
1814}
1815
1816/// Determines whether there is a user-defined conversion sequence
1817/// (C++ [over.ics.user]) that converts expression From to the type
1818/// ToType. If such a conversion exists, User will contain the
1819/// user-defined conversion sequence that performs such a conversion
1820/// and this routine will return true. Otherwise, this routine returns
1821/// false and User is unspecified.
1822///
1823/// \param AllowExplicit  true if the conversion should consider C++0x
1824/// "explicit" conversion functions as well as non-explicit conversion
1825/// functions (C++0x [class.conv.fct]p2).
1826OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1827                                          UserDefinedConversionSequence& User,
1828                                           OverloadCandidateSet& CandidateSet,
1829                                                bool AllowExplicit) {
1830  // Whether we will only visit constructors.
1831  bool ConstructorsOnly = false;
1832
1833  // If the type we are conversion to is a class type, enumerate its
1834  // constructors.
1835  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1836    // C++ [over.match.ctor]p1:
1837    //   When objects of class type are direct-initialized (8.5), or
1838    //   copy-initialized from an expression of the same or a
1839    //   derived class type (8.5), overload resolution selects the
1840    //   constructor. [...] For copy-initialization, the candidate
1841    //   functions are all the converting constructors (12.3.1) of
1842    //   that class. The argument list is the expression-list within
1843    //   the parentheses of the initializer.
1844    if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1845        (From->getType()->getAs<RecordType>() &&
1846         IsDerivedFrom(From->getType(), ToType)))
1847      ConstructorsOnly = true;
1848
1849    if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1850      // We're not going to find any constructors.
1851    } else if (CXXRecordDecl *ToRecordDecl
1852                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1853      DeclarationName ConstructorName
1854        = Context.DeclarationNames.getCXXConstructorName(
1855                       Context.getCanonicalType(ToType).getUnqualifiedType());
1856      DeclContext::lookup_iterator Con, ConEnd;
1857      for (llvm::tie(Con, ConEnd)
1858             = ToRecordDecl->lookup(ConstructorName);
1859           Con != ConEnd; ++Con) {
1860        NamedDecl *D = *Con;
1861        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1862
1863        // Find the constructor (which may be a template).
1864        CXXConstructorDecl *Constructor = 0;
1865        FunctionTemplateDecl *ConstructorTmpl
1866          = dyn_cast<FunctionTemplateDecl>(D);
1867        if (ConstructorTmpl)
1868          Constructor
1869            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1870        else
1871          Constructor = cast<CXXConstructorDecl>(D);
1872
1873        if (!Constructor->isInvalidDecl() &&
1874            Constructor->isConvertingConstructor(AllowExplicit)) {
1875          if (ConstructorTmpl)
1876            AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
1877                                         /*ExplicitArgs*/ 0,
1878                                         &From, 1, CandidateSet,
1879                                 /*SuppressUserConversions=*/!ConstructorsOnly);
1880          else
1881            // Allow one user-defined conversion when user specifies a
1882            // From->ToType conversion via an static cast (c-style, etc).
1883            AddOverloadCandidate(Constructor, FoundDecl,
1884                                 &From, 1, CandidateSet,
1885                                 /*SuppressUserConversions=*/!ConstructorsOnly);
1886        }
1887      }
1888    }
1889  }
1890
1891  // Enumerate conversion functions, if we're allowed to.
1892  if (ConstructorsOnly) {
1893  } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1894                          PDiag(0) << From->getSourceRange())) {
1895    // No conversion functions from incomplete types.
1896  } else if (const RecordType *FromRecordType
1897                                   = From->getType()->getAs<RecordType>()) {
1898    if (CXXRecordDecl *FromRecordDecl
1899         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1900      // Add all of the conversion functions as candidates.
1901      const UnresolvedSetImpl *Conversions
1902        = FromRecordDecl->getVisibleConversionFunctions();
1903      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
1904             E = Conversions->end(); I != E; ++I) {
1905        DeclAccessPair FoundDecl = I.getPair();
1906        NamedDecl *D = FoundDecl.getDecl();
1907        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1908        if (isa<UsingShadowDecl>(D))
1909          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1910
1911        CXXConversionDecl *Conv;
1912        FunctionTemplateDecl *ConvTemplate;
1913        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1914          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1915        else
1916          Conv = cast<CXXConversionDecl>(D);
1917
1918        if (AllowExplicit || !Conv->isExplicit()) {
1919          if (ConvTemplate)
1920            AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
1921                                           ActingContext, From, ToType,
1922                                           CandidateSet);
1923          else
1924            AddConversionCandidate(Conv, FoundDecl, ActingContext,
1925                                   From, ToType, CandidateSet);
1926        }
1927      }
1928    }
1929  }
1930
1931  OverloadCandidateSet::iterator Best;
1932  switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1933    case OR_Success:
1934      // Record the standard conversion we used and the conversion function.
1935      if (CXXConstructorDecl *Constructor
1936            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1937        // C++ [over.ics.user]p1:
1938        //   If the user-defined conversion is specified by a
1939        //   constructor (12.3.1), the initial standard conversion
1940        //   sequence converts the source type to the type required by
1941        //   the argument of the constructor.
1942        //
1943        QualType ThisType = Constructor->getThisType(Context);
1944        if (Best->Conversions[0].isEllipsis())
1945          User.EllipsisConversion = true;
1946        else {
1947          User.Before = Best->Conversions[0].Standard;
1948          User.EllipsisConversion = false;
1949        }
1950        User.ConversionFunction = Constructor;
1951        User.After.setAsIdentityConversion();
1952        User.After.setFromType(
1953          ThisType->getAs<PointerType>()->getPointeeType());
1954        User.After.setAllToTypes(ToType);
1955        return OR_Success;
1956      } else if (CXXConversionDecl *Conversion
1957                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1958        // C++ [over.ics.user]p1:
1959        //
1960        //   [...] If the user-defined conversion is specified by a
1961        //   conversion function (12.3.2), the initial standard
1962        //   conversion sequence converts the source type to the
1963        //   implicit object parameter of the conversion function.
1964        User.Before = Best->Conversions[0].Standard;
1965        User.ConversionFunction = Conversion;
1966        User.EllipsisConversion = false;
1967
1968        // C++ [over.ics.user]p2:
1969        //   The second standard conversion sequence converts the
1970        //   result of the user-defined conversion to the target type
1971        //   for the sequence. Since an implicit conversion sequence
1972        //   is an initialization, the special rules for
1973        //   initialization by user-defined conversion apply when
1974        //   selecting the best user-defined conversion for a
1975        //   user-defined conversion sequence (see 13.3.3 and
1976        //   13.3.3.1).
1977        User.After = Best->FinalConversion;
1978        return OR_Success;
1979      } else {
1980        assert(false && "Not a constructor or conversion function?");
1981        return OR_No_Viable_Function;
1982      }
1983
1984    case OR_No_Viable_Function:
1985      return OR_No_Viable_Function;
1986    case OR_Deleted:
1987      // No conversion here! We're done.
1988      return OR_Deleted;
1989
1990    case OR_Ambiguous:
1991      return OR_Ambiguous;
1992    }
1993
1994  return OR_No_Viable_Function;
1995}
1996
1997bool
1998Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
1999  ImplicitConversionSequence ICS;
2000  OverloadCandidateSet CandidateSet(From->getExprLoc());
2001  OverloadingResult OvResult =
2002    IsUserDefinedConversion(From, ToType, ICS.UserDefined,
2003                            CandidateSet, false);
2004  if (OvResult == OR_Ambiguous)
2005    Diag(From->getSourceRange().getBegin(),
2006         diag::err_typecheck_ambiguous_condition)
2007          << From->getType() << ToType << From->getSourceRange();
2008  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2009    Diag(From->getSourceRange().getBegin(),
2010         diag::err_typecheck_nonviable_condition)
2011    << From->getType() << ToType << From->getSourceRange();
2012  else
2013    return false;
2014  PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
2015  return true;
2016}
2017
2018/// CompareImplicitConversionSequences - Compare two implicit
2019/// conversion sequences to determine whether one is better than the
2020/// other or if they are indistinguishable (C++ 13.3.3.2).
2021ImplicitConversionSequence::CompareKind
2022Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2023                                         const ImplicitConversionSequence& ICS2)
2024{
2025  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2026  // conversion sequences (as defined in 13.3.3.1)
2027  //   -- a standard conversion sequence (13.3.3.1.1) is a better
2028  //      conversion sequence than a user-defined conversion sequence or
2029  //      an ellipsis conversion sequence, and
2030  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
2031  //      conversion sequence than an ellipsis conversion sequence
2032  //      (13.3.3.1.3).
2033  //
2034  // C++0x [over.best.ics]p10:
2035  //   For the purpose of ranking implicit conversion sequences as
2036  //   described in 13.3.3.2, the ambiguous conversion sequence is
2037  //   treated as a user-defined sequence that is indistinguishable
2038  //   from any other user-defined conversion sequence.
2039  if (ICS1.getKindRank() < ICS2.getKindRank())
2040    return ImplicitConversionSequence::Better;
2041  else if (ICS2.getKindRank() < ICS1.getKindRank())
2042    return ImplicitConversionSequence::Worse;
2043
2044  // The following checks require both conversion sequences to be of
2045  // the same kind.
2046  if (ICS1.getKind() != ICS2.getKind())
2047    return ImplicitConversionSequence::Indistinguishable;
2048
2049  // Two implicit conversion sequences of the same form are
2050  // indistinguishable conversion sequences unless one of the
2051  // following rules apply: (C++ 13.3.3.2p3):
2052  if (ICS1.isStandard())
2053    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
2054  else if (ICS1.isUserDefined()) {
2055    // User-defined conversion sequence U1 is a better conversion
2056    // sequence than another user-defined conversion sequence U2 if
2057    // they contain the same user-defined conversion function or
2058    // constructor and if the second standard conversion sequence of
2059    // U1 is better than the second standard conversion sequence of
2060    // U2 (C++ 13.3.3.2p3).
2061    if (ICS1.UserDefined.ConversionFunction ==
2062          ICS2.UserDefined.ConversionFunction)
2063      return CompareStandardConversionSequences(ICS1.UserDefined.After,
2064                                                ICS2.UserDefined.After);
2065  }
2066
2067  return ImplicitConversionSequence::Indistinguishable;
2068}
2069
2070// Per 13.3.3.2p3, compare the given standard conversion sequences to
2071// determine if one is a proper subset of the other.
2072static ImplicitConversionSequence::CompareKind
2073compareStandardConversionSubsets(ASTContext &Context,
2074                                 const StandardConversionSequence& SCS1,
2075                                 const StandardConversionSequence& SCS2) {
2076  ImplicitConversionSequence::CompareKind Result
2077    = ImplicitConversionSequence::Indistinguishable;
2078
2079  // the identity conversion sequence is considered to be a subsequence of
2080  // any non-identity conversion sequence
2081  if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2082    if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2083      return ImplicitConversionSequence::Better;
2084    else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2085      return ImplicitConversionSequence::Worse;
2086  }
2087
2088  if (SCS1.Second != SCS2.Second) {
2089    if (SCS1.Second == ICK_Identity)
2090      Result = ImplicitConversionSequence::Better;
2091    else if (SCS2.Second == ICK_Identity)
2092      Result = ImplicitConversionSequence::Worse;
2093    else
2094      return ImplicitConversionSequence::Indistinguishable;
2095  } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
2096    return ImplicitConversionSequence::Indistinguishable;
2097
2098  if (SCS1.Third == SCS2.Third) {
2099    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2100                             : ImplicitConversionSequence::Indistinguishable;
2101  }
2102
2103  if (SCS1.Third == ICK_Identity)
2104    return Result == ImplicitConversionSequence::Worse
2105             ? ImplicitConversionSequence::Indistinguishable
2106             : ImplicitConversionSequence::Better;
2107
2108  if (SCS2.Third == ICK_Identity)
2109    return Result == ImplicitConversionSequence::Better
2110             ? ImplicitConversionSequence::Indistinguishable
2111             : ImplicitConversionSequence::Worse;
2112
2113  return ImplicitConversionSequence::Indistinguishable;
2114}
2115
2116/// CompareStandardConversionSequences - Compare two standard
2117/// conversion sequences to determine whether one is better than the
2118/// other or if they are indistinguishable (C++ 13.3.3.2p3).
2119ImplicitConversionSequence::CompareKind
2120Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2121                                         const StandardConversionSequence& SCS2)
2122{
2123  // Standard conversion sequence S1 is a better conversion sequence
2124  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2125
2126  //  -- S1 is a proper subsequence of S2 (comparing the conversion
2127  //     sequences in the canonical form defined by 13.3.3.1.1,
2128  //     excluding any Lvalue Transformation; the identity conversion
2129  //     sequence is considered to be a subsequence of any
2130  //     non-identity conversion sequence) or, if not that,
2131  if (ImplicitConversionSequence::CompareKind CK
2132        = compareStandardConversionSubsets(Context, SCS1, SCS2))
2133    return CK;
2134
2135  //  -- the rank of S1 is better than the rank of S2 (by the rules
2136  //     defined below), or, if not that,
2137  ImplicitConversionRank Rank1 = SCS1.getRank();
2138  ImplicitConversionRank Rank2 = SCS2.getRank();
2139  if (Rank1 < Rank2)
2140    return ImplicitConversionSequence::Better;
2141  else if (Rank2 < Rank1)
2142    return ImplicitConversionSequence::Worse;
2143
2144  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2145  // are indistinguishable unless one of the following rules
2146  // applies:
2147
2148  //   A conversion that is not a conversion of a pointer, or
2149  //   pointer to member, to bool is better than another conversion
2150  //   that is such a conversion.
2151  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2152    return SCS2.isPointerConversionToBool()
2153             ? ImplicitConversionSequence::Better
2154             : ImplicitConversionSequence::Worse;
2155
2156  // C++ [over.ics.rank]p4b2:
2157  //
2158  //   If class B is derived directly or indirectly from class A,
2159  //   conversion of B* to A* is better than conversion of B* to
2160  //   void*, and conversion of A* to void* is better than conversion
2161  //   of B* to void*.
2162  bool SCS1ConvertsToVoid
2163    = SCS1.isPointerConversionToVoidPointer(Context);
2164  bool SCS2ConvertsToVoid
2165    = SCS2.isPointerConversionToVoidPointer(Context);
2166  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2167    // Exactly one of the conversion sequences is a conversion to
2168    // a void pointer; it's the worse conversion.
2169    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2170                              : ImplicitConversionSequence::Worse;
2171  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2172    // Neither conversion sequence converts to a void pointer; compare
2173    // their derived-to-base conversions.
2174    if (ImplicitConversionSequence::CompareKind DerivedCK
2175          = CompareDerivedToBaseConversions(SCS1, SCS2))
2176      return DerivedCK;
2177  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2178    // Both conversion sequences are conversions to void
2179    // pointers. Compare the source types to determine if there's an
2180    // inheritance relationship in their sources.
2181    QualType FromType1 = SCS1.getFromType();
2182    QualType FromType2 = SCS2.getFromType();
2183
2184    // Adjust the types we're converting from via the array-to-pointer
2185    // conversion, if we need to.
2186    if (SCS1.First == ICK_Array_To_Pointer)
2187      FromType1 = Context.getArrayDecayedType(FromType1);
2188    if (SCS2.First == ICK_Array_To_Pointer)
2189      FromType2 = Context.getArrayDecayedType(FromType2);
2190
2191    QualType FromPointee1
2192      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2193    QualType FromPointee2
2194      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2195
2196    if (IsDerivedFrom(FromPointee2, FromPointee1))
2197      return ImplicitConversionSequence::Better;
2198    else if (IsDerivedFrom(FromPointee1, FromPointee2))
2199      return ImplicitConversionSequence::Worse;
2200
2201    // Objective-C++: If one interface is more specific than the
2202    // other, it is the better one.
2203    const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2204    const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2205    if (FromIface1 && FromIface1) {
2206      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2207        return ImplicitConversionSequence::Better;
2208      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2209        return ImplicitConversionSequence::Worse;
2210    }
2211  }
2212
2213  // Compare based on qualification conversions (C++ 13.3.3.2p3,
2214  // bullet 3).
2215  if (ImplicitConversionSequence::CompareKind QualCK
2216        = CompareQualificationConversions(SCS1, SCS2))
2217    return QualCK;
2218
2219  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
2220    // C++0x [over.ics.rank]p3b4:
2221    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2222    //      implicit object parameter of a non-static member function declared
2223    //      without a ref-qualifier, and S1 binds an rvalue reference to an
2224    //      rvalue and S2 binds an lvalue reference.
2225    // FIXME: We don't know if we're dealing with the implicit object parameter,
2226    // or if the member function in this case has a ref qualifier.
2227    // (Of course, we don't have ref qualifiers yet.)
2228    if (SCS1.RRefBinding != SCS2.RRefBinding)
2229      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2230                              : ImplicitConversionSequence::Worse;
2231
2232    // C++ [over.ics.rank]p3b4:
2233    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
2234    //      which the references refer are the same type except for
2235    //      top-level cv-qualifiers, and the type to which the reference
2236    //      initialized by S2 refers is more cv-qualified than the type
2237    //      to which the reference initialized by S1 refers.
2238    QualType T1 = SCS1.getToType(2);
2239    QualType T2 = SCS2.getToType(2);
2240    T1 = Context.getCanonicalType(T1);
2241    T2 = Context.getCanonicalType(T2);
2242    Qualifiers T1Quals, T2Quals;
2243    QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2244    QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2245    if (UnqualT1 == UnqualT2) {
2246      // If the type is an array type, promote the element qualifiers to the type
2247      // for comparison.
2248      if (isa<ArrayType>(T1) && T1Quals)
2249        T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2250      if (isa<ArrayType>(T2) && T2Quals)
2251        T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2252      if (T2.isMoreQualifiedThan(T1))
2253        return ImplicitConversionSequence::Better;
2254      else if (T1.isMoreQualifiedThan(T2))
2255        return ImplicitConversionSequence::Worse;
2256    }
2257  }
2258
2259  return ImplicitConversionSequence::Indistinguishable;
2260}
2261
2262/// CompareQualificationConversions - Compares two standard conversion
2263/// sequences to determine whether they can be ranked based on their
2264/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2265ImplicitConversionSequence::CompareKind
2266Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
2267                                      const StandardConversionSequence& SCS2) {
2268  // C++ 13.3.3.2p3:
2269  //  -- S1 and S2 differ only in their qualification conversion and
2270  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
2271  //     cv-qualification signature of type T1 is a proper subset of
2272  //     the cv-qualification signature of type T2, and S1 is not the
2273  //     deprecated string literal array-to-pointer conversion (4.2).
2274  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2275      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2276    return ImplicitConversionSequence::Indistinguishable;
2277
2278  // FIXME: the example in the standard doesn't use a qualification
2279  // conversion (!)
2280  QualType T1 = SCS1.getToType(2);
2281  QualType T2 = SCS2.getToType(2);
2282  T1 = Context.getCanonicalType(T1);
2283  T2 = Context.getCanonicalType(T2);
2284  Qualifiers T1Quals, T2Quals;
2285  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2286  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2287
2288  // If the types are the same, we won't learn anything by unwrapped
2289  // them.
2290  if (UnqualT1 == UnqualT2)
2291    return ImplicitConversionSequence::Indistinguishable;
2292
2293  // If the type is an array type, promote the element qualifiers to the type
2294  // for comparison.
2295  if (isa<ArrayType>(T1) && T1Quals)
2296    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2297  if (isa<ArrayType>(T2) && T2Quals)
2298    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2299
2300  ImplicitConversionSequence::CompareKind Result
2301    = ImplicitConversionSequence::Indistinguishable;
2302  while (UnwrapSimilarPointerTypes(T1, T2)) {
2303    // Within each iteration of the loop, we check the qualifiers to
2304    // determine if this still looks like a qualification
2305    // conversion. Then, if all is well, we unwrap one more level of
2306    // pointers or pointers-to-members and do it all again
2307    // until there are no more pointers or pointers-to-members left
2308    // to unwrap. This essentially mimics what
2309    // IsQualificationConversion does, but here we're checking for a
2310    // strict subset of qualifiers.
2311    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2312      // The qualifiers are the same, so this doesn't tell us anything
2313      // about how the sequences rank.
2314      ;
2315    else if (T2.isMoreQualifiedThan(T1)) {
2316      // T1 has fewer qualifiers, so it could be the better sequence.
2317      if (Result == ImplicitConversionSequence::Worse)
2318        // Neither has qualifiers that are a subset of the other's
2319        // qualifiers.
2320        return ImplicitConversionSequence::Indistinguishable;
2321
2322      Result = ImplicitConversionSequence::Better;
2323    } else if (T1.isMoreQualifiedThan(T2)) {
2324      // T2 has fewer qualifiers, so it could be the better sequence.
2325      if (Result == ImplicitConversionSequence::Better)
2326        // Neither has qualifiers that are a subset of the other's
2327        // qualifiers.
2328        return ImplicitConversionSequence::Indistinguishable;
2329
2330      Result = ImplicitConversionSequence::Worse;
2331    } else {
2332      // Qualifiers are disjoint.
2333      return ImplicitConversionSequence::Indistinguishable;
2334    }
2335
2336    // If the types after this point are equivalent, we're done.
2337    if (Context.hasSameUnqualifiedType(T1, T2))
2338      break;
2339  }
2340
2341  // Check that the winning standard conversion sequence isn't using
2342  // the deprecated string literal array to pointer conversion.
2343  switch (Result) {
2344  case ImplicitConversionSequence::Better:
2345    if (SCS1.DeprecatedStringLiteralToCharPtr)
2346      Result = ImplicitConversionSequence::Indistinguishable;
2347    break;
2348
2349  case ImplicitConversionSequence::Indistinguishable:
2350    break;
2351
2352  case ImplicitConversionSequence::Worse:
2353    if (SCS2.DeprecatedStringLiteralToCharPtr)
2354      Result = ImplicitConversionSequence::Indistinguishable;
2355    break;
2356  }
2357
2358  return Result;
2359}
2360
2361/// CompareDerivedToBaseConversions - Compares two standard conversion
2362/// sequences to determine whether they can be ranked based on their
2363/// various kinds of derived-to-base conversions (C++
2364/// [over.ics.rank]p4b3).  As part of these checks, we also look at
2365/// conversions between Objective-C interface types.
2366ImplicitConversionSequence::CompareKind
2367Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2368                                      const StandardConversionSequence& SCS2) {
2369  QualType FromType1 = SCS1.getFromType();
2370  QualType ToType1 = SCS1.getToType(1);
2371  QualType FromType2 = SCS2.getFromType();
2372  QualType ToType2 = SCS2.getToType(1);
2373
2374  // Adjust the types we're converting from via the array-to-pointer
2375  // conversion, if we need to.
2376  if (SCS1.First == ICK_Array_To_Pointer)
2377    FromType1 = Context.getArrayDecayedType(FromType1);
2378  if (SCS2.First == ICK_Array_To_Pointer)
2379    FromType2 = Context.getArrayDecayedType(FromType2);
2380
2381  // Canonicalize all of the types.
2382  FromType1 = Context.getCanonicalType(FromType1);
2383  ToType1 = Context.getCanonicalType(ToType1);
2384  FromType2 = Context.getCanonicalType(FromType2);
2385  ToType2 = Context.getCanonicalType(ToType2);
2386
2387  // C++ [over.ics.rank]p4b3:
2388  //
2389  //   If class B is derived directly or indirectly from class A and
2390  //   class C is derived directly or indirectly from B,
2391  //
2392  // For Objective-C, we let A, B, and C also be Objective-C
2393  // interfaces.
2394
2395  // Compare based on pointer conversions.
2396  if (SCS1.Second == ICK_Pointer_Conversion &&
2397      SCS2.Second == ICK_Pointer_Conversion &&
2398      /*FIXME: Remove if Objective-C id conversions get their own rank*/
2399      FromType1->isPointerType() && FromType2->isPointerType() &&
2400      ToType1->isPointerType() && ToType2->isPointerType()) {
2401    QualType FromPointee1
2402      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2403    QualType ToPointee1
2404      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2405    QualType FromPointee2
2406      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2407    QualType ToPointee2
2408      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2409
2410    const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2411    const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2412    const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2413    const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
2414
2415    //   -- conversion of C* to B* is better than conversion of C* to A*,
2416    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2417      if (IsDerivedFrom(ToPointee1, ToPointee2))
2418        return ImplicitConversionSequence::Better;
2419      else if (IsDerivedFrom(ToPointee2, ToPointee1))
2420        return ImplicitConversionSequence::Worse;
2421
2422      if (ToIface1 && ToIface2) {
2423        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2424          return ImplicitConversionSequence::Better;
2425        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2426          return ImplicitConversionSequence::Worse;
2427      }
2428    }
2429
2430    //   -- conversion of B* to A* is better than conversion of C* to A*,
2431    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2432      if (IsDerivedFrom(FromPointee2, FromPointee1))
2433        return ImplicitConversionSequence::Better;
2434      else if (IsDerivedFrom(FromPointee1, FromPointee2))
2435        return ImplicitConversionSequence::Worse;
2436
2437      if (FromIface1 && FromIface2) {
2438        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2439          return ImplicitConversionSequence::Better;
2440        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2441          return ImplicitConversionSequence::Worse;
2442      }
2443    }
2444  }
2445
2446  // Ranking of member-pointer types.
2447  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2448      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2449      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2450    const MemberPointerType * FromMemPointer1 =
2451                                        FromType1->getAs<MemberPointerType>();
2452    const MemberPointerType * ToMemPointer1 =
2453                                          ToType1->getAs<MemberPointerType>();
2454    const MemberPointerType * FromMemPointer2 =
2455                                          FromType2->getAs<MemberPointerType>();
2456    const MemberPointerType * ToMemPointer2 =
2457                                          ToType2->getAs<MemberPointerType>();
2458    const Type *FromPointeeType1 = FromMemPointer1->getClass();
2459    const Type *ToPointeeType1 = ToMemPointer1->getClass();
2460    const Type *FromPointeeType2 = FromMemPointer2->getClass();
2461    const Type *ToPointeeType2 = ToMemPointer2->getClass();
2462    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2463    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2464    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2465    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
2466    // conversion of A::* to B::* is better than conversion of A::* to C::*,
2467    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2468      if (IsDerivedFrom(ToPointee1, ToPointee2))
2469        return ImplicitConversionSequence::Worse;
2470      else if (IsDerivedFrom(ToPointee2, ToPointee1))
2471        return ImplicitConversionSequence::Better;
2472    }
2473    // conversion of B::* to C::* is better than conversion of A::* to C::*
2474    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2475      if (IsDerivedFrom(FromPointee1, FromPointee2))
2476        return ImplicitConversionSequence::Better;
2477      else if (IsDerivedFrom(FromPointee2, FromPointee1))
2478        return ImplicitConversionSequence::Worse;
2479    }
2480  }
2481
2482  if (SCS1.Second == ICK_Derived_To_Base) {
2483    //   -- conversion of C to B is better than conversion of C to A,
2484    //   -- binding of an expression of type C to a reference of type
2485    //      B& is better than binding an expression of type C to a
2486    //      reference of type A&,
2487    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2488        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2489      if (IsDerivedFrom(ToType1, ToType2))
2490        return ImplicitConversionSequence::Better;
2491      else if (IsDerivedFrom(ToType2, ToType1))
2492        return ImplicitConversionSequence::Worse;
2493    }
2494
2495    //   -- conversion of B to A is better than conversion of C to A.
2496    //   -- binding of an expression of type B to a reference of type
2497    //      A& is better than binding an expression of type C to a
2498    //      reference of type A&,
2499    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2500        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2501      if (IsDerivedFrom(FromType2, FromType1))
2502        return ImplicitConversionSequence::Better;
2503      else if (IsDerivedFrom(FromType1, FromType2))
2504        return ImplicitConversionSequence::Worse;
2505    }
2506  }
2507
2508  return ImplicitConversionSequence::Indistinguishable;
2509}
2510
2511/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2512/// determine whether they are reference-related,
2513/// reference-compatible, reference-compatible with added
2514/// qualification, or incompatible, for use in C++ initialization by
2515/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2516/// type, and the first type (T1) is the pointee type of the reference
2517/// type being initialized.
2518Sema::ReferenceCompareResult
2519Sema::CompareReferenceRelationship(SourceLocation Loc,
2520                                   QualType OrigT1, QualType OrigT2,
2521                                   bool& DerivedToBase) {
2522  assert(!OrigT1->isReferenceType() &&
2523    "T1 must be the pointee type of the reference type");
2524  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2525
2526  QualType T1 = Context.getCanonicalType(OrigT1);
2527  QualType T2 = Context.getCanonicalType(OrigT2);
2528  Qualifiers T1Quals, T2Quals;
2529  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2530  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2531
2532  // C++ [dcl.init.ref]p4:
2533  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2534  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
2535  //   T1 is a base class of T2.
2536  if (UnqualT1 == UnqualT2)
2537    DerivedToBase = false;
2538  else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
2539           IsDerivedFrom(UnqualT2, UnqualT1))
2540    DerivedToBase = true;
2541  else
2542    return Ref_Incompatible;
2543
2544  // At this point, we know that T1 and T2 are reference-related (at
2545  // least).
2546
2547  // If the type is an array type, promote the element qualifiers to the type
2548  // for comparison.
2549  if (isa<ArrayType>(T1) && T1Quals)
2550    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2551  if (isa<ArrayType>(T2) && T2Quals)
2552    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2553
2554  // C++ [dcl.init.ref]p4:
2555  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2556  //   reference-related to T2 and cv1 is the same cv-qualification
2557  //   as, or greater cv-qualification than, cv2. For purposes of
2558  //   overload resolution, cases for which cv1 is greater
2559  //   cv-qualification than cv2 are identified as
2560  //   reference-compatible with added qualification (see 13.3.3.2).
2561  if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2562    return Ref_Compatible;
2563  else if (T1.isMoreQualifiedThan(T2))
2564    return Ref_Compatible_With_Added_Qualification;
2565  else
2566    return Ref_Related;
2567}
2568
2569/// \brief Compute an implicit conversion sequence for reference
2570/// initialization.
2571static ImplicitConversionSequence
2572TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2573                 SourceLocation DeclLoc,
2574                 bool SuppressUserConversions,
2575                 bool AllowExplicit) {
2576  assert(DeclType->isReferenceType() && "Reference init needs a reference");
2577
2578  // Most paths end in a failed conversion.
2579  ImplicitConversionSequence ICS;
2580  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2581
2582  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2583  QualType T2 = Init->getType();
2584
2585  // If the initializer is the address of an overloaded function, try
2586  // to resolve the overloaded function. If all goes well, T2 is the
2587  // type of the resulting function.
2588  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2589    DeclAccessPair Found;
2590    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2591                                                                false, Found))
2592      T2 = Fn->getType();
2593  }
2594
2595  // Compute some basic properties of the types and the initializer.
2596  bool isRValRef = DeclType->isRValueReferenceType();
2597  bool DerivedToBase = false;
2598  Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
2599  Sema::ReferenceCompareResult RefRelationship
2600    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2601
2602
2603  // C++ [over.ics.ref]p3:
2604  //   Except for an implicit object parameter, for which see 13.3.1,
2605  //   a standard conversion sequence cannot be formed if it requires
2606  //   binding an lvalue reference to non-const to an rvalue or
2607  //   binding an rvalue reference to an lvalue.
2608  //
2609  // FIXME: DPG doesn't trust this code. It seems far too early to
2610  // abort because of a binding of an rvalue reference to an lvalue.
2611  if (isRValRef && InitLvalue == Expr::LV_Valid)
2612    return ICS;
2613
2614  // C++0x [dcl.init.ref]p16:
2615  //   A reference to type "cv1 T1" is initialized by an expression
2616  //   of type "cv2 T2" as follows:
2617
2618  //     -- If the initializer expression
2619  //       -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2620  //          reference-compatible with "cv2 T2," or
2621  //
2622  // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2623  if (InitLvalue == Expr::LV_Valid &&
2624      RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2625    // C++ [over.ics.ref]p1:
2626    //   When a parameter of reference type binds directly (8.5.3)
2627    //   to an argument expression, the implicit conversion sequence
2628    //   is the identity conversion, unless the argument expression
2629    //   has a type that is a derived class of the parameter type,
2630    //   in which case the implicit conversion sequence is a
2631    //   derived-to-base Conversion (13.3.3.1).
2632    ICS.setStandard();
2633    ICS.Standard.First = ICK_Identity;
2634    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2635    ICS.Standard.Third = ICK_Identity;
2636    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2637    ICS.Standard.setToType(0, T2);
2638    ICS.Standard.setToType(1, T1);
2639    ICS.Standard.setToType(2, T1);
2640    ICS.Standard.ReferenceBinding = true;
2641    ICS.Standard.DirectBinding = true;
2642    ICS.Standard.RRefBinding = false;
2643    ICS.Standard.CopyConstructor = 0;
2644
2645    // Nothing more to do: the inaccessibility/ambiguity check for
2646    // derived-to-base conversions is suppressed when we're
2647    // computing the implicit conversion sequence (C++
2648    // [over.best.ics]p2).
2649    return ICS;
2650  }
2651
2652  //       -- has a class type (i.e., T2 is a class type), where T1 is
2653  //          not reference-related to T2, and can be implicitly
2654  //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
2655  //          is reference-compatible with "cv3 T3" 92) (this
2656  //          conversion is selected by enumerating the applicable
2657  //          conversion functions (13.3.1.6) and choosing the best
2658  //          one through overload resolution (13.3)),
2659  if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2660      !S.RequireCompleteType(DeclLoc, T2, 0) &&
2661      RefRelationship == Sema::Ref_Incompatible) {
2662    CXXRecordDecl *T2RecordDecl
2663      = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2664
2665    OverloadCandidateSet CandidateSet(DeclLoc);
2666    const UnresolvedSetImpl *Conversions
2667      = T2RecordDecl->getVisibleConversionFunctions();
2668    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2669           E = Conversions->end(); I != E; ++I) {
2670      NamedDecl *D = *I;
2671      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2672      if (isa<UsingShadowDecl>(D))
2673        D = cast<UsingShadowDecl>(D)->getTargetDecl();
2674
2675      FunctionTemplateDecl *ConvTemplate
2676        = dyn_cast<FunctionTemplateDecl>(D);
2677      CXXConversionDecl *Conv;
2678      if (ConvTemplate)
2679        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2680      else
2681        Conv = cast<CXXConversionDecl>(D);
2682
2683      // If the conversion function doesn't return a reference type,
2684      // it can't be considered for this conversion.
2685      if (Conv->getConversionType()->isLValueReferenceType() &&
2686          (AllowExplicit || !Conv->isExplicit())) {
2687        if (ConvTemplate)
2688          S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2689                                         Init, DeclType, CandidateSet);
2690        else
2691          S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2692                                 DeclType, CandidateSet);
2693      }
2694    }
2695
2696    OverloadCandidateSet::iterator Best;
2697    switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2698    case OR_Success:
2699      // C++ [over.ics.ref]p1:
2700      //
2701      //   [...] If the parameter binds directly to the result of
2702      //   applying a conversion function to the argument
2703      //   expression, the implicit conversion sequence is a
2704      //   user-defined conversion sequence (13.3.3.1.2), with the
2705      //   second standard conversion sequence either an identity
2706      //   conversion or, if the conversion function returns an
2707      //   entity of a type that is a derived class of the parameter
2708      //   type, a derived-to-base Conversion.
2709      if (!Best->FinalConversion.DirectBinding)
2710        break;
2711
2712      ICS.setUserDefined();
2713      ICS.UserDefined.Before = Best->Conversions[0].Standard;
2714      ICS.UserDefined.After = Best->FinalConversion;
2715      ICS.UserDefined.ConversionFunction = Best->Function;
2716      ICS.UserDefined.EllipsisConversion = false;
2717      assert(ICS.UserDefined.After.ReferenceBinding &&
2718             ICS.UserDefined.After.DirectBinding &&
2719             "Expected a direct reference binding!");
2720      return ICS;
2721
2722    case OR_Ambiguous:
2723      ICS.setAmbiguous();
2724      for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2725           Cand != CandidateSet.end(); ++Cand)
2726        if (Cand->Viable)
2727          ICS.Ambiguous.addConversion(Cand->Function);
2728      return ICS;
2729
2730    case OR_No_Viable_Function:
2731    case OR_Deleted:
2732      // There was no suitable conversion, or we found a deleted
2733      // conversion; continue with other checks.
2734      break;
2735    }
2736  }
2737
2738  //     -- Otherwise, the reference shall be to a non-volatile const
2739  //        type (i.e., cv1 shall be const), or the reference shall be an
2740  //        rvalue reference and the initializer expression shall be an rvalue.
2741  //
2742  // We actually handle one oddity of C++ [over.ics.ref] at this
2743  // point, which is that, due to p2 (which short-circuits reference
2744  // binding by only attempting a simple conversion for non-direct
2745  // bindings) and p3's strange wording, we allow a const volatile
2746  // reference to bind to an rvalue. Hence the check for the presence
2747  // of "const" rather than checking for "const" being the only
2748  // qualifier.
2749  if (!isRValRef && !T1.isConstQualified())
2750    return ICS;
2751
2752  //       -- if T2 is a class type and
2753  //          -- the initializer expression is an rvalue and "cv1 T1"
2754  //             is reference-compatible with "cv2 T2," or
2755  //
2756  //          -- T1 is not reference-related to T2 and the initializer
2757  //             expression can be implicitly converted to an rvalue
2758  //             of type "cv3 T3" (this conversion is selected by
2759  //             enumerating the applicable conversion functions
2760  //             (13.3.1.6) and choosing the best one through overload
2761  //             resolution (13.3)),
2762  //
2763  //          then the reference is bound to the initializer
2764  //          expression rvalue in the first case and to the object
2765  //          that is the result of the conversion in the second case
2766  //          (or, in either case, to the appropriate base class
2767  //          subobject of the object).
2768  //
2769  // We're only checking the first case here, which is a direct
2770  // binding in C++0x but not in C++03.
2771  if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2772      RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2773    ICS.setStandard();
2774    ICS.Standard.First = ICK_Identity;
2775    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2776    ICS.Standard.Third = ICK_Identity;
2777    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2778    ICS.Standard.setToType(0, T2);
2779    ICS.Standard.setToType(1, T1);
2780    ICS.Standard.setToType(2, T1);
2781    ICS.Standard.ReferenceBinding = true;
2782    ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2783    ICS.Standard.RRefBinding = isRValRef;
2784    ICS.Standard.CopyConstructor = 0;
2785    return ICS;
2786  }
2787
2788  //       -- Otherwise, a temporary of type "cv1 T1" is created and
2789  //          initialized from the initializer expression using the
2790  //          rules for a non-reference copy initialization (8.5). The
2791  //          reference is then bound to the temporary. If T1 is
2792  //          reference-related to T2, cv1 must be the same
2793  //          cv-qualification as, or greater cv-qualification than,
2794  //          cv2; otherwise, the program is ill-formed.
2795  if (RefRelationship == Sema::Ref_Related) {
2796    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2797    // we would be reference-compatible or reference-compatible with
2798    // added qualification. But that wasn't the case, so the reference
2799    // initialization fails.
2800    return ICS;
2801  }
2802
2803  // If at least one of the types is a class type, the types are not
2804  // related, and we aren't allowed any user conversions, the
2805  // reference binding fails. This case is important for breaking
2806  // recursion, since TryImplicitConversion below will attempt to
2807  // create a temporary through the use of a copy constructor.
2808  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2809      (T1->isRecordType() || T2->isRecordType()))
2810    return ICS;
2811
2812  // C++ [over.ics.ref]p2:
2813  //   When a parameter of reference type is not bound directly to
2814  //   an argument expression, the conversion sequence is the one
2815  //   required to convert the argument expression to the
2816  //   underlying type of the reference according to
2817  //   13.3.3.1. Conceptually, this conversion sequence corresponds
2818  //   to copy-initializing a temporary of the underlying type with
2819  //   the argument expression. Any difference in top-level
2820  //   cv-qualification is subsumed by the initialization itself
2821  //   and does not constitute a conversion.
2822  ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2823                                /*AllowExplicit=*/false,
2824                                /*InOverloadResolution=*/false);
2825
2826  // Of course, that's still a reference binding.
2827  if (ICS.isStandard()) {
2828    ICS.Standard.ReferenceBinding = true;
2829    ICS.Standard.RRefBinding = isRValRef;
2830  } else if (ICS.isUserDefined()) {
2831    ICS.UserDefined.After.ReferenceBinding = true;
2832    ICS.UserDefined.After.RRefBinding = isRValRef;
2833  }
2834  return ICS;
2835}
2836
2837/// TryCopyInitialization - Try to copy-initialize a value of type
2838/// ToType from the expression From. Return the implicit conversion
2839/// sequence required to pass this argument, which may be a bad
2840/// conversion sequence (meaning that the argument cannot be passed to
2841/// a parameter of this type). If @p SuppressUserConversions, then we
2842/// do not permit any user-defined conversion sequences.
2843static ImplicitConversionSequence
2844TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
2845                      bool SuppressUserConversions,
2846                      bool InOverloadResolution) {
2847  if (ToType->isReferenceType())
2848    return TryReferenceInit(S, From, ToType,
2849                            /*FIXME:*/From->getLocStart(),
2850                            SuppressUserConversions,
2851                            /*AllowExplicit=*/false);
2852
2853  return S.TryImplicitConversion(From, ToType,
2854                                 SuppressUserConversions,
2855                                 /*AllowExplicit=*/false,
2856                                 InOverloadResolution);
2857}
2858
2859/// TryObjectArgumentInitialization - Try to initialize the object
2860/// parameter of the given member function (@c Method) from the
2861/// expression @p From.
2862ImplicitConversionSequence
2863Sema::TryObjectArgumentInitialization(QualType OrigFromType,
2864                                      CXXMethodDecl *Method,
2865                                      CXXRecordDecl *ActingContext) {
2866  QualType ClassType = Context.getTypeDeclType(ActingContext);
2867  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2868  //                 const volatile object.
2869  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2870    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2871  QualType ImplicitParamType =  Context.getCVRQualifiedType(ClassType, Quals);
2872
2873  // Set up the conversion sequence as a "bad" conversion, to allow us
2874  // to exit early.
2875  ImplicitConversionSequence ICS;
2876
2877  // We need to have an object of class type.
2878  QualType FromType = OrigFromType;
2879  if (const PointerType *PT = FromType->getAs<PointerType>())
2880    FromType = PT->getPointeeType();
2881
2882  assert(FromType->isRecordType());
2883
2884  // The implicit object parameter is has the type "reference to cv X",
2885  // where X is the class of which the function is a member
2886  // (C++ [over.match.funcs]p4). However, when finding an implicit
2887  // conversion sequence for the argument, we are not allowed to
2888  // create temporaries or perform user-defined conversions
2889  // (C++ [over.match.funcs]p5). We perform a simplified version of
2890  // reference binding here, that allows class rvalues to bind to
2891  // non-constant references.
2892
2893  // First check the qualifiers. We don't care about lvalue-vs-rvalue
2894  // with the implicit object parameter (C++ [over.match.funcs]p5).
2895  QualType FromTypeCanon = Context.getCanonicalType(FromType);
2896  if (ImplicitParamType.getCVRQualifiers()
2897                                    != FromTypeCanon.getLocalCVRQualifiers() &&
2898      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
2899    ICS.setBad(BadConversionSequence::bad_qualifiers,
2900               OrigFromType, ImplicitParamType);
2901    return ICS;
2902  }
2903
2904  // Check that we have either the same type or a derived type. It
2905  // affects the conversion rank.
2906  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2907  ImplicitConversionKind SecondKind;
2908  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2909    SecondKind = ICK_Identity;
2910  } else if (IsDerivedFrom(FromType, ClassType))
2911    SecondKind = ICK_Derived_To_Base;
2912  else {
2913    ICS.setBad(BadConversionSequence::unrelated_class,
2914               FromType, ImplicitParamType);
2915    return ICS;
2916  }
2917
2918  // Success. Mark this as a reference binding.
2919  ICS.setStandard();
2920  ICS.Standard.setAsIdentityConversion();
2921  ICS.Standard.Second = SecondKind;
2922  ICS.Standard.setFromType(FromType);
2923  ICS.Standard.setAllToTypes(ImplicitParamType);
2924  ICS.Standard.ReferenceBinding = true;
2925  ICS.Standard.DirectBinding = true;
2926  ICS.Standard.RRefBinding = false;
2927  return ICS;
2928}
2929
2930/// PerformObjectArgumentInitialization - Perform initialization of
2931/// the implicit object parameter for the given Method with the given
2932/// expression.
2933bool
2934Sema::PerformObjectArgumentInitialization(Expr *&From,
2935                                          NestedNameSpecifier *Qualifier,
2936                                          NamedDecl *FoundDecl,
2937                                          CXXMethodDecl *Method) {
2938  QualType FromRecordType, DestType;
2939  QualType ImplicitParamRecordType  =
2940    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2941
2942  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
2943    FromRecordType = PT->getPointeeType();
2944    DestType = Method->getThisType(Context);
2945  } else {
2946    FromRecordType = From->getType();
2947    DestType = ImplicitParamRecordType;
2948  }
2949
2950  // Note that we always use the true parent context when performing
2951  // the actual argument initialization.
2952  ImplicitConversionSequence ICS
2953    = TryObjectArgumentInitialization(From->getType(), Method,
2954                                      Method->getParent());
2955  if (ICS.isBad())
2956    return Diag(From->getSourceRange().getBegin(),
2957                diag::err_implicit_object_parameter_init)
2958       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2959
2960  if (ICS.Standard.Second == ICK_Derived_To_Base)
2961    return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
2962
2963  if (!Context.hasSameType(From->getType(), DestType))
2964    ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2965                      /*isLvalue=*/!From->getType()->isPointerType());
2966  return false;
2967}
2968
2969/// TryContextuallyConvertToBool - Attempt to contextually convert the
2970/// expression From to bool (C++0x [conv]p3).
2971ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2972  // FIXME: This is pretty broken.
2973  return TryImplicitConversion(From, Context.BoolTy,
2974                               // FIXME: Are these flags correct?
2975                               /*SuppressUserConversions=*/false,
2976                               /*AllowExplicit=*/true,
2977                               /*InOverloadResolution=*/false);
2978}
2979
2980/// PerformContextuallyConvertToBool - Perform a contextual conversion
2981/// of the expression From to bool (C++0x [conv]p3).
2982bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2983  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2984  if (!ICS.isBad())
2985    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
2986
2987  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
2988    return  Diag(From->getSourceRange().getBegin(),
2989                 diag::err_typecheck_bool_condition)
2990                  << From->getType() << From->getSourceRange();
2991  return true;
2992}
2993
2994/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
2995/// expression From to 'id'.
2996ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
2997  QualType Ty = Context.getObjCIdType();
2998  return TryImplicitConversion(From, Ty,
2999                                 // FIXME: Are these flags correct?
3000                                 /*SuppressUserConversions=*/false,
3001                                 /*AllowExplicit=*/true,
3002                                 /*InOverloadResolution=*/false);
3003}
3004
3005/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3006/// of the expression From to 'id'.
3007bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
3008  QualType Ty = Context.getObjCIdType();
3009  ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3010  if (!ICS.isBad())
3011    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3012  return true;
3013}
3014
3015/// AddOverloadCandidate - Adds the given function to the set of
3016/// candidate functions, using the given function call arguments.  If
3017/// @p SuppressUserConversions, then don't allow user-defined
3018/// conversions via constructors or conversion operators.
3019///
3020/// \para PartialOverloading true if we are performing "partial" overloading
3021/// based on an incomplete set of function arguments. This feature is used by
3022/// code completion.
3023void
3024Sema::AddOverloadCandidate(FunctionDecl *Function,
3025                           DeclAccessPair FoundDecl,
3026                           Expr **Args, unsigned NumArgs,
3027                           OverloadCandidateSet& CandidateSet,
3028                           bool SuppressUserConversions,
3029                           bool PartialOverloading) {
3030  const FunctionProtoType* Proto
3031    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
3032  assert(Proto && "Functions without a prototype cannot be overloaded");
3033  assert(!Function->getDescribedFunctionTemplate() &&
3034         "Use AddTemplateOverloadCandidate for function templates");
3035
3036  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3037    if (!isa<CXXConstructorDecl>(Method)) {
3038      // If we get here, it's because we're calling a member function
3039      // that is named without a member access expression (e.g.,
3040      // "this->f") that was either written explicitly or created
3041      // implicitly. This can happen with a qualified call to a member
3042      // function, e.g., X::f(). We use an empty type for the implied
3043      // object argument (C++ [over.call.func]p3), and the acting context
3044      // is irrelevant.
3045      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
3046                         QualType(), Args, NumArgs, CandidateSet,
3047                         SuppressUserConversions);
3048      return;
3049    }
3050    // We treat a constructor like a non-member function, since its object
3051    // argument doesn't participate in overload resolution.
3052  }
3053
3054  if (!CandidateSet.isNewCandidate(Function))
3055    return;
3056
3057  // Overload resolution is always an unevaluated context.
3058  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3059
3060  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3061    // C++ [class.copy]p3:
3062    //   A member function template is never instantiated to perform the copy
3063    //   of a class object to an object of its class type.
3064    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3065    if (NumArgs == 1 &&
3066        Constructor->isCopyConstructorLikeSpecialization() &&
3067        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3068         IsDerivedFrom(Args[0]->getType(), ClassType)))
3069      return;
3070  }
3071
3072  // Add this candidate
3073  CandidateSet.push_back(OverloadCandidate());
3074  OverloadCandidate& Candidate = CandidateSet.back();
3075  Candidate.FoundDecl = FoundDecl;
3076  Candidate.Function = Function;
3077  Candidate.Viable = true;
3078  Candidate.IsSurrogate = false;
3079  Candidate.IgnoreObjectArgument = false;
3080
3081  unsigned NumArgsInProto = Proto->getNumArgs();
3082
3083  // (C++ 13.3.2p2): A candidate function having fewer than m
3084  // parameters is viable only if it has an ellipsis in its parameter
3085  // list (8.3.5).
3086  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3087      !Proto->isVariadic()) {
3088    Candidate.Viable = false;
3089    Candidate.FailureKind = ovl_fail_too_many_arguments;
3090    return;
3091  }
3092
3093  // (C++ 13.3.2p2): A candidate function having more than m parameters
3094  // is viable only if the (m+1)st parameter has a default argument
3095  // (8.3.6). For the purposes of overload resolution, the
3096  // parameter list is truncated on the right, so that there are
3097  // exactly m parameters.
3098  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
3099  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
3100    // Not enough arguments.
3101    Candidate.Viable = false;
3102    Candidate.FailureKind = ovl_fail_too_few_arguments;
3103    return;
3104  }
3105
3106  // Determine the implicit conversion sequences for each of the
3107  // arguments.
3108  Candidate.Conversions.resize(NumArgs);
3109  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3110    if (ArgIdx < NumArgsInProto) {
3111      // (C++ 13.3.2p3): for F to be a viable function, there shall
3112      // exist for each argument an implicit conversion sequence
3113      // (13.3.3.1) that converts that argument to the corresponding
3114      // parameter of F.
3115      QualType ParamType = Proto->getArgType(ArgIdx);
3116      Candidate.Conversions[ArgIdx]
3117        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
3118                                SuppressUserConversions,
3119                                /*InOverloadResolution=*/true);
3120      if (Candidate.Conversions[ArgIdx].isBad()) {
3121        Candidate.Viable = false;
3122        Candidate.FailureKind = ovl_fail_bad_conversion;
3123        break;
3124      }
3125    } else {
3126      // (C++ 13.3.2p2): For the purposes of overload resolution, any
3127      // argument for which there is no corresponding parameter is
3128      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
3129      Candidate.Conversions[ArgIdx].setEllipsis();
3130    }
3131  }
3132}
3133
3134/// \brief Add all of the function declarations in the given function set to
3135/// the overload canddiate set.
3136void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
3137                                 Expr **Args, unsigned NumArgs,
3138                                 OverloadCandidateSet& CandidateSet,
3139                                 bool SuppressUserConversions) {
3140  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
3141    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3142    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3143      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
3144        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
3145                           cast<CXXMethodDecl>(FD)->getParent(),
3146                           Args[0]->getType(), Args + 1, NumArgs - 1,
3147                           CandidateSet, SuppressUserConversions);
3148      else
3149        AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
3150                             SuppressUserConversions);
3151    } else {
3152      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
3153      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3154          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
3155        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
3156                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
3157                                   /*FIXME: explicit args */ 0,
3158                                   Args[0]->getType(), Args + 1, NumArgs - 1,
3159                                   CandidateSet,
3160                                   SuppressUserConversions);
3161      else
3162        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
3163                                     /*FIXME: explicit args */ 0,
3164                                     Args, NumArgs, CandidateSet,
3165                                     SuppressUserConversions);
3166    }
3167  }
3168}
3169
3170/// AddMethodCandidate - Adds a named decl (which is some kind of
3171/// method) as a method candidate to the given overload set.
3172void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
3173                              QualType ObjectType,
3174                              Expr **Args, unsigned NumArgs,
3175                              OverloadCandidateSet& CandidateSet,
3176                              bool SuppressUserConversions) {
3177  NamedDecl *Decl = FoundDecl.getDecl();
3178  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
3179
3180  if (isa<UsingShadowDecl>(Decl))
3181    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3182
3183  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3184    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3185           "Expected a member function template");
3186    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3187                               /*ExplicitArgs*/ 0,
3188                               ObjectType, Args, NumArgs,
3189                               CandidateSet,
3190                               SuppressUserConversions);
3191  } else {
3192    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
3193                       ObjectType, Args, NumArgs,
3194                       CandidateSet, SuppressUserConversions);
3195  }
3196}
3197
3198/// AddMethodCandidate - Adds the given C++ member function to the set
3199/// of candidate functions, using the given function call arguments
3200/// and the object argument (@c Object). For example, in a call
3201/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3202/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3203/// allow user-defined conversions via constructors or conversion
3204/// operators.
3205void
3206Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
3207                         CXXRecordDecl *ActingContext, QualType ObjectType,
3208                         Expr **Args, unsigned NumArgs,
3209                         OverloadCandidateSet& CandidateSet,
3210                         bool SuppressUserConversions) {
3211  const FunctionProtoType* Proto
3212    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
3213  assert(Proto && "Methods without a prototype cannot be overloaded");
3214  assert(!isa<CXXConstructorDecl>(Method) &&
3215         "Use AddOverloadCandidate for constructors");
3216
3217  if (!CandidateSet.isNewCandidate(Method))
3218    return;
3219
3220  // Overload resolution is always an unevaluated context.
3221  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3222
3223  // Add this candidate
3224  CandidateSet.push_back(OverloadCandidate());
3225  OverloadCandidate& Candidate = CandidateSet.back();
3226  Candidate.FoundDecl = FoundDecl;
3227  Candidate.Function = Method;
3228  Candidate.IsSurrogate = false;
3229  Candidate.IgnoreObjectArgument = false;
3230
3231  unsigned NumArgsInProto = Proto->getNumArgs();
3232
3233  // (C++ 13.3.2p2): A candidate function having fewer than m
3234  // parameters is viable only if it has an ellipsis in its parameter
3235  // list (8.3.5).
3236  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3237    Candidate.Viable = false;
3238    Candidate.FailureKind = ovl_fail_too_many_arguments;
3239    return;
3240  }
3241
3242  // (C++ 13.3.2p2): A candidate function having more than m parameters
3243  // is viable only if the (m+1)st parameter has a default argument
3244  // (8.3.6). For the purposes of overload resolution, the
3245  // parameter list is truncated on the right, so that there are
3246  // exactly m parameters.
3247  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3248  if (NumArgs < MinRequiredArgs) {
3249    // Not enough arguments.
3250    Candidate.Viable = false;
3251    Candidate.FailureKind = ovl_fail_too_few_arguments;
3252    return;
3253  }
3254
3255  Candidate.Viable = true;
3256  Candidate.Conversions.resize(NumArgs + 1);
3257
3258  if (Method->isStatic() || ObjectType.isNull())
3259    // The implicit object argument is ignored.
3260    Candidate.IgnoreObjectArgument = true;
3261  else {
3262    // Determine the implicit conversion sequence for the object
3263    // parameter.
3264    Candidate.Conversions[0]
3265      = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
3266    if (Candidate.Conversions[0].isBad()) {
3267      Candidate.Viable = false;
3268      Candidate.FailureKind = ovl_fail_bad_conversion;
3269      return;
3270    }
3271  }
3272
3273  // Determine the implicit conversion sequences for each of the
3274  // arguments.
3275  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3276    if (ArgIdx < NumArgsInProto) {
3277      // (C++ 13.3.2p3): for F to be a viable function, there shall
3278      // exist for each argument an implicit conversion sequence
3279      // (13.3.3.1) that converts that argument to the corresponding
3280      // parameter of F.
3281      QualType ParamType = Proto->getArgType(ArgIdx);
3282      Candidate.Conversions[ArgIdx + 1]
3283        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
3284                                SuppressUserConversions,
3285                                /*InOverloadResolution=*/true);
3286      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
3287        Candidate.Viable = false;
3288        Candidate.FailureKind = ovl_fail_bad_conversion;
3289        break;
3290      }
3291    } else {
3292      // (C++ 13.3.2p2): For the purposes of overload resolution, any
3293      // argument for which there is no corresponding parameter is
3294      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
3295      Candidate.Conversions[ArgIdx + 1].setEllipsis();
3296    }
3297  }
3298}
3299
3300/// \brief Add a C++ member function template as a candidate to the candidate
3301/// set, using template argument deduction to produce an appropriate member
3302/// function template specialization.
3303void
3304Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
3305                                 DeclAccessPair FoundDecl,
3306                                 CXXRecordDecl *ActingContext,
3307                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
3308                                 QualType ObjectType,
3309                                 Expr **Args, unsigned NumArgs,
3310                                 OverloadCandidateSet& CandidateSet,
3311                                 bool SuppressUserConversions) {
3312  if (!CandidateSet.isNewCandidate(MethodTmpl))
3313    return;
3314
3315  // C++ [over.match.funcs]p7:
3316  //   In each case where a candidate is a function template, candidate
3317  //   function template specializations are generated using template argument
3318  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
3319  //   candidate functions in the usual way.113) A given name can refer to one
3320  //   or more function templates and also to a set of overloaded non-template
3321  //   functions. In such a case, the candidate functions generated from each
3322  //   function template are combined with the set of non-template candidate
3323  //   functions.
3324  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
3325  FunctionDecl *Specialization = 0;
3326  if (TemplateDeductionResult Result
3327      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
3328                                Args, NumArgs, Specialization, Info)) {
3329    CandidateSet.push_back(OverloadCandidate());
3330    OverloadCandidate &Candidate = CandidateSet.back();
3331    Candidate.FoundDecl = FoundDecl;
3332    Candidate.Function = MethodTmpl->getTemplatedDecl();
3333    Candidate.Viable = false;
3334    Candidate.FailureKind = ovl_fail_bad_deduction;
3335    Candidate.IsSurrogate = false;
3336    Candidate.IgnoreObjectArgument = false;
3337    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3338                                                          Info);
3339    return;
3340  }
3341
3342  // Add the function template specialization produced by template argument
3343  // deduction as a candidate.
3344  assert(Specialization && "Missing member function template specialization?");
3345  assert(isa<CXXMethodDecl>(Specialization) &&
3346         "Specialization is not a member function?");
3347  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
3348                     ActingContext, ObjectType, Args, NumArgs,
3349                     CandidateSet, SuppressUserConversions);
3350}
3351
3352/// \brief Add a C++ function template specialization as a candidate
3353/// in the candidate set, using template argument deduction to produce
3354/// an appropriate function template specialization.
3355void
3356Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
3357                                   DeclAccessPair FoundDecl,
3358                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
3359                                   Expr **Args, unsigned NumArgs,
3360                                   OverloadCandidateSet& CandidateSet,
3361                                   bool SuppressUserConversions) {
3362  if (!CandidateSet.isNewCandidate(FunctionTemplate))
3363    return;
3364
3365  // C++ [over.match.funcs]p7:
3366  //   In each case where a candidate is a function template, candidate
3367  //   function template specializations are generated using template argument
3368  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
3369  //   candidate functions in the usual way.113) A given name can refer to one
3370  //   or more function templates and also to a set of overloaded non-template
3371  //   functions. In such a case, the candidate functions generated from each
3372  //   function template are combined with the set of non-template candidate
3373  //   functions.
3374  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
3375  FunctionDecl *Specialization = 0;
3376  if (TemplateDeductionResult Result
3377        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
3378                                  Args, NumArgs, Specialization, Info)) {
3379    CandidateSet.push_back(OverloadCandidate());
3380    OverloadCandidate &Candidate = CandidateSet.back();
3381    Candidate.FoundDecl = FoundDecl;
3382    Candidate.Function = FunctionTemplate->getTemplatedDecl();
3383    Candidate.Viable = false;
3384    Candidate.FailureKind = ovl_fail_bad_deduction;
3385    Candidate.IsSurrogate = false;
3386    Candidate.IgnoreObjectArgument = false;
3387    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3388                                                          Info);
3389    return;
3390  }
3391
3392  // Add the function template specialization produced by template argument
3393  // deduction as a candidate.
3394  assert(Specialization && "Missing function template specialization?");
3395  AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
3396                       SuppressUserConversions);
3397}
3398
3399/// AddConversionCandidate - Add a C++ conversion function as a
3400/// candidate in the candidate set (C++ [over.match.conv],
3401/// C++ [over.match.copy]). From is the expression we're converting from,
3402/// and ToType is the type that we're eventually trying to convert to
3403/// (which may or may not be the same type as the type that the
3404/// conversion function produces).
3405void
3406Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
3407                             DeclAccessPair FoundDecl,
3408                             CXXRecordDecl *ActingContext,
3409                             Expr *From, QualType ToType,
3410                             OverloadCandidateSet& CandidateSet) {
3411  assert(!Conversion->getDescribedFunctionTemplate() &&
3412         "Conversion function templates use AddTemplateConversionCandidate");
3413  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
3414  if (!CandidateSet.isNewCandidate(Conversion))
3415    return;
3416
3417  // Overload resolution is always an unevaluated context.
3418  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3419
3420  // Add this candidate
3421  CandidateSet.push_back(OverloadCandidate());
3422  OverloadCandidate& Candidate = CandidateSet.back();
3423  Candidate.FoundDecl = FoundDecl;
3424  Candidate.Function = Conversion;
3425  Candidate.IsSurrogate = false;
3426  Candidate.IgnoreObjectArgument = false;
3427  Candidate.FinalConversion.setAsIdentityConversion();
3428  Candidate.FinalConversion.setFromType(ConvType);
3429  Candidate.FinalConversion.setAllToTypes(ToType);
3430
3431  // Determine the implicit conversion sequence for the implicit
3432  // object parameter.
3433  Candidate.Viable = true;
3434  Candidate.Conversions.resize(1);
3435  Candidate.Conversions[0]
3436    = TryObjectArgumentInitialization(From->getType(), Conversion,
3437                                      ActingContext);
3438  // Conversion functions to a different type in the base class is visible in
3439  // the derived class.  So, a derived to base conversion should not participate
3440  // in overload resolution.
3441  if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3442    Candidate.Conversions[0].Standard.Second = ICK_Identity;
3443  if (Candidate.Conversions[0].isBad()) {
3444    Candidate.Viable = false;
3445    Candidate.FailureKind = ovl_fail_bad_conversion;
3446    return;
3447  }
3448
3449  // We won't go through a user-define type conversion function to convert a
3450  // derived to base as such conversions are given Conversion Rank. They only
3451  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3452  QualType FromCanon
3453    = Context.getCanonicalType(From->getType().getUnqualifiedType());
3454  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3455  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3456    Candidate.Viable = false;
3457    Candidate.FailureKind = ovl_fail_trivial_conversion;
3458    return;
3459  }
3460
3461  // To determine what the conversion from the result of calling the
3462  // conversion function to the type we're eventually trying to
3463  // convert to (ToType), we need to synthesize a call to the
3464  // conversion function and attempt copy initialization from it. This
3465  // makes sure that we get the right semantics with respect to
3466  // lvalues/rvalues and the type. Fortunately, we can allocate this
3467  // call on the stack and we don't need its arguments to be
3468  // well-formed.
3469  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
3470                            From->getLocStart());
3471  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
3472                                CastExpr::CK_FunctionToPointerDecay,
3473                                &ConversionRef, CXXBaseSpecifierArray(), false);
3474
3475  // Note that it is safe to allocate CallExpr on the stack here because
3476  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3477  // allocator).
3478  CallExpr Call(Context, &ConversionFn, 0, 0,
3479                Conversion->getConversionType().getNonReferenceType(),
3480                From->getLocStart());
3481  ImplicitConversionSequence ICS =
3482    TryCopyInitialization(*this, &Call, ToType,
3483                          /*SuppressUserConversions=*/true,
3484                          /*InOverloadResolution=*/false);
3485
3486  switch (ICS.getKind()) {
3487  case ImplicitConversionSequence::StandardConversion:
3488    Candidate.FinalConversion = ICS.Standard;
3489
3490    // C++ [over.ics.user]p3:
3491    //   If the user-defined conversion is specified by a specialization of a
3492    //   conversion function template, the second standard conversion sequence
3493    //   shall have exact match rank.
3494    if (Conversion->getPrimaryTemplate() &&
3495        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3496      Candidate.Viable = false;
3497      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3498    }
3499
3500    break;
3501
3502  case ImplicitConversionSequence::BadConversion:
3503    Candidate.Viable = false;
3504    Candidate.FailureKind = ovl_fail_bad_final_conversion;
3505    break;
3506
3507  default:
3508    assert(false &&
3509           "Can only end up with a standard conversion sequence or failure");
3510  }
3511}
3512
3513/// \brief Adds a conversion function template specialization
3514/// candidate to the overload set, using template argument deduction
3515/// to deduce the template arguments of the conversion function
3516/// template from the type that we are converting to (C++
3517/// [temp.deduct.conv]).
3518void
3519Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
3520                                     DeclAccessPair FoundDecl,
3521                                     CXXRecordDecl *ActingDC,
3522                                     Expr *From, QualType ToType,
3523                                     OverloadCandidateSet &CandidateSet) {
3524  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3525         "Only conversion function templates permitted here");
3526
3527  if (!CandidateSet.isNewCandidate(FunctionTemplate))
3528    return;
3529
3530  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
3531  CXXConversionDecl *Specialization = 0;
3532  if (TemplateDeductionResult Result
3533        = DeduceTemplateArguments(FunctionTemplate, ToType,
3534                                  Specialization, Info)) {
3535    CandidateSet.push_back(OverloadCandidate());
3536    OverloadCandidate &Candidate = CandidateSet.back();
3537    Candidate.FoundDecl = FoundDecl;
3538    Candidate.Function = FunctionTemplate->getTemplatedDecl();
3539    Candidate.Viable = false;
3540    Candidate.FailureKind = ovl_fail_bad_deduction;
3541    Candidate.IsSurrogate = false;
3542    Candidate.IgnoreObjectArgument = false;
3543    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3544                                                          Info);
3545    return;
3546  }
3547
3548  // Add the conversion function template specialization produced by
3549  // template argument deduction as a candidate.
3550  assert(Specialization && "Missing function template specialization?");
3551  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
3552                         CandidateSet);
3553}
3554
3555/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3556/// converts the given @c Object to a function pointer via the
3557/// conversion function @c Conversion, and then attempts to call it
3558/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3559/// the type of function that we'll eventually be calling.
3560void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
3561                                 DeclAccessPair FoundDecl,
3562                                 CXXRecordDecl *ActingContext,
3563                                 const FunctionProtoType *Proto,
3564                                 QualType ObjectType,
3565                                 Expr **Args, unsigned NumArgs,
3566                                 OverloadCandidateSet& CandidateSet) {
3567  if (!CandidateSet.isNewCandidate(Conversion))
3568    return;
3569
3570  // Overload resolution is always an unevaluated context.
3571  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3572
3573  CandidateSet.push_back(OverloadCandidate());
3574  OverloadCandidate& Candidate = CandidateSet.back();
3575  Candidate.FoundDecl = FoundDecl;
3576  Candidate.Function = 0;
3577  Candidate.Surrogate = Conversion;
3578  Candidate.Viable = true;
3579  Candidate.IsSurrogate = true;
3580  Candidate.IgnoreObjectArgument = false;
3581  Candidate.Conversions.resize(NumArgs + 1);
3582
3583  // Determine the implicit conversion sequence for the implicit
3584  // object parameter.
3585  ImplicitConversionSequence ObjectInit
3586    = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
3587  if (ObjectInit.isBad()) {
3588    Candidate.Viable = false;
3589    Candidate.FailureKind = ovl_fail_bad_conversion;
3590    Candidate.Conversions[0] = ObjectInit;
3591    return;
3592  }
3593
3594  // The first conversion is actually a user-defined conversion whose
3595  // first conversion is ObjectInit's standard conversion (which is
3596  // effectively a reference binding). Record it as such.
3597  Candidate.Conversions[0].setUserDefined();
3598  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
3599  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
3600  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
3601  Candidate.Conversions[0].UserDefined.After
3602    = Candidate.Conversions[0].UserDefined.Before;
3603  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3604
3605  // Find the
3606  unsigned NumArgsInProto = Proto->getNumArgs();
3607
3608  // (C++ 13.3.2p2): A candidate function having fewer than m
3609  // parameters is viable only if it has an ellipsis in its parameter
3610  // list (8.3.5).
3611  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3612    Candidate.Viable = false;
3613    Candidate.FailureKind = ovl_fail_too_many_arguments;
3614    return;
3615  }
3616
3617  // Function types don't have any default arguments, so just check if
3618  // we have enough arguments.
3619  if (NumArgs < NumArgsInProto) {
3620    // Not enough arguments.
3621    Candidate.Viable = false;
3622    Candidate.FailureKind = ovl_fail_too_few_arguments;
3623    return;
3624  }
3625
3626  // Determine the implicit conversion sequences for each of the
3627  // arguments.
3628  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3629    if (ArgIdx < NumArgsInProto) {
3630      // (C++ 13.3.2p3): for F to be a viable function, there shall
3631      // exist for each argument an implicit conversion sequence
3632      // (13.3.3.1) that converts that argument to the corresponding
3633      // parameter of F.
3634      QualType ParamType = Proto->getArgType(ArgIdx);
3635      Candidate.Conversions[ArgIdx + 1]
3636        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
3637                                /*SuppressUserConversions=*/false,
3638                                /*InOverloadResolution=*/false);
3639      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
3640        Candidate.Viable = false;
3641        Candidate.FailureKind = ovl_fail_bad_conversion;
3642        break;
3643      }
3644    } else {
3645      // (C++ 13.3.2p2): For the purposes of overload resolution, any
3646      // argument for which there is no corresponding parameter is
3647      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
3648      Candidate.Conversions[ArgIdx + 1].setEllipsis();
3649    }
3650  }
3651}
3652
3653/// \brief Add overload candidates for overloaded operators that are
3654/// member functions.
3655///
3656/// Add the overloaded operator candidates that are member functions
3657/// for the operator Op that was used in an operator expression such
3658/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3659/// CandidateSet will store the added overload candidates. (C++
3660/// [over.match.oper]).
3661void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3662                                       SourceLocation OpLoc,
3663                                       Expr **Args, unsigned NumArgs,
3664                                       OverloadCandidateSet& CandidateSet,
3665                                       SourceRange OpRange) {
3666  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3667
3668  // C++ [over.match.oper]p3:
3669  //   For a unary operator @ with an operand of a type whose
3670  //   cv-unqualified version is T1, and for a binary operator @ with
3671  //   a left operand of a type whose cv-unqualified version is T1 and
3672  //   a right operand of a type whose cv-unqualified version is T2,
3673  //   three sets of candidate functions, designated member
3674  //   candidates, non-member candidates and built-in candidates, are
3675  //   constructed as follows:
3676  QualType T1 = Args[0]->getType();
3677  QualType T2;
3678  if (NumArgs > 1)
3679    T2 = Args[1]->getType();
3680
3681  //     -- If T1 is a class type, the set of member candidates is the
3682  //        result of the qualified lookup of T1::operator@
3683  //        (13.3.1.1.1); otherwise, the set of member candidates is
3684  //        empty.
3685  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
3686    // Complete the type if it can be completed. Otherwise, we're done.
3687    if (RequireCompleteType(OpLoc, T1, PDiag()))
3688      return;
3689
3690    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3691    LookupQualifiedName(Operators, T1Rec->getDecl());
3692    Operators.suppressDiagnostics();
3693
3694    for (LookupResult::iterator Oper = Operators.begin(),
3695                             OperEnd = Operators.end();
3696         Oper != OperEnd;
3697         ++Oper)
3698      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
3699                         Args + 1, NumArgs - 1, CandidateSet,
3700                         /* SuppressUserConversions = */ false);
3701  }
3702}
3703
3704/// AddBuiltinCandidate - Add a candidate for a built-in
3705/// operator. ResultTy and ParamTys are the result and parameter types
3706/// of the built-in candidate, respectively. Args and NumArgs are the
3707/// arguments being passed to the candidate. IsAssignmentOperator
3708/// should be true when this built-in candidate is an assignment
3709/// operator. NumContextualBoolArguments is the number of arguments
3710/// (at the beginning of the argument list) that will be contextually
3711/// converted to bool.
3712void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
3713                               Expr **Args, unsigned NumArgs,
3714                               OverloadCandidateSet& CandidateSet,
3715                               bool IsAssignmentOperator,
3716                               unsigned NumContextualBoolArguments) {
3717  // Overload resolution is always an unevaluated context.
3718  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3719
3720  // Add this candidate
3721  CandidateSet.push_back(OverloadCandidate());
3722  OverloadCandidate& Candidate = CandidateSet.back();
3723  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
3724  Candidate.Function = 0;
3725  Candidate.IsSurrogate = false;
3726  Candidate.IgnoreObjectArgument = false;
3727  Candidate.BuiltinTypes.ResultTy = ResultTy;
3728  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3729    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3730
3731  // Determine the implicit conversion sequences for each of the
3732  // arguments.
3733  Candidate.Viable = true;
3734  Candidate.Conversions.resize(NumArgs);
3735  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3736    // C++ [over.match.oper]p4:
3737    //   For the built-in assignment operators, conversions of the
3738    //   left operand are restricted as follows:
3739    //     -- no temporaries are introduced to hold the left operand, and
3740    //     -- no user-defined conversions are applied to the left
3741    //        operand to achieve a type match with the left-most
3742    //        parameter of a built-in candidate.
3743    //
3744    // We block these conversions by turning off user-defined
3745    // conversions, since that is the only way that initialization of
3746    // a reference to a non-class type can occur from something that
3747    // is not of the same type.
3748    if (ArgIdx < NumContextualBoolArguments) {
3749      assert(ParamTys[ArgIdx] == Context.BoolTy &&
3750             "Contextual conversion to bool requires bool type");
3751      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3752    } else {
3753      Candidate.Conversions[ArgIdx]
3754        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
3755                                ArgIdx == 0 && IsAssignmentOperator,
3756                                /*InOverloadResolution=*/false);
3757    }
3758    if (Candidate.Conversions[ArgIdx].isBad()) {
3759      Candidate.Viable = false;
3760      Candidate.FailureKind = ovl_fail_bad_conversion;
3761      break;
3762    }
3763  }
3764}
3765
3766/// BuiltinCandidateTypeSet - A set of types that will be used for the
3767/// candidate operator functions for built-in operators (C++
3768/// [over.built]). The types are separated into pointer types and
3769/// enumeration types.
3770class BuiltinCandidateTypeSet  {
3771  /// TypeSet - A set of types.
3772  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
3773
3774  /// PointerTypes - The set of pointer types that will be used in the
3775  /// built-in candidates.
3776  TypeSet PointerTypes;
3777
3778  /// MemberPointerTypes - The set of member pointer types that will be
3779  /// used in the built-in candidates.
3780  TypeSet MemberPointerTypes;
3781
3782  /// EnumerationTypes - The set of enumeration types that will be
3783  /// used in the built-in candidates.
3784  TypeSet EnumerationTypes;
3785
3786  /// \brief The set of vector types that will be used in the built-in
3787  /// candidates.
3788  TypeSet VectorTypes;
3789
3790  /// Sema - The semantic analysis instance where we are building the
3791  /// candidate type set.
3792  Sema &SemaRef;
3793
3794  /// Context - The AST context in which we will build the type sets.
3795  ASTContext &Context;
3796
3797  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3798                                               const Qualifiers &VisibleQuals);
3799  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
3800
3801public:
3802  /// iterator - Iterates through the types that are part of the set.
3803  typedef TypeSet::iterator iterator;
3804
3805  BuiltinCandidateTypeSet(Sema &SemaRef)
3806    : SemaRef(SemaRef), Context(SemaRef.Context) { }
3807
3808  void AddTypesConvertedFrom(QualType Ty,
3809                             SourceLocation Loc,
3810                             bool AllowUserConversions,
3811                             bool AllowExplicitConversions,
3812                             const Qualifiers &VisibleTypeConversionsQuals);
3813
3814  /// pointer_begin - First pointer type found;
3815  iterator pointer_begin() { return PointerTypes.begin(); }
3816
3817  /// pointer_end - Past the last pointer type found;
3818  iterator pointer_end() { return PointerTypes.end(); }
3819
3820  /// member_pointer_begin - First member pointer type found;
3821  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3822
3823  /// member_pointer_end - Past the last member pointer type found;
3824  iterator member_pointer_end() { return MemberPointerTypes.end(); }
3825
3826  /// enumeration_begin - First enumeration type found;
3827  iterator enumeration_begin() { return EnumerationTypes.begin(); }
3828
3829  /// enumeration_end - Past the last enumeration type found;
3830  iterator enumeration_end() { return EnumerationTypes.end(); }
3831
3832  iterator vector_begin() { return VectorTypes.begin(); }
3833  iterator vector_end() { return VectorTypes.end(); }
3834};
3835
3836/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
3837/// the set of pointer types along with any more-qualified variants of
3838/// that type. For example, if @p Ty is "int const *", this routine
3839/// will add "int const *", "int const volatile *", "int const
3840/// restrict *", and "int const volatile restrict *" to the set of
3841/// pointer types. Returns true if the add of @p Ty itself succeeded,
3842/// false otherwise.
3843///
3844/// FIXME: what to do about extended qualifiers?
3845bool
3846BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3847                                             const Qualifiers &VisibleQuals) {
3848
3849  // Insert this type.
3850  if (!PointerTypes.insert(Ty))
3851    return false;
3852
3853  const PointerType *PointerTy = Ty->getAs<PointerType>();
3854  assert(PointerTy && "type was not a pointer type!");
3855
3856  QualType PointeeTy = PointerTy->getPointeeType();
3857  // Don't add qualified variants of arrays. For one, they're not allowed
3858  // (the qualifier would sink to the element type), and for another, the
3859  // only overload situation where it matters is subscript or pointer +- int,
3860  // and those shouldn't have qualifier variants anyway.
3861  if (PointeeTy->isArrayType())
3862    return true;
3863  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3864  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
3865    BaseCVR = Array->getElementType().getCVRQualifiers();
3866  bool hasVolatile = VisibleQuals.hasVolatile();
3867  bool hasRestrict = VisibleQuals.hasRestrict();
3868
3869  // Iterate through all strict supersets of BaseCVR.
3870  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3871    if ((CVR | BaseCVR) != CVR) continue;
3872    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3873    // in the types.
3874    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3875    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
3876    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3877    PointerTypes.insert(Context.getPointerType(QPointeeTy));
3878  }
3879
3880  return true;
3881}
3882
3883/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3884/// to the set of pointer types along with any more-qualified variants of
3885/// that type. For example, if @p Ty is "int const *", this routine
3886/// will add "int const *", "int const volatile *", "int const
3887/// restrict *", and "int const volatile restrict *" to the set of
3888/// pointer types. Returns true if the add of @p Ty itself succeeded,
3889/// false otherwise.
3890///
3891/// FIXME: what to do about extended qualifiers?
3892bool
3893BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3894    QualType Ty) {
3895  // Insert this type.
3896  if (!MemberPointerTypes.insert(Ty))
3897    return false;
3898
3899  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3900  assert(PointerTy && "type was not a member pointer type!");
3901
3902  QualType PointeeTy = PointerTy->getPointeeType();
3903  // Don't add qualified variants of arrays. For one, they're not allowed
3904  // (the qualifier would sink to the element type), and for another, the
3905  // only overload situation where it matters is subscript or pointer +- int,
3906  // and those shouldn't have qualifier variants anyway.
3907  if (PointeeTy->isArrayType())
3908    return true;
3909  const Type *ClassTy = PointerTy->getClass();
3910
3911  // Iterate through all strict supersets of the pointee type's CVR
3912  // qualifiers.
3913  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3914  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3915    if ((CVR | BaseCVR) != CVR) continue;
3916
3917    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3918    MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
3919  }
3920
3921  return true;
3922}
3923
3924/// AddTypesConvertedFrom - Add each of the types to which the type @p
3925/// Ty can be implicit converted to the given set of @p Types. We're
3926/// primarily interested in pointer types and enumeration types. We also
3927/// take member pointer types, for the conditional operator.
3928/// AllowUserConversions is true if we should look at the conversion
3929/// functions of a class type, and AllowExplicitConversions if we
3930/// should also include the explicit conversion functions of a class
3931/// type.
3932void
3933BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
3934                                               SourceLocation Loc,
3935                                               bool AllowUserConversions,
3936                                               bool AllowExplicitConversions,
3937                                               const Qualifiers &VisibleQuals) {
3938  // Only deal with canonical types.
3939  Ty = Context.getCanonicalType(Ty);
3940
3941  // Look through reference types; they aren't part of the type of an
3942  // expression for the purposes of conversions.
3943  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
3944    Ty = RefTy->getPointeeType();
3945
3946  // We don't care about qualifiers on the type.
3947  Ty = Ty.getLocalUnqualifiedType();
3948
3949  // If we're dealing with an array type, decay to the pointer.
3950  if (Ty->isArrayType())
3951    Ty = SemaRef.Context.getArrayDecayedType(Ty);
3952
3953  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
3954    QualType PointeeTy = PointerTy->getPointeeType();
3955
3956    // Insert our type, and its more-qualified variants, into the set
3957    // of types.
3958    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
3959      return;
3960  } else if (Ty->isMemberPointerType()) {
3961    // Member pointers are far easier, since the pointee can't be converted.
3962    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3963      return;
3964  } else if (Ty->isEnumeralType()) {
3965    EnumerationTypes.insert(Ty);
3966  } else if (Ty->isVectorType()) {
3967    VectorTypes.insert(Ty);
3968  } else if (AllowUserConversions) {
3969    if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
3970      if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
3971        // No conversion functions in incomplete types.
3972        return;
3973      }
3974
3975      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3976      const UnresolvedSetImpl *Conversions
3977        = ClassDecl->getVisibleConversionFunctions();
3978      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3979             E = Conversions->end(); I != E; ++I) {
3980        NamedDecl *D = I.getDecl();
3981        if (isa<UsingShadowDecl>(D))
3982          D = cast<UsingShadowDecl>(D)->getTargetDecl();
3983
3984        // Skip conversion function templates; they don't tell us anything
3985        // about which builtin types we can convert to.
3986        if (isa<FunctionTemplateDecl>(D))
3987          continue;
3988
3989        CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
3990        if (AllowExplicitConversions || !Conv->isExplicit()) {
3991          AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
3992                                VisibleQuals);
3993        }
3994      }
3995    }
3996  }
3997}
3998
3999/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4000/// the volatile- and non-volatile-qualified assignment operators for the
4001/// given type to the candidate set.
4002static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4003                                                   QualType T,
4004                                                   Expr **Args,
4005                                                   unsigned NumArgs,
4006                                    OverloadCandidateSet &CandidateSet) {
4007  QualType ParamTypes[2];
4008
4009  // T& operator=(T&, T)
4010  ParamTypes[0] = S.Context.getLValueReferenceType(T);
4011  ParamTypes[1] = T;
4012  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4013                        /*IsAssignmentOperator=*/true);
4014
4015  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4016    // volatile T& operator=(volatile T&, T)
4017    ParamTypes[0]
4018      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
4019    ParamTypes[1] = T;
4020    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4021                          /*IsAssignmentOperator=*/true);
4022  }
4023}
4024
4025/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4026/// if any, found in visible type conversion functions found in ArgExpr's type.
4027static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4028    Qualifiers VRQuals;
4029    const RecordType *TyRec;
4030    if (const MemberPointerType *RHSMPType =
4031        ArgExpr->getType()->getAs<MemberPointerType>())
4032      TyRec = RHSMPType->getClass()->getAs<RecordType>();
4033    else
4034      TyRec = ArgExpr->getType()->getAs<RecordType>();
4035    if (!TyRec) {
4036      // Just to be safe, assume the worst case.
4037      VRQuals.addVolatile();
4038      VRQuals.addRestrict();
4039      return VRQuals;
4040    }
4041
4042    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4043    if (!ClassDecl->hasDefinition())
4044      return VRQuals;
4045
4046    const UnresolvedSetImpl *Conversions =
4047      ClassDecl->getVisibleConversionFunctions();
4048
4049    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4050           E = Conversions->end(); I != E; ++I) {
4051      NamedDecl *D = I.getDecl();
4052      if (isa<UsingShadowDecl>(D))
4053        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4054      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
4055        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4056        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4057          CanTy = ResTypeRef->getPointeeType();
4058        // Need to go down the pointer/mempointer chain and add qualifiers
4059        // as see them.
4060        bool done = false;
4061        while (!done) {
4062          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4063            CanTy = ResTypePtr->getPointeeType();
4064          else if (const MemberPointerType *ResTypeMPtr =
4065                CanTy->getAs<MemberPointerType>())
4066            CanTy = ResTypeMPtr->getPointeeType();
4067          else
4068            done = true;
4069          if (CanTy.isVolatileQualified())
4070            VRQuals.addVolatile();
4071          if (CanTy.isRestrictQualified())
4072            VRQuals.addRestrict();
4073          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4074            return VRQuals;
4075        }
4076      }
4077    }
4078    return VRQuals;
4079}
4080
4081/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4082/// operator overloads to the candidate set (C++ [over.built]), based
4083/// on the operator @p Op and the arguments given. For example, if the
4084/// operator is a binary '+', this routine might add "int
4085/// operator+(int, int)" to cover integer addition.
4086void
4087Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
4088                                   SourceLocation OpLoc,
4089                                   Expr **Args, unsigned NumArgs,
4090                                   OverloadCandidateSet& CandidateSet) {
4091  // The set of "promoted arithmetic types", which are the arithmetic
4092  // types are that preserved by promotion (C++ [over.built]p2). Note
4093  // that the first few of these types are the promoted integral
4094  // types; these types need to be first.
4095  // FIXME: What about complex?
4096  const unsigned FirstIntegralType = 0;
4097  const unsigned LastIntegralType = 13;
4098  const unsigned FirstPromotedIntegralType = 7,
4099                 LastPromotedIntegralType = 13;
4100  const unsigned FirstPromotedArithmeticType = 7,
4101                 LastPromotedArithmeticType = 16;
4102  const unsigned NumArithmeticTypes = 16;
4103  QualType ArithmeticTypes[NumArithmeticTypes] = {
4104    Context.BoolTy, Context.CharTy, Context.WCharTy,
4105// FIXME:   Context.Char16Ty, Context.Char32Ty,
4106    Context.SignedCharTy, Context.ShortTy,
4107    Context.UnsignedCharTy, Context.UnsignedShortTy,
4108    Context.IntTy, Context.LongTy, Context.LongLongTy,
4109    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4110    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4111  };
4112  assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4113         "Invalid first promoted integral type");
4114  assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4115           == Context.UnsignedLongLongTy &&
4116         "Invalid last promoted integral type");
4117  assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4118         "Invalid first promoted arithmetic type");
4119  assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4120            == Context.LongDoubleTy &&
4121         "Invalid last promoted arithmetic type");
4122
4123  // Find all of the types that the arguments can convert to, but only
4124  // if the operator we're looking at has built-in operator candidates
4125  // that make use of these types.
4126  Qualifiers VisibleTypeConversionsQuals;
4127  VisibleTypeConversionsQuals.addConst();
4128  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4129    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4130
4131  BuiltinCandidateTypeSet CandidateTypes(*this);
4132  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4133    CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4134                                         OpLoc,
4135                                         true,
4136                                         (Op == OO_Exclaim ||
4137                                          Op == OO_AmpAmp ||
4138                                          Op == OO_PipePipe),
4139                                         VisibleTypeConversionsQuals);
4140
4141  bool isComparison = false;
4142  switch (Op) {
4143  case OO_None:
4144  case NUM_OVERLOADED_OPERATORS:
4145    assert(false && "Expected an overloaded operator");
4146    break;
4147
4148  case OO_Star: // '*' is either unary or binary
4149    if (NumArgs == 1)
4150      goto UnaryStar;
4151    else
4152      goto BinaryStar;
4153    break;
4154
4155  case OO_Plus: // '+' is either unary or binary
4156    if (NumArgs == 1)
4157      goto UnaryPlus;
4158    else
4159      goto BinaryPlus;
4160    break;
4161
4162  case OO_Minus: // '-' is either unary or binary
4163    if (NumArgs == 1)
4164      goto UnaryMinus;
4165    else
4166      goto BinaryMinus;
4167    break;
4168
4169  case OO_Amp: // '&' is either unary or binary
4170    if (NumArgs == 1)
4171      goto UnaryAmp;
4172    else
4173      goto BinaryAmp;
4174
4175  case OO_PlusPlus:
4176  case OO_MinusMinus:
4177    // C++ [over.built]p3:
4178    //
4179    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
4180    //   is either volatile or empty, there exist candidate operator
4181    //   functions of the form
4182    //
4183    //       VQ T&      operator++(VQ T&);
4184    //       T          operator++(VQ T&, int);
4185    //
4186    // C++ [over.built]p4:
4187    //
4188    //   For every pair (T, VQ), where T is an arithmetic type other
4189    //   than bool, and VQ is either volatile or empty, there exist
4190    //   candidate operator functions of the form
4191    //
4192    //       VQ T&      operator--(VQ T&);
4193    //       T          operator--(VQ T&, int);
4194    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4195         Arith < NumArithmeticTypes; ++Arith) {
4196      QualType ArithTy = ArithmeticTypes[Arith];
4197      QualType ParamTypes[2]
4198        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
4199
4200      // Non-volatile version.
4201      if (NumArgs == 1)
4202        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4203      else
4204        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4205      // heuristic to reduce number of builtin candidates in the set.
4206      // Add volatile version only if there are conversions to a volatile type.
4207      if (VisibleTypeConversionsQuals.hasVolatile()) {
4208        // Volatile version
4209        ParamTypes[0]
4210          = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4211        if (NumArgs == 1)
4212          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4213        else
4214          AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4215      }
4216    }
4217
4218    // C++ [over.built]p5:
4219    //
4220    //   For every pair (T, VQ), where T is a cv-qualified or
4221    //   cv-unqualified object type, and VQ is either volatile or
4222    //   empty, there exist candidate operator functions of the form
4223    //
4224    //       T*VQ&      operator++(T*VQ&);
4225    //       T*VQ&      operator--(T*VQ&);
4226    //       T*         operator++(T*VQ&, int);
4227    //       T*         operator--(T*VQ&, int);
4228    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4229         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4230      // Skip pointer types that aren't pointers to object types.
4231      if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
4232        continue;
4233
4234      QualType ParamTypes[2] = {
4235        Context.getLValueReferenceType(*Ptr), Context.IntTy
4236      };
4237
4238      // Without volatile
4239      if (NumArgs == 1)
4240        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4241      else
4242        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4243
4244      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4245          VisibleTypeConversionsQuals.hasVolatile()) {
4246        // With volatile
4247        ParamTypes[0]
4248          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
4249        if (NumArgs == 1)
4250          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4251        else
4252          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4253      }
4254    }
4255    break;
4256
4257  UnaryStar:
4258    // C++ [over.built]p6:
4259    //   For every cv-qualified or cv-unqualified object type T, there
4260    //   exist candidate operator functions of the form
4261    //
4262    //       T&         operator*(T*);
4263    //
4264    // C++ [over.built]p7:
4265    //   For every function type T, there exist candidate operator
4266    //   functions of the form
4267    //       T&         operator*(T*);
4268    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4269         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4270      QualType ParamTy = *Ptr;
4271      QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
4272      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
4273                          &ParamTy, Args, 1, CandidateSet);
4274    }
4275    break;
4276
4277  UnaryPlus:
4278    // C++ [over.built]p8:
4279    //   For every type T, there exist candidate operator functions of
4280    //   the form
4281    //
4282    //       T*         operator+(T*);
4283    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4284         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4285      QualType ParamTy = *Ptr;
4286      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4287    }
4288
4289    // Fall through
4290
4291  UnaryMinus:
4292    // C++ [over.built]p9:
4293    //  For every promoted arithmetic type T, there exist candidate
4294    //  operator functions of the form
4295    //
4296    //       T         operator+(T);
4297    //       T         operator-(T);
4298    for (unsigned Arith = FirstPromotedArithmeticType;
4299         Arith < LastPromotedArithmeticType; ++Arith) {
4300      QualType ArithTy = ArithmeticTypes[Arith];
4301      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4302    }
4303
4304    // Extension: We also add these operators for vector types.
4305    for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4306                                        VecEnd = CandidateTypes.vector_end();
4307         Vec != VecEnd; ++Vec) {
4308      QualType VecTy = *Vec;
4309      AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4310    }
4311    break;
4312
4313  case OO_Tilde:
4314    // C++ [over.built]p10:
4315    //   For every promoted integral type T, there exist candidate
4316    //   operator functions of the form
4317    //
4318    //        T         operator~(T);
4319    for (unsigned Int = FirstPromotedIntegralType;
4320         Int < LastPromotedIntegralType; ++Int) {
4321      QualType IntTy = ArithmeticTypes[Int];
4322      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4323    }
4324
4325    // Extension: We also add this operator for vector types.
4326    for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4327                                        VecEnd = CandidateTypes.vector_end();
4328         Vec != VecEnd; ++Vec) {
4329      QualType VecTy = *Vec;
4330      AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4331    }
4332    break;
4333
4334  case OO_New:
4335  case OO_Delete:
4336  case OO_Array_New:
4337  case OO_Array_Delete:
4338  case OO_Call:
4339    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
4340    break;
4341
4342  case OO_Comma:
4343  UnaryAmp:
4344  case OO_Arrow:
4345    // C++ [over.match.oper]p3:
4346    //   -- For the operator ',', the unary operator '&', or the
4347    //      operator '->', the built-in candidates set is empty.
4348    break;
4349
4350  case OO_EqualEqual:
4351  case OO_ExclaimEqual:
4352    // C++ [over.match.oper]p16:
4353    //   For every pointer to member type T, there exist candidate operator
4354    //   functions of the form
4355    //
4356    //        bool operator==(T,T);
4357    //        bool operator!=(T,T);
4358    for (BuiltinCandidateTypeSet::iterator
4359           MemPtr = CandidateTypes.member_pointer_begin(),
4360           MemPtrEnd = CandidateTypes.member_pointer_end();
4361         MemPtr != MemPtrEnd;
4362         ++MemPtr) {
4363      QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4364      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4365    }
4366
4367    // Fall through
4368
4369  case OO_Less:
4370  case OO_Greater:
4371  case OO_LessEqual:
4372  case OO_GreaterEqual:
4373    // C++ [over.built]p15:
4374    //
4375    //   For every pointer or enumeration type T, there exist
4376    //   candidate operator functions of the form
4377    //
4378    //        bool       operator<(T, T);
4379    //        bool       operator>(T, T);
4380    //        bool       operator<=(T, T);
4381    //        bool       operator>=(T, T);
4382    //        bool       operator==(T, T);
4383    //        bool       operator!=(T, T);
4384    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4385         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4386      QualType ParamTypes[2] = { *Ptr, *Ptr };
4387      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4388    }
4389    for (BuiltinCandidateTypeSet::iterator Enum
4390           = CandidateTypes.enumeration_begin();
4391         Enum != CandidateTypes.enumeration_end(); ++Enum) {
4392      QualType ParamTypes[2] = { *Enum, *Enum };
4393      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4394    }
4395
4396    // Fall through.
4397    isComparison = true;
4398
4399  BinaryPlus:
4400  BinaryMinus:
4401    if (!isComparison) {
4402      // We didn't fall through, so we must have OO_Plus or OO_Minus.
4403
4404      // C++ [over.built]p13:
4405      //
4406      //   For every cv-qualified or cv-unqualified object type T
4407      //   there exist candidate operator functions of the form
4408      //
4409      //      T*         operator+(T*, ptrdiff_t);
4410      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
4411      //      T*         operator-(T*, ptrdiff_t);
4412      //      T*         operator+(ptrdiff_t, T*);
4413      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
4414      //
4415      // C++ [over.built]p14:
4416      //
4417      //   For every T, where T is a pointer to object type, there
4418      //   exist candidate operator functions of the form
4419      //
4420      //      ptrdiff_t  operator-(T, T);
4421      for (BuiltinCandidateTypeSet::iterator Ptr
4422             = CandidateTypes.pointer_begin();
4423           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4424        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4425
4426        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4427        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4428
4429        if (Op == OO_Plus) {
4430          // T* operator+(ptrdiff_t, T*);
4431          ParamTypes[0] = ParamTypes[1];
4432          ParamTypes[1] = *Ptr;
4433          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4434        } else {
4435          // ptrdiff_t operator-(T, T);
4436          ParamTypes[1] = *Ptr;
4437          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4438                              Args, 2, CandidateSet);
4439        }
4440      }
4441    }
4442    // Fall through
4443
4444  case OO_Slash:
4445  BinaryStar:
4446  Conditional:
4447    // C++ [over.built]p12:
4448    //
4449    //   For every pair of promoted arithmetic types L and R, there
4450    //   exist candidate operator functions of the form
4451    //
4452    //        LR         operator*(L, R);
4453    //        LR         operator/(L, R);
4454    //        LR         operator+(L, R);
4455    //        LR         operator-(L, R);
4456    //        bool       operator<(L, R);
4457    //        bool       operator>(L, R);
4458    //        bool       operator<=(L, R);
4459    //        bool       operator>=(L, R);
4460    //        bool       operator==(L, R);
4461    //        bool       operator!=(L, R);
4462    //
4463    //   where LR is the result of the usual arithmetic conversions
4464    //   between types L and R.
4465    //
4466    // C++ [over.built]p24:
4467    //
4468    //   For every pair of promoted arithmetic types L and R, there exist
4469    //   candidate operator functions of the form
4470    //
4471    //        LR       operator?(bool, L, R);
4472    //
4473    //   where LR is the result of the usual arithmetic conversions
4474    //   between types L and R.
4475    // Our candidates ignore the first parameter.
4476    for (unsigned Left = FirstPromotedArithmeticType;
4477         Left < LastPromotedArithmeticType; ++Left) {
4478      for (unsigned Right = FirstPromotedArithmeticType;
4479           Right < LastPromotedArithmeticType; ++Right) {
4480        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4481        QualType Result
4482          = isComparison
4483          ? Context.BoolTy
4484          : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
4485        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4486      }
4487    }
4488
4489    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4490    // conditional operator for vector types.
4491    for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4492         Vec1End = CandidateTypes.vector_end();
4493         Vec1 != Vec1End; ++Vec1)
4494      for (BuiltinCandidateTypeSet::iterator
4495           Vec2 = CandidateTypes.vector_begin(),
4496           Vec2End = CandidateTypes.vector_end();
4497           Vec2 != Vec2End; ++Vec2) {
4498        QualType LandR[2] = { *Vec1, *Vec2 };
4499        QualType Result;
4500        if (isComparison)
4501          Result = Context.BoolTy;
4502        else {
4503          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4504            Result = *Vec1;
4505          else
4506            Result = *Vec2;
4507        }
4508
4509        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4510      }
4511
4512    break;
4513
4514  case OO_Percent:
4515  BinaryAmp:
4516  case OO_Caret:
4517  case OO_Pipe:
4518  case OO_LessLess:
4519  case OO_GreaterGreater:
4520    // C++ [over.built]p17:
4521    //
4522    //   For every pair of promoted integral types L and R, there
4523    //   exist candidate operator functions of the form
4524    //
4525    //      LR         operator%(L, R);
4526    //      LR         operator&(L, R);
4527    //      LR         operator^(L, R);
4528    //      LR         operator|(L, R);
4529    //      L          operator<<(L, R);
4530    //      L          operator>>(L, R);
4531    //
4532    //   where LR is the result of the usual arithmetic conversions
4533    //   between types L and R.
4534    for (unsigned Left = FirstPromotedIntegralType;
4535         Left < LastPromotedIntegralType; ++Left) {
4536      for (unsigned Right = FirstPromotedIntegralType;
4537           Right < LastPromotedIntegralType; ++Right) {
4538        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4539        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4540            ? LandR[0]
4541            : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
4542        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4543      }
4544    }
4545    break;
4546
4547  case OO_Equal:
4548    // C++ [over.built]p20:
4549    //
4550    //   For every pair (T, VQ), where T is an enumeration or
4551    //   pointer to member type and VQ is either volatile or
4552    //   empty, there exist candidate operator functions of the form
4553    //
4554    //        VQ T&      operator=(VQ T&, T);
4555    for (BuiltinCandidateTypeSet::iterator
4556           Enum = CandidateTypes.enumeration_begin(),
4557           EnumEnd = CandidateTypes.enumeration_end();
4558         Enum != EnumEnd; ++Enum)
4559      AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
4560                                             CandidateSet);
4561    for (BuiltinCandidateTypeSet::iterator
4562           MemPtr = CandidateTypes.member_pointer_begin(),
4563         MemPtrEnd = CandidateTypes.member_pointer_end();
4564         MemPtr != MemPtrEnd; ++MemPtr)
4565      AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
4566                                             CandidateSet);
4567
4568    // Fall through.
4569
4570  case OO_PlusEqual:
4571  case OO_MinusEqual:
4572    // C++ [over.built]p19:
4573    //
4574    //   For every pair (T, VQ), where T is any type and VQ is either
4575    //   volatile or empty, there exist candidate operator functions
4576    //   of the form
4577    //
4578    //        T*VQ&      operator=(T*VQ&, T*);
4579    //
4580    // C++ [over.built]p21:
4581    //
4582    //   For every pair (T, VQ), where T is a cv-qualified or
4583    //   cv-unqualified object type and VQ is either volatile or
4584    //   empty, there exist candidate operator functions of the form
4585    //
4586    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
4587    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
4588    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4589         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4590      QualType ParamTypes[2];
4591      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4592
4593      // non-volatile version
4594      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
4595      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4596                          /*IsAssigmentOperator=*/Op == OO_Equal);
4597
4598      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4599          VisibleTypeConversionsQuals.hasVolatile()) {
4600        // volatile version
4601        ParamTypes[0]
4602          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
4603        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4604                            /*IsAssigmentOperator=*/Op == OO_Equal);
4605      }
4606    }
4607    // Fall through.
4608
4609  case OO_StarEqual:
4610  case OO_SlashEqual:
4611    // C++ [over.built]p18:
4612    //
4613    //   For every triple (L, VQ, R), where L is an arithmetic type,
4614    //   VQ is either volatile or empty, and R is a promoted
4615    //   arithmetic type, there exist candidate operator functions of
4616    //   the form
4617    //
4618    //        VQ L&      operator=(VQ L&, R);
4619    //        VQ L&      operator*=(VQ L&, R);
4620    //        VQ L&      operator/=(VQ L&, R);
4621    //        VQ L&      operator+=(VQ L&, R);
4622    //        VQ L&      operator-=(VQ L&, R);
4623    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
4624      for (unsigned Right = FirstPromotedArithmeticType;
4625           Right < LastPromotedArithmeticType; ++Right) {
4626        QualType ParamTypes[2];
4627        ParamTypes[1] = ArithmeticTypes[Right];
4628
4629        // Add this built-in operator as a candidate (VQ is empty).
4630        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
4631        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4632                            /*IsAssigmentOperator=*/Op == OO_Equal);
4633
4634        // Add this built-in operator as a candidate (VQ is 'volatile').
4635        if (VisibleTypeConversionsQuals.hasVolatile()) {
4636          ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4637          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4638          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4639                              /*IsAssigmentOperator=*/Op == OO_Equal);
4640        }
4641      }
4642    }
4643
4644    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4645    for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4646                                        Vec1End = CandidateTypes.vector_end();
4647         Vec1 != Vec1End; ++Vec1)
4648      for (BuiltinCandidateTypeSet::iterator
4649                Vec2 = CandidateTypes.vector_begin(),
4650             Vec2End = CandidateTypes.vector_end();
4651           Vec2 != Vec2End; ++Vec2) {
4652        QualType ParamTypes[2];
4653        ParamTypes[1] = *Vec2;
4654        // Add this built-in operator as a candidate (VQ is empty).
4655        ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4656        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4657                            /*IsAssigmentOperator=*/Op == OO_Equal);
4658
4659        // Add this built-in operator as a candidate (VQ is 'volatile').
4660        if (VisibleTypeConversionsQuals.hasVolatile()) {
4661          ParamTypes[0] = Context.getVolatileType(*Vec1);
4662          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4663          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4664                              /*IsAssigmentOperator=*/Op == OO_Equal);
4665        }
4666      }
4667    break;
4668
4669  case OO_PercentEqual:
4670  case OO_LessLessEqual:
4671  case OO_GreaterGreaterEqual:
4672  case OO_AmpEqual:
4673  case OO_CaretEqual:
4674  case OO_PipeEqual:
4675    // C++ [over.built]p22:
4676    //
4677    //   For every triple (L, VQ, R), where L is an integral type, VQ
4678    //   is either volatile or empty, and R is a promoted integral
4679    //   type, there exist candidate operator functions of the form
4680    //
4681    //        VQ L&       operator%=(VQ L&, R);
4682    //        VQ L&       operator<<=(VQ L&, R);
4683    //        VQ L&       operator>>=(VQ L&, R);
4684    //        VQ L&       operator&=(VQ L&, R);
4685    //        VQ L&       operator^=(VQ L&, R);
4686    //        VQ L&       operator|=(VQ L&, R);
4687    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
4688      for (unsigned Right = FirstPromotedIntegralType;
4689           Right < LastPromotedIntegralType; ++Right) {
4690        QualType ParamTypes[2];
4691        ParamTypes[1] = ArithmeticTypes[Right];
4692
4693        // Add this built-in operator as a candidate (VQ is empty).
4694        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
4695        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4696        if (VisibleTypeConversionsQuals.hasVolatile()) {
4697          // Add this built-in operator as a candidate (VQ is 'volatile').
4698          ParamTypes[0] = ArithmeticTypes[Left];
4699          ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4700          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4701          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4702        }
4703      }
4704    }
4705    break;
4706
4707  case OO_Exclaim: {
4708    // C++ [over.operator]p23:
4709    //
4710    //   There also exist candidate operator functions of the form
4711    //
4712    //        bool        operator!(bool);
4713    //        bool        operator&&(bool, bool);     [BELOW]
4714    //        bool        operator||(bool, bool);     [BELOW]
4715    QualType ParamTy = Context.BoolTy;
4716    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4717                        /*IsAssignmentOperator=*/false,
4718                        /*NumContextualBoolArguments=*/1);
4719    break;
4720  }
4721
4722  case OO_AmpAmp:
4723  case OO_PipePipe: {
4724    // C++ [over.operator]p23:
4725    //
4726    //   There also exist candidate operator functions of the form
4727    //
4728    //        bool        operator!(bool);            [ABOVE]
4729    //        bool        operator&&(bool, bool);
4730    //        bool        operator||(bool, bool);
4731    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
4732    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4733                        /*IsAssignmentOperator=*/false,
4734                        /*NumContextualBoolArguments=*/2);
4735    break;
4736  }
4737
4738  case OO_Subscript:
4739    // C++ [over.built]p13:
4740    //
4741    //   For every cv-qualified or cv-unqualified object type T there
4742    //   exist candidate operator functions of the form
4743    //
4744    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
4745    //        T&         operator[](T*, ptrdiff_t);
4746    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
4747    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
4748    //        T&         operator[](ptrdiff_t, T*);
4749    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4750         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4751      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4752      QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
4753      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
4754
4755      // T& operator[](T*, ptrdiff_t)
4756      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4757
4758      // T& operator[](ptrdiff_t, T*);
4759      ParamTypes[0] = ParamTypes[1];
4760      ParamTypes[1] = *Ptr;
4761      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4762    }
4763    break;
4764
4765  case OO_ArrowStar:
4766    // C++ [over.built]p11:
4767    //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4768    //    C1 is the same type as C2 or is a derived class of C2, T is an object
4769    //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4770    //    there exist candidate operator functions of the form
4771    //    CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4772    //    where CV12 is the union of CV1 and CV2.
4773    {
4774      for (BuiltinCandidateTypeSet::iterator Ptr =
4775             CandidateTypes.pointer_begin();
4776           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4777        QualType C1Ty = (*Ptr);
4778        QualType C1;
4779        QualifierCollector Q1;
4780        if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
4781          C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
4782          if (!isa<RecordType>(C1))
4783            continue;
4784          // heuristic to reduce number of builtin candidates in the set.
4785          // Add volatile/restrict version only if there are conversions to a
4786          // volatile/restrict type.
4787          if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4788            continue;
4789          if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4790            continue;
4791        }
4792        for (BuiltinCandidateTypeSet::iterator
4793             MemPtr = CandidateTypes.member_pointer_begin(),
4794             MemPtrEnd = CandidateTypes.member_pointer_end();
4795             MemPtr != MemPtrEnd; ++MemPtr) {
4796          const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4797          QualType C2 = QualType(mptr->getClass(), 0);
4798          C2 = C2.getUnqualifiedType();
4799          if (C1 != C2 && !IsDerivedFrom(C1, C2))
4800            break;
4801          QualType ParamTypes[2] = { *Ptr, *MemPtr };
4802          // build CV12 T&
4803          QualType T = mptr->getPointeeType();
4804          if (!VisibleTypeConversionsQuals.hasVolatile() &&
4805              T.isVolatileQualified())
4806            continue;
4807          if (!VisibleTypeConversionsQuals.hasRestrict() &&
4808              T.isRestrictQualified())
4809            continue;
4810          T = Q1.apply(T);
4811          QualType ResultTy = Context.getLValueReferenceType(T);
4812          AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4813        }
4814      }
4815    }
4816    break;
4817
4818  case OO_Conditional:
4819    // Note that we don't consider the first argument, since it has been
4820    // contextually converted to bool long ago. The candidates below are
4821    // therefore added as binary.
4822    //
4823    // C++ [over.built]p24:
4824    //   For every type T, where T is a pointer or pointer-to-member type,
4825    //   there exist candidate operator functions of the form
4826    //
4827    //        T        operator?(bool, T, T);
4828    //
4829    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4830         E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4831      QualType ParamTypes[2] = { *Ptr, *Ptr };
4832      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4833    }
4834    for (BuiltinCandidateTypeSet::iterator Ptr =
4835           CandidateTypes.member_pointer_begin(),
4836         E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4837      QualType ParamTypes[2] = { *Ptr, *Ptr };
4838      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4839    }
4840    goto Conditional;
4841  }
4842}
4843
4844/// \brief Add function candidates found via argument-dependent lookup
4845/// to the set of overloading candidates.
4846///
4847/// This routine performs argument-dependent name lookup based on the
4848/// given function name (which may also be an operator name) and adds
4849/// all of the overload candidates found by ADL to the overload
4850/// candidate set (C++ [basic.lookup.argdep]).
4851void
4852Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4853                                           bool Operator,
4854                                           Expr **Args, unsigned NumArgs,
4855                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4856                                           OverloadCandidateSet& CandidateSet,
4857                                           bool PartialOverloading) {
4858  ADLResult Fns;
4859
4860  // FIXME: This approach for uniquing ADL results (and removing
4861  // redundant candidates from the set) relies on pointer-equality,
4862  // which means we need to key off the canonical decl.  However,
4863  // always going back to the canonical decl might not get us the
4864  // right set of default arguments.  What default arguments are
4865  // we supposed to consider on ADL candidates, anyway?
4866
4867  // FIXME: Pass in the explicit template arguments?
4868  ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
4869
4870  // Erase all of the candidates we already knew about.
4871  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4872                                   CandEnd = CandidateSet.end();
4873       Cand != CandEnd; ++Cand)
4874    if (Cand->Function) {
4875      Fns.erase(Cand->Function);
4876      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4877        Fns.erase(FunTmpl);
4878    }
4879
4880  // For each of the ADL candidates we found, add it to the overload
4881  // set.
4882  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
4883    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
4884    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
4885      if (ExplicitTemplateArgs)
4886        continue;
4887
4888      AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
4889                           false, PartialOverloading);
4890    } else
4891      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
4892                                   FoundDecl, ExplicitTemplateArgs,
4893                                   Args, NumArgs, CandidateSet);
4894  }
4895}
4896
4897/// isBetterOverloadCandidate - Determines whether the first overload
4898/// candidate is a better candidate than the second (C++ 13.3.3p1).
4899bool
4900Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
4901                                const OverloadCandidate& Cand2,
4902                                SourceLocation Loc) {
4903  // Define viable functions to be better candidates than non-viable
4904  // functions.
4905  if (!Cand2.Viable)
4906    return Cand1.Viable;
4907  else if (!Cand1.Viable)
4908    return false;
4909
4910  // C++ [over.match.best]p1:
4911  //
4912  //   -- if F is a static member function, ICS1(F) is defined such
4913  //      that ICS1(F) is neither better nor worse than ICS1(G) for
4914  //      any function G, and, symmetrically, ICS1(G) is neither
4915  //      better nor worse than ICS1(F).
4916  unsigned StartArg = 0;
4917  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4918    StartArg = 1;
4919
4920  // C++ [over.match.best]p1:
4921  //   A viable function F1 is defined to be a better function than another
4922  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
4923  //   conversion sequence than ICSi(F2), and then...
4924  unsigned NumArgs = Cand1.Conversions.size();
4925  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4926  bool HasBetterConversion = false;
4927  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
4928    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4929                                               Cand2.Conversions[ArgIdx])) {
4930    case ImplicitConversionSequence::Better:
4931      // Cand1 has a better conversion sequence.
4932      HasBetterConversion = true;
4933      break;
4934
4935    case ImplicitConversionSequence::Worse:
4936      // Cand1 can't be better than Cand2.
4937      return false;
4938
4939    case ImplicitConversionSequence::Indistinguishable:
4940      // Do nothing.
4941      break;
4942    }
4943  }
4944
4945  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
4946  //       ICSj(F2), or, if not that,
4947  if (HasBetterConversion)
4948    return true;
4949
4950  //     - F1 is a non-template function and F2 is a function template
4951  //       specialization, or, if not that,
4952  if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4953      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4954    return true;
4955
4956  //   -- F1 and F2 are function template specializations, and the function
4957  //      template for F1 is more specialized than the template for F2
4958  //      according to the partial ordering rules described in 14.5.5.2, or,
4959  //      if not that,
4960  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4961      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4962    if (FunctionTemplateDecl *BetterTemplate
4963          = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4964                                       Cand2.Function->getPrimaryTemplate(),
4965                                       Loc,
4966                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4967                                                             : TPOC_Call))
4968      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
4969
4970  //   -- the context is an initialization by user-defined conversion
4971  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
4972  //      from the return type of F1 to the destination type (i.e.,
4973  //      the type of the entity being initialized) is a better
4974  //      conversion sequence than the standard conversion sequence
4975  //      from the return type of F2 to the destination type.
4976  if (Cand1.Function && Cand2.Function &&
4977      isa<CXXConversionDecl>(Cand1.Function) &&
4978      isa<CXXConversionDecl>(Cand2.Function)) {
4979    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4980                                               Cand2.FinalConversion)) {
4981    case ImplicitConversionSequence::Better:
4982      // Cand1 has a better conversion sequence.
4983      return true;
4984
4985    case ImplicitConversionSequence::Worse:
4986      // Cand1 can't be better than Cand2.
4987      return false;
4988
4989    case ImplicitConversionSequence::Indistinguishable:
4990      // Do nothing
4991      break;
4992    }
4993  }
4994
4995  return false;
4996}
4997
4998/// \brief Computes the best viable function (C++ 13.3.3)
4999/// within an overload candidate set.
5000///
5001/// \param CandidateSet the set of candidate functions.
5002///
5003/// \param Loc the location of the function name (or operator symbol) for
5004/// which overload resolution occurs.
5005///
5006/// \param Best f overload resolution was successful or found a deleted
5007/// function, Best points to the candidate function found.
5008///
5009/// \returns The result of overload resolution.
5010OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5011                                           SourceLocation Loc,
5012                                        OverloadCandidateSet::iterator& Best) {
5013  // Find the best viable function.
5014  Best = CandidateSet.end();
5015  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5016       Cand != CandidateSet.end(); ++Cand) {
5017    if (Cand->Viable) {
5018      if (Best == CandidateSet.end() ||
5019          isBetterOverloadCandidate(*Cand, *Best, Loc))
5020        Best = Cand;
5021    }
5022  }
5023
5024  // If we didn't find any viable functions, abort.
5025  if (Best == CandidateSet.end())
5026    return OR_No_Viable_Function;
5027
5028  // Make sure that this function is better than every other viable
5029  // function. If not, we have an ambiguity.
5030  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5031       Cand != CandidateSet.end(); ++Cand) {
5032    if (Cand->Viable &&
5033        Cand != Best &&
5034        !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
5035      Best = CandidateSet.end();
5036      return OR_Ambiguous;
5037    }
5038  }
5039
5040  // Best is the best viable function.
5041  if (Best->Function &&
5042      (Best->Function->isDeleted() ||
5043       Best->Function->getAttr<UnavailableAttr>()))
5044    return OR_Deleted;
5045
5046  // C++ [basic.def.odr]p2:
5047  //   An overloaded function is used if it is selected by overload resolution
5048  //   when referred to from a potentially-evaluated expression. [Note: this
5049  //   covers calls to named functions (5.2.2), operator overloading
5050  //   (clause 13), user-defined conversions (12.3.2), allocation function for
5051  //   placement new (5.3.4), as well as non-default initialization (8.5).
5052  if (Best->Function)
5053    MarkDeclarationReferenced(Loc, Best->Function);
5054  return OR_Success;
5055}
5056
5057namespace {
5058
5059enum OverloadCandidateKind {
5060  oc_function,
5061  oc_method,
5062  oc_constructor,
5063  oc_function_template,
5064  oc_method_template,
5065  oc_constructor_template,
5066  oc_implicit_default_constructor,
5067  oc_implicit_copy_constructor,
5068  oc_implicit_copy_assignment
5069};
5070
5071OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5072                                                FunctionDecl *Fn,
5073                                                std::string &Description) {
5074  bool isTemplate = false;
5075
5076  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5077    isTemplate = true;
5078    Description = S.getTemplateArgumentBindingsText(
5079      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5080  }
5081
5082  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
5083    if (!Ctor->isImplicit())
5084      return isTemplate ? oc_constructor_template : oc_constructor;
5085
5086    return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5087                                     : oc_implicit_default_constructor;
5088  }
5089
5090  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5091    // This actually gets spelled 'candidate function' for now, but
5092    // it doesn't hurt to split it out.
5093    if (!Meth->isImplicit())
5094      return isTemplate ? oc_method_template : oc_method;
5095
5096    assert(Meth->isCopyAssignment()
5097           && "implicit method is not copy assignment operator?");
5098    return oc_implicit_copy_assignment;
5099  }
5100
5101  return isTemplate ? oc_function_template : oc_function;
5102}
5103
5104} // end anonymous namespace
5105
5106// Notes the location of an overload candidate.
5107void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
5108  std::string FnDesc;
5109  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5110  Diag(Fn->getLocation(), diag::note_ovl_candidate)
5111    << (unsigned) K << FnDesc;
5112}
5113
5114/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
5115/// "lead" diagnostic; it will be given two arguments, the source and
5116/// target types of the conversion.
5117void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5118                                       SourceLocation CaretLoc,
5119                                       const PartialDiagnostic &PDiag) {
5120  Diag(CaretLoc, PDiag)
5121    << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5122  for (AmbiguousConversionSequence::const_iterator
5123         I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5124    NoteOverloadCandidate(*I);
5125  }
5126}
5127
5128namespace {
5129
5130void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5131  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5132  assert(Conv.isBad());
5133  assert(Cand->Function && "for now, candidate must be a function");
5134  FunctionDecl *Fn = Cand->Function;
5135
5136  // There's a conversion slot for the object argument if this is a
5137  // non-constructor method.  Note that 'I' corresponds the
5138  // conversion-slot index.
5139  bool isObjectArgument = false;
5140  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
5141    if (I == 0)
5142      isObjectArgument = true;
5143    else
5144      I--;
5145  }
5146
5147  std::string FnDesc;
5148  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5149
5150  Expr *FromExpr = Conv.Bad.FromExpr;
5151  QualType FromTy = Conv.Bad.getFromType();
5152  QualType ToTy = Conv.Bad.getToType();
5153
5154  if (FromTy == S.Context.OverloadTy) {
5155    assert(FromExpr && "overload set argument came from implicit argument?");
5156    Expr *E = FromExpr->IgnoreParens();
5157    if (isa<UnaryOperator>(E))
5158      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
5159    DeclarationName Name = cast<OverloadExpr>(E)->getName();
5160
5161    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5162      << (unsigned) FnKind << FnDesc
5163      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5164      << ToTy << Name << I+1;
5165    return;
5166  }
5167
5168  // Do some hand-waving analysis to see if the non-viability is due
5169  // to a qualifier mismatch.
5170  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5171  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5172  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5173    CToTy = RT->getPointeeType();
5174  else {
5175    // TODO: detect and diagnose the full richness of const mismatches.
5176    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5177      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5178        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5179  }
5180
5181  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5182      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5183    // It is dumb that we have to do this here.
5184    while (isa<ArrayType>(CFromTy))
5185      CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5186    while (isa<ArrayType>(CToTy))
5187      CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5188
5189    Qualifiers FromQs = CFromTy.getQualifiers();
5190    Qualifiers ToQs = CToTy.getQualifiers();
5191
5192    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5193      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5194        << (unsigned) FnKind << FnDesc
5195        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5196        << FromTy
5197        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5198        << (unsigned) isObjectArgument << I+1;
5199      return;
5200    }
5201
5202    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5203    assert(CVR && "unexpected qualifiers mismatch");
5204
5205    if (isObjectArgument) {
5206      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5207        << (unsigned) FnKind << FnDesc
5208        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5209        << FromTy << (CVR - 1);
5210    } else {
5211      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5212        << (unsigned) FnKind << FnDesc
5213        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5214        << FromTy << (CVR - 1) << I+1;
5215    }
5216    return;
5217  }
5218
5219  // Diagnose references or pointers to incomplete types differently,
5220  // since it's far from impossible that the incompleteness triggered
5221  // the failure.
5222  QualType TempFromTy = FromTy.getNonReferenceType();
5223  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5224    TempFromTy = PTy->getPointeeType();
5225  if (TempFromTy->isIncompleteType()) {
5226    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5227      << (unsigned) FnKind << FnDesc
5228      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5229      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5230    return;
5231  }
5232
5233  // TODO: specialize more based on the kind of mismatch
5234  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5235    << (unsigned) FnKind << FnDesc
5236    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5237    << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5238}
5239
5240void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5241                           unsigned NumFormalArgs) {
5242  // TODO: treat calls to a missing default constructor as a special case
5243
5244  FunctionDecl *Fn = Cand->Function;
5245  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5246
5247  unsigned MinParams = Fn->getMinRequiredArguments();
5248
5249  // at least / at most / exactly
5250  // FIXME: variadic templates "at most" should account for parameter packs
5251  unsigned mode, modeCount;
5252  if (NumFormalArgs < MinParams) {
5253    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5254           (Cand->FailureKind == ovl_fail_bad_deduction &&
5255            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
5256    if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5257      mode = 0; // "at least"
5258    else
5259      mode = 2; // "exactly"
5260    modeCount = MinParams;
5261  } else {
5262    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5263           (Cand->FailureKind == ovl_fail_bad_deduction &&
5264            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
5265    if (MinParams != FnTy->getNumArgs())
5266      mode = 1; // "at most"
5267    else
5268      mode = 2; // "exactly"
5269    modeCount = FnTy->getNumArgs();
5270  }
5271
5272  std::string Description;
5273  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5274
5275  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
5276    << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5277    << modeCount << NumFormalArgs;
5278}
5279
5280/// Diagnose a failed template-argument deduction.
5281void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5282                          Expr **Args, unsigned NumArgs) {
5283  FunctionDecl *Fn = Cand->Function; // pattern
5284
5285  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
5286  NamedDecl *ParamD;
5287  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5288  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5289  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
5290  switch (Cand->DeductionFailure.Result) {
5291  case Sema::TDK_Success:
5292    llvm_unreachable("TDK_success while diagnosing bad deduction");
5293
5294  case Sema::TDK_Incomplete: {
5295    assert(ParamD && "no parameter found for incomplete deduction result");
5296    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5297      << ParamD->getDeclName();
5298    return;
5299  }
5300
5301  case Sema::TDK_Inconsistent:
5302  case Sema::TDK_InconsistentQuals: {
5303    assert(ParamD && "no parameter found for inconsistent deduction result");
5304    int which = 0;
5305    if (isa<TemplateTypeParmDecl>(ParamD))
5306      which = 0;
5307    else if (isa<NonTypeTemplateParmDecl>(ParamD))
5308      which = 1;
5309    else {
5310      which = 2;
5311    }
5312
5313    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5314      << which << ParamD->getDeclName()
5315      << *Cand->DeductionFailure.getFirstArg()
5316      << *Cand->DeductionFailure.getSecondArg();
5317    return;
5318  }
5319
5320  case Sema::TDK_InvalidExplicitArguments:
5321    assert(ParamD && "no parameter found for invalid explicit arguments");
5322    if (ParamD->getDeclName())
5323      S.Diag(Fn->getLocation(),
5324             diag::note_ovl_candidate_explicit_arg_mismatch_named)
5325        << ParamD->getDeclName();
5326    else {
5327      int index = 0;
5328      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5329        index = TTP->getIndex();
5330      else if (NonTypeTemplateParmDecl *NTTP
5331                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5332        index = NTTP->getIndex();
5333      else
5334        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5335      S.Diag(Fn->getLocation(),
5336             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5337        << (index + 1);
5338    }
5339    return;
5340
5341  case Sema::TDK_TooManyArguments:
5342  case Sema::TDK_TooFewArguments:
5343    DiagnoseArityMismatch(S, Cand, NumArgs);
5344    return;
5345
5346  case Sema::TDK_InstantiationDepth:
5347    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5348    return;
5349
5350  case Sema::TDK_SubstitutionFailure: {
5351    std::string ArgString;
5352    if (TemplateArgumentList *Args
5353                            = Cand->DeductionFailure.getTemplateArgumentList())
5354      ArgString = S.getTemplateArgumentBindingsText(
5355                    Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5356                                                    *Args);
5357    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5358      << ArgString;
5359    return;
5360  }
5361
5362  // TODO: diagnose these individually, then kill off
5363  // note_ovl_candidate_bad_deduction, which is uselessly vague.
5364  case Sema::TDK_NonDeducedMismatch:
5365  case Sema::TDK_FailedOverloadResolution:
5366    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5367    return;
5368  }
5369}
5370
5371/// Generates a 'note' diagnostic for an overload candidate.  We've
5372/// already generated a primary error at the call site.
5373///
5374/// It really does need to be a single diagnostic with its caret
5375/// pointed at the candidate declaration.  Yes, this creates some
5376/// major challenges of technical writing.  Yes, this makes pointing
5377/// out problems with specific arguments quite awkward.  It's still
5378/// better than generating twenty screens of text for every failed
5379/// overload.
5380///
5381/// It would be great to be able to express per-candidate problems
5382/// more richly for those diagnostic clients that cared, but we'd
5383/// still have to be just as careful with the default diagnostics.
5384void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5385                           Expr **Args, unsigned NumArgs) {
5386  FunctionDecl *Fn = Cand->Function;
5387
5388  // Note deleted candidates, but only if they're viable.
5389  if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
5390    std::string FnDesc;
5391    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5392
5393    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
5394      << FnKind << FnDesc << Fn->isDeleted();
5395    return;
5396  }
5397
5398  // We don't really have anything else to say about viable candidates.
5399  if (Cand->Viable) {
5400    S.NoteOverloadCandidate(Fn);
5401    return;
5402  }
5403
5404  switch (Cand->FailureKind) {
5405  case ovl_fail_too_many_arguments:
5406  case ovl_fail_too_few_arguments:
5407    return DiagnoseArityMismatch(S, Cand, NumArgs);
5408
5409  case ovl_fail_bad_deduction:
5410    return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5411
5412  case ovl_fail_trivial_conversion:
5413  case ovl_fail_bad_final_conversion:
5414  case ovl_fail_final_conversion_not_exact:
5415    return S.NoteOverloadCandidate(Fn);
5416
5417  case ovl_fail_bad_conversion: {
5418    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5419    for (unsigned N = Cand->Conversions.size(); I != N; ++I)
5420      if (Cand->Conversions[I].isBad())
5421        return DiagnoseBadConversion(S, Cand, I);
5422
5423    // FIXME: this currently happens when we're called from SemaInit
5424    // when user-conversion overload fails.  Figure out how to handle
5425    // those conditions and diagnose them well.
5426    return S.NoteOverloadCandidate(Fn);
5427  }
5428  }
5429}
5430
5431void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5432  // Desugar the type of the surrogate down to a function type,
5433  // retaining as many typedefs as possible while still showing
5434  // the function type (and, therefore, its parameter types).
5435  QualType FnType = Cand->Surrogate->getConversionType();
5436  bool isLValueReference = false;
5437  bool isRValueReference = false;
5438  bool isPointer = false;
5439  if (const LValueReferenceType *FnTypeRef =
5440        FnType->getAs<LValueReferenceType>()) {
5441    FnType = FnTypeRef->getPointeeType();
5442    isLValueReference = true;
5443  } else if (const RValueReferenceType *FnTypeRef =
5444               FnType->getAs<RValueReferenceType>()) {
5445    FnType = FnTypeRef->getPointeeType();
5446    isRValueReference = true;
5447  }
5448  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5449    FnType = FnTypePtr->getPointeeType();
5450    isPointer = true;
5451  }
5452  // Desugar down to a function type.
5453  FnType = QualType(FnType->getAs<FunctionType>(), 0);
5454  // Reconstruct the pointer/reference as appropriate.
5455  if (isPointer) FnType = S.Context.getPointerType(FnType);
5456  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5457  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5458
5459  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5460    << FnType;
5461}
5462
5463void NoteBuiltinOperatorCandidate(Sema &S,
5464                                  const char *Opc,
5465                                  SourceLocation OpLoc,
5466                                  OverloadCandidate *Cand) {
5467  assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5468  std::string TypeStr("operator");
5469  TypeStr += Opc;
5470  TypeStr += "(";
5471  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5472  if (Cand->Conversions.size() == 1) {
5473    TypeStr += ")";
5474    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5475  } else {
5476    TypeStr += ", ";
5477    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5478    TypeStr += ")";
5479    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5480  }
5481}
5482
5483void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5484                                  OverloadCandidate *Cand) {
5485  unsigned NoOperands = Cand->Conversions.size();
5486  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5487    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
5488    if (ICS.isBad()) break; // all meaningless after first invalid
5489    if (!ICS.isAmbiguous()) continue;
5490
5491    S.DiagnoseAmbiguousConversion(ICS, OpLoc,
5492                              S.PDiag(diag::note_ambiguous_type_conversion));
5493  }
5494}
5495
5496SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5497  if (Cand->Function)
5498    return Cand->Function->getLocation();
5499  if (Cand->IsSurrogate)
5500    return Cand->Surrogate->getLocation();
5501  return SourceLocation();
5502}
5503
5504struct CompareOverloadCandidatesForDisplay {
5505  Sema &S;
5506  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
5507
5508  bool operator()(const OverloadCandidate *L,
5509                  const OverloadCandidate *R) {
5510    // Fast-path this check.
5511    if (L == R) return false;
5512
5513    // Order first by viability.
5514    if (L->Viable) {
5515      if (!R->Viable) return true;
5516
5517      // TODO: introduce a tri-valued comparison for overload
5518      // candidates.  Would be more worthwhile if we had a sort
5519      // that could exploit it.
5520      if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5521      if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
5522    } else if (R->Viable)
5523      return false;
5524
5525    assert(L->Viable == R->Viable);
5526
5527    // Criteria by which we can sort non-viable candidates:
5528    if (!L->Viable) {
5529      // 1. Arity mismatches come after other candidates.
5530      if (L->FailureKind == ovl_fail_too_many_arguments ||
5531          L->FailureKind == ovl_fail_too_few_arguments)
5532        return false;
5533      if (R->FailureKind == ovl_fail_too_many_arguments ||
5534          R->FailureKind == ovl_fail_too_few_arguments)
5535        return true;
5536
5537      // 2. Bad conversions come first and are ordered by the number
5538      // of bad conversions and quality of good conversions.
5539      if (L->FailureKind == ovl_fail_bad_conversion) {
5540        if (R->FailureKind != ovl_fail_bad_conversion)
5541          return true;
5542
5543        // If there's any ordering between the defined conversions...
5544        // FIXME: this might not be transitive.
5545        assert(L->Conversions.size() == R->Conversions.size());
5546
5547        int leftBetter = 0;
5548        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5549        for (unsigned E = L->Conversions.size(); I != E; ++I) {
5550          switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5551                                                       R->Conversions[I])) {
5552          case ImplicitConversionSequence::Better:
5553            leftBetter++;
5554            break;
5555
5556          case ImplicitConversionSequence::Worse:
5557            leftBetter--;
5558            break;
5559
5560          case ImplicitConversionSequence::Indistinguishable:
5561            break;
5562          }
5563        }
5564        if (leftBetter > 0) return true;
5565        if (leftBetter < 0) return false;
5566
5567      } else if (R->FailureKind == ovl_fail_bad_conversion)
5568        return false;
5569
5570      // TODO: others?
5571    }
5572
5573    // Sort everything else by location.
5574    SourceLocation LLoc = GetLocationForCandidate(L);
5575    SourceLocation RLoc = GetLocationForCandidate(R);
5576
5577    // Put candidates without locations (e.g. builtins) at the end.
5578    if (LLoc.isInvalid()) return false;
5579    if (RLoc.isInvalid()) return true;
5580
5581    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
5582  }
5583};
5584
5585/// CompleteNonViableCandidate - Normally, overload resolution only
5586/// computes up to the first
5587void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5588                                Expr **Args, unsigned NumArgs) {
5589  assert(!Cand->Viable);
5590
5591  // Don't do anything on failures other than bad conversion.
5592  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5593
5594  // Skip forward to the first bad conversion.
5595  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
5596  unsigned ConvCount = Cand->Conversions.size();
5597  while (true) {
5598    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5599    ConvIdx++;
5600    if (Cand->Conversions[ConvIdx - 1].isBad())
5601      break;
5602  }
5603
5604  if (ConvIdx == ConvCount)
5605    return;
5606
5607  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5608         "remaining conversion is initialized?");
5609
5610  // FIXME: this should probably be preserved from the overload
5611  // operation somehow.
5612  bool SuppressUserConversions = false;
5613
5614  const FunctionProtoType* Proto;
5615  unsigned ArgIdx = ConvIdx;
5616
5617  if (Cand->IsSurrogate) {
5618    QualType ConvType
5619      = Cand->Surrogate->getConversionType().getNonReferenceType();
5620    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5621      ConvType = ConvPtrType->getPointeeType();
5622    Proto = ConvType->getAs<FunctionProtoType>();
5623    ArgIdx--;
5624  } else if (Cand->Function) {
5625    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5626    if (isa<CXXMethodDecl>(Cand->Function) &&
5627        !isa<CXXConstructorDecl>(Cand->Function))
5628      ArgIdx--;
5629  } else {
5630    // Builtin binary operator with a bad first conversion.
5631    assert(ConvCount <= 3);
5632    for (; ConvIdx != ConvCount; ++ConvIdx)
5633      Cand->Conversions[ConvIdx]
5634        = TryCopyInitialization(S, Args[ConvIdx],
5635                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
5636                                SuppressUserConversions,
5637                                /*InOverloadResolution*/ true);
5638    return;
5639  }
5640
5641  // Fill in the rest of the conversions.
5642  unsigned NumArgsInProto = Proto->getNumArgs();
5643  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5644    if (ArgIdx < NumArgsInProto)
5645      Cand->Conversions[ConvIdx]
5646        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5647                                SuppressUserConversions,
5648                                /*InOverloadResolution=*/true);
5649    else
5650      Cand->Conversions[ConvIdx].setEllipsis();
5651  }
5652}
5653
5654} // end anonymous namespace
5655
5656/// PrintOverloadCandidates - When overload resolution fails, prints
5657/// diagnostic messages containing the candidates in the candidate
5658/// set.
5659void
5660Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
5661                              OverloadCandidateDisplayKind OCD,
5662                              Expr **Args, unsigned NumArgs,
5663                              const char *Opc,
5664                              SourceLocation OpLoc) {
5665  // Sort the candidates by viability and position.  Sorting directly would
5666  // be prohibitive, so we make a set of pointers and sort those.
5667  llvm::SmallVector<OverloadCandidate*, 32> Cands;
5668  if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5669  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5670                                  LastCand = CandidateSet.end();
5671       Cand != LastCand; ++Cand) {
5672    if (Cand->Viable)
5673      Cands.push_back(Cand);
5674    else if (OCD == OCD_AllCandidates) {
5675      CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5676      Cands.push_back(Cand);
5677    }
5678  }
5679
5680  std::sort(Cands.begin(), Cands.end(),
5681            CompareOverloadCandidatesForDisplay(*this));
5682
5683  bool ReportedAmbiguousConversions = false;
5684
5685  llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5686  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5687    OverloadCandidate *Cand = *I;
5688
5689    if (Cand->Function)
5690      NoteFunctionCandidate(*this, Cand, Args, NumArgs);
5691    else if (Cand->IsSurrogate)
5692      NoteSurrogateCandidate(*this, Cand);
5693
5694    // This a builtin candidate.  We do not, in general, want to list
5695    // every possible builtin candidate.
5696    else if (Cand->Viable) {
5697      // Generally we only see ambiguities including viable builtin
5698      // operators if overload resolution got screwed up by an
5699      // ambiguous user-defined conversion.
5700      //
5701      // FIXME: It's quite possible for different conversions to see
5702      // different ambiguities, though.
5703      if (!ReportedAmbiguousConversions) {
5704        NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5705        ReportedAmbiguousConversions = true;
5706      }
5707
5708      // If this is a viable builtin, print it.
5709      NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
5710    }
5711  }
5712}
5713
5714static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
5715  if (isa<UnresolvedLookupExpr>(E))
5716    return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
5717
5718  return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
5719}
5720
5721/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5722/// an overloaded function (C++ [over.over]), where @p From is an
5723/// expression with overloaded function type and @p ToType is the type
5724/// we're trying to resolve to. For example:
5725///
5726/// @code
5727/// int f(double);
5728/// int f(int);
5729///
5730/// int (*pfd)(double) = f; // selects f(double)
5731/// @endcode
5732///
5733/// This routine returns the resulting FunctionDecl if it could be
5734/// resolved, and NULL otherwise. When @p Complain is true, this
5735/// routine will emit diagnostics if there is an error.
5736FunctionDecl *
5737Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
5738                                         bool Complain,
5739                                         DeclAccessPair &FoundResult) {
5740  QualType FunctionType = ToType;
5741  bool IsMember = false;
5742  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
5743    FunctionType = ToTypePtr->getPointeeType();
5744  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
5745    FunctionType = ToTypeRef->getPointeeType();
5746  else if (const MemberPointerType *MemTypePtr =
5747                    ToType->getAs<MemberPointerType>()) {
5748    FunctionType = MemTypePtr->getPointeeType();
5749    IsMember = true;
5750  }
5751
5752  // C++ [over.over]p1:
5753  //   [...] [Note: any redundant set of parentheses surrounding the
5754  //   overloaded function name is ignored (5.1). ]
5755  // C++ [over.over]p1:
5756  //   [...] The overloaded function name can be preceded by the &
5757  //   operator.
5758  OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5759  TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5760  if (OvlExpr->hasExplicitTemplateArgs()) {
5761    OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5762    ExplicitTemplateArgs = &ETABuffer;
5763  }
5764
5765  // We expect a pointer or reference to function, or a function pointer.
5766  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5767  if (!FunctionType->isFunctionType()) {
5768    if (Complain)
5769      Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5770        << OvlExpr->getName() << ToType;
5771
5772    return 0;
5773  }
5774
5775  assert(From->getType() == Context.OverloadTy);
5776
5777  // Look through all of the overloaded functions, searching for one
5778  // whose type matches exactly.
5779  llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
5780  llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5781
5782  bool FoundNonTemplateFunction = false;
5783  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5784         E = OvlExpr->decls_end(); I != E; ++I) {
5785    // Look through any using declarations to find the underlying function.
5786    NamedDecl *Fn = (*I)->getUnderlyingDecl();
5787
5788    // C++ [over.over]p3:
5789    //   Non-member functions and static member functions match
5790    //   targets of type "pointer-to-function" or "reference-to-function."
5791    //   Nonstatic member functions match targets of
5792    //   type "pointer-to-member-function."
5793    // Note that according to DR 247, the containing class does not matter.
5794
5795    if (FunctionTemplateDecl *FunctionTemplate
5796          = dyn_cast<FunctionTemplateDecl>(Fn)) {
5797      if (CXXMethodDecl *Method
5798            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
5799        // Skip non-static function templates when converting to pointer, and
5800        // static when converting to member pointer.
5801        if (Method->isStatic() == IsMember)
5802          continue;
5803      } else if (IsMember)
5804        continue;
5805
5806      // C++ [over.over]p2:
5807      //   If the name is a function template, template argument deduction is
5808      //   done (14.8.2.2), and if the argument deduction succeeds, the
5809      //   resulting template argument list is used to generate a single
5810      //   function template specialization, which is added to the set of
5811      //   overloaded functions considered.
5812      // FIXME: We don't really want to build the specialization here, do we?
5813      FunctionDecl *Specialization = 0;
5814      TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
5815      if (TemplateDeductionResult Result
5816            = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
5817                                      FunctionType, Specialization, Info)) {
5818        // FIXME: make a note of the failed deduction for diagnostics.
5819        (void)Result;
5820      } else {
5821        // FIXME: If the match isn't exact, shouldn't we just drop this as
5822        // a candidate? Find a testcase before changing the code.
5823        assert(FunctionType
5824                 == Context.getCanonicalType(Specialization->getType()));
5825        Matches.push_back(std::make_pair(I.getPair(),
5826                    cast<FunctionDecl>(Specialization->getCanonicalDecl())));
5827      }
5828
5829      continue;
5830    }
5831
5832    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5833      // Skip non-static functions when converting to pointer, and static
5834      // when converting to member pointer.
5835      if (Method->isStatic() == IsMember)
5836        continue;
5837
5838      // If we have explicit template arguments, skip non-templates.
5839      if (OvlExpr->hasExplicitTemplateArgs())
5840        continue;
5841    } else if (IsMember)
5842      continue;
5843
5844    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
5845      QualType ResultTy;
5846      if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5847          IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5848                               ResultTy)) {
5849        Matches.push_back(std::make_pair(I.getPair(),
5850                           cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
5851        FoundNonTemplateFunction = true;
5852      }
5853    }
5854  }
5855
5856  // If there were 0 or 1 matches, we're done.
5857  if (Matches.empty()) {
5858    if (Complain) {
5859      Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5860        << OvlExpr->getName() << FunctionType;
5861      for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5862                                 E = OvlExpr->decls_end();
5863           I != E; ++I)
5864        if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5865          NoteOverloadCandidate(F);
5866    }
5867
5868    return 0;
5869  } else if (Matches.size() == 1) {
5870    FunctionDecl *Result = Matches[0].second;
5871    FoundResult = Matches[0].first;
5872    MarkDeclarationReferenced(From->getLocStart(), Result);
5873    if (Complain)
5874      CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
5875    return Result;
5876  }
5877
5878  // C++ [over.over]p4:
5879  //   If more than one function is selected, [...]
5880  if (!FoundNonTemplateFunction) {
5881    //   [...] and any given function template specialization F1 is
5882    //   eliminated if the set contains a second function template
5883    //   specialization whose function template is more specialized
5884    //   than the function template of F1 according to the partial
5885    //   ordering rules of 14.5.5.2.
5886
5887    // The algorithm specified above is quadratic. We instead use a
5888    // two-pass algorithm (similar to the one used to identify the
5889    // best viable function in an overload set) that identifies the
5890    // best function template (if it exists).
5891
5892    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5893    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5894      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
5895
5896    UnresolvedSetIterator Result =
5897        getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
5898                           TPOC_Other, From->getLocStart(),
5899                           PDiag(),
5900                           PDiag(diag::err_addr_ovl_ambiguous)
5901                               << Matches[0].second->getDeclName(),
5902                           PDiag(diag::note_ovl_candidate)
5903                               << (unsigned) oc_function_template);
5904    assert(Result != MatchesCopy.end() && "no most-specialized template");
5905    MarkDeclarationReferenced(From->getLocStart(), *Result);
5906    FoundResult = Matches[Result - MatchesCopy.begin()].first;
5907    if (Complain) {
5908      CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
5909      DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5910    }
5911    return cast<FunctionDecl>(*Result);
5912  }
5913
5914  //   [...] any function template specializations in the set are
5915  //   eliminated if the set also contains a non-template function, [...]
5916  for (unsigned I = 0, N = Matches.size(); I != N; ) {
5917    if (Matches[I].second->getPrimaryTemplate() == 0)
5918      ++I;
5919    else {
5920      Matches[I] = Matches[--N];
5921      Matches.set_size(N);
5922    }
5923  }
5924
5925  // [...] After such eliminations, if any, there shall remain exactly one
5926  // selected function.
5927  if (Matches.size() == 1) {
5928    MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
5929    FoundResult = Matches[0].first;
5930    if (Complain) {
5931      CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
5932      DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5933    }
5934    return cast<FunctionDecl>(Matches[0].second);
5935  }
5936
5937  // FIXME: We should probably return the same thing that BestViableFunction
5938  // returns (even if we issue the diagnostics here).
5939  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
5940    << Matches[0].second->getDeclName();
5941  for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5942    NoteOverloadCandidate(Matches[I].second);
5943  return 0;
5944}
5945
5946/// \brief Given an expression that refers to an overloaded function, try to
5947/// resolve that overloaded function expression down to a single function.
5948///
5949/// This routine can only resolve template-ids that refer to a single function
5950/// template, where that template-id refers to a single template whose template
5951/// arguments are either provided by the template-id or have defaults,
5952/// as described in C++0x [temp.arg.explicit]p3.
5953FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5954  // C++ [over.over]p1:
5955  //   [...] [Note: any redundant set of parentheses surrounding the
5956  //   overloaded function name is ignored (5.1). ]
5957  // C++ [over.over]p1:
5958  //   [...] The overloaded function name can be preceded by the &
5959  //   operator.
5960
5961  if (From->getType() != Context.OverloadTy)
5962    return 0;
5963
5964  OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5965
5966  // If we didn't actually find any template-ids, we're done.
5967  if (!OvlExpr->hasExplicitTemplateArgs())
5968    return 0;
5969
5970  TemplateArgumentListInfo ExplicitTemplateArgs;
5971  OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
5972
5973  // Look through all of the overloaded functions, searching for one
5974  // whose type matches exactly.
5975  FunctionDecl *Matched = 0;
5976  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5977         E = OvlExpr->decls_end(); I != E; ++I) {
5978    // C++0x [temp.arg.explicit]p3:
5979    //   [...] In contexts where deduction is done and fails, or in contexts
5980    //   where deduction is not done, if a template argument list is
5981    //   specified and it, along with any default template arguments,
5982    //   identifies a single function template specialization, then the
5983    //   template-id is an lvalue for the function template specialization.
5984    FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5985
5986    // C++ [over.over]p2:
5987    //   If the name is a function template, template argument deduction is
5988    //   done (14.8.2.2), and if the argument deduction succeeds, the
5989    //   resulting template argument list is used to generate a single
5990    //   function template specialization, which is added to the set of
5991    //   overloaded functions considered.
5992    FunctionDecl *Specialization = 0;
5993    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
5994    if (TemplateDeductionResult Result
5995          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5996                                    Specialization, Info)) {
5997      // FIXME: make a note of the failed deduction for diagnostics.
5998      (void)Result;
5999      continue;
6000    }
6001
6002    // Multiple matches; we can't resolve to a single declaration.
6003    if (Matched)
6004      return 0;
6005
6006    Matched = Specialization;
6007  }
6008
6009  return Matched;
6010}
6011
6012/// \brief Add a single candidate to the overload set.
6013static void AddOverloadedCallCandidate(Sema &S,
6014                                       DeclAccessPair FoundDecl,
6015                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
6016                                       Expr **Args, unsigned NumArgs,
6017                                       OverloadCandidateSet &CandidateSet,
6018                                       bool PartialOverloading) {
6019  NamedDecl *Callee = FoundDecl.getDecl();
6020  if (isa<UsingShadowDecl>(Callee))
6021    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6022
6023  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
6024    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
6025    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
6026                           false, PartialOverloading);
6027    return;
6028  }
6029
6030  if (FunctionTemplateDecl *FuncTemplate
6031      = dyn_cast<FunctionTemplateDecl>(Callee)) {
6032    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6033                                   ExplicitTemplateArgs,
6034                                   Args, NumArgs, CandidateSet);
6035    return;
6036  }
6037
6038  assert(false && "unhandled case in overloaded call candidate");
6039
6040  // do nothing?
6041}
6042
6043/// \brief Add the overload candidates named by callee and/or found by argument
6044/// dependent lookup to the given overload set.
6045void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
6046                                       Expr **Args, unsigned NumArgs,
6047                                       OverloadCandidateSet &CandidateSet,
6048                                       bool PartialOverloading) {
6049
6050#ifndef NDEBUG
6051  // Verify that ArgumentDependentLookup is consistent with the rules
6052  // in C++0x [basic.lookup.argdep]p3:
6053  //
6054  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
6055  //   and let Y be the lookup set produced by argument dependent
6056  //   lookup (defined as follows). If X contains
6057  //
6058  //     -- a declaration of a class member, or
6059  //
6060  //     -- a block-scope function declaration that is not a
6061  //        using-declaration, or
6062  //
6063  //     -- a declaration that is neither a function or a function
6064  //        template
6065  //
6066  //   then Y is empty.
6067
6068  if (ULE->requiresADL()) {
6069    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6070           E = ULE->decls_end(); I != E; ++I) {
6071      assert(!(*I)->getDeclContext()->isRecord());
6072      assert(isa<UsingShadowDecl>(*I) ||
6073             !(*I)->getDeclContext()->isFunctionOrMethod());
6074      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
6075    }
6076  }
6077#endif
6078
6079  // It would be nice to avoid this copy.
6080  TemplateArgumentListInfo TABuffer;
6081  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6082  if (ULE->hasExplicitTemplateArgs()) {
6083    ULE->copyTemplateArgumentsInto(TABuffer);
6084    ExplicitTemplateArgs = &TABuffer;
6085  }
6086
6087  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6088         E = ULE->decls_end(); I != E; ++I)
6089    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
6090                               Args, NumArgs, CandidateSet,
6091                               PartialOverloading);
6092
6093  if (ULE->requiresADL())
6094    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6095                                         Args, NumArgs,
6096                                         ExplicitTemplateArgs,
6097                                         CandidateSet,
6098                                         PartialOverloading);
6099}
6100
6101static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6102                                      Expr **Args, unsigned NumArgs) {
6103  Fn->Destroy(SemaRef.Context);
6104  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6105    Args[Arg]->Destroy(SemaRef.Context);
6106  return SemaRef.ExprError();
6107}
6108
6109/// Attempts to recover from a call where no functions were found.
6110///
6111/// Returns true if new candidates were found.
6112static Sema::OwningExprResult
6113BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
6114                      UnresolvedLookupExpr *ULE,
6115                      SourceLocation LParenLoc,
6116                      Expr **Args, unsigned NumArgs,
6117                      SourceLocation *CommaLocs,
6118                      SourceLocation RParenLoc) {
6119
6120  CXXScopeSpec SS;
6121  if (ULE->getQualifier()) {
6122    SS.setScopeRep(ULE->getQualifier());
6123    SS.setRange(ULE->getQualifierRange());
6124  }
6125
6126  TemplateArgumentListInfo TABuffer;
6127  const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6128  if (ULE->hasExplicitTemplateArgs()) {
6129    ULE->copyTemplateArgumentsInto(TABuffer);
6130    ExplicitTemplateArgs = &TABuffer;
6131  }
6132
6133  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6134                 Sema::LookupOrdinaryName);
6135  if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
6136    return Destroy(SemaRef, Fn, Args, NumArgs);
6137
6138  assert(!R.empty() && "lookup results empty despite recovery");
6139
6140  // Build an implicit member call if appropriate.  Just drop the
6141  // casts and such from the call, we don't really care.
6142  Sema::OwningExprResult NewFn = SemaRef.ExprError();
6143  if ((*R.begin())->isCXXClassMember())
6144    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6145  else if (ExplicitTemplateArgs)
6146    NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6147  else
6148    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6149
6150  if (NewFn.isInvalid())
6151    return Destroy(SemaRef, Fn, Args, NumArgs);
6152
6153  Fn->Destroy(SemaRef.Context);
6154
6155  // This shouldn't cause an infinite loop because we're giving it
6156  // an expression with non-empty lookup results, which should never
6157  // end up here.
6158  return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6159                         Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6160                               CommaLocs, RParenLoc);
6161}
6162
6163/// ResolveOverloadedCallFn - Given the call expression that calls Fn
6164/// (which eventually refers to the declaration Func) and the call
6165/// arguments Args/NumArgs, attempt to resolve the function call down
6166/// to a specific function. If overload resolution succeeds, returns
6167/// the function declaration produced by overload
6168/// resolution. Otherwise, emits diagnostics, deletes all of the
6169/// arguments and Fn, and returns NULL.
6170Sema::OwningExprResult
6171Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
6172                              SourceLocation LParenLoc,
6173                              Expr **Args, unsigned NumArgs,
6174                              SourceLocation *CommaLocs,
6175                              SourceLocation RParenLoc) {
6176#ifndef NDEBUG
6177  if (ULE->requiresADL()) {
6178    // To do ADL, we must have found an unqualified name.
6179    assert(!ULE->getQualifier() && "qualified name with ADL");
6180
6181    // We don't perform ADL for implicit declarations of builtins.
6182    // Verify that this was correctly set up.
6183    FunctionDecl *F;
6184    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6185        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6186        F->getBuiltinID() && F->isImplicit())
6187      assert(0 && "performing ADL for builtin");
6188
6189    // We don't perform ADL in C.
6190    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6191  }
6192#endif
6193
6194  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
6195
6196  // Add the functions denoted by the callee to the set of candidate
6197  // functions, including those from argument-dependent lookup.
6198  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
6199
6200  // If we found nothing, try to recover.
6201  // AddRecoveryCallCandidates diagnoses the error itself, so we just
6202  // bailout out if it fails.
6203  if (CandidateSet.empty())
6204    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
6205                                 CommaLocs, RParenLoc);
6206
6207  OverloadCandidateSet::iterator Best;
6208  switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
6209  case OR_Success: {
6210    FunctionDecl *FDecl = Best->Function;
6211    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
6212    DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
6213    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
6214    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6215  }
6216
6217  case OR_No_Viable_Function:
6218    Diag(Fn->getSourceRange().getBegin(),
6219         diag::err_ovl_no_viable_function_in_call)
6220      << ULE->getName() << Fn->getSourceRange();
6221    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6222    break;
6223
6224  case OR_Ambiguous:
6225    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
6226      << ULE->getName() << Fn->getSourceRange();
6227    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
6228    break;
6229
6230  case OR_Deleted:
6231    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6232      << Best->Function->isDeleted()
6233      << ULE->getName()
6234      << Fn->getSourceRange();
6235    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6236    break;
6237  }
6238
6239  // Overload resolution failed. Destroy all of the subexpressions and
6240  // return NULL.
6241  Fn->Destroy(Context);
6242  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6243    Args[Arg]->Destroy(Context);
6244  return ExprError();
6245}
6246
6247static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
6248  return Functions.size() > 1 ||
6249    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6250}
6251
6252/// \brief Create a unary operation that may resolve to an overloaded
6253/// operator.
6254///
6255/// \param OpLoc The location of the operator itself (e.g., '*').
6256///
6257/// \param OpcIn The UnaryOperator::Opcode that describes this
6258/// operator.
6259///
6260/// \param Functions The set of non-member functions that will be
6261/// considered by overload resolution. The caller needs to build this
6262/// set based on the context using, e.g.,
6263/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6264/// set should not contain any member functions; those will be added
6265/// by CreateOverloadedUnaryOp().
6266///
6267/// \param input The input argument.
6268Sema::OwningExprResult
6269Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6270                              const UnresolvedSetImpl &Fns,
6271                              ExprArg input) {
6272  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6273  Expr *Input = (Expr *)input.get();
6274
6275  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6276  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6277  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6278
6279  Expr *Args[2] = { Input, 0 };
6280  unsigned NumArgs = 1;
6281
6282  // For post-increment and post-decrement, add the implicit '0' as
6283  // the second argument, so that we know this is a post-increment or
6284  // post-decrement.
6285  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6286    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
6287    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
6288                                           SourceLocation());
6289    NumArgs = 2;
6290  }
6291
6292  if (Input->isTypeDependent()) {
6293    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
6294    UnresolvedLookupExpr *Fn
6295      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
6296                                     0, SourceRange(), OpName, OpLoc,
6297                                     /*ADL*/ true, IsOverloaded(Fns),
6298                                     Fns.begin(), Fns.end());
6299    input.release();
6300    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6301                                                   &Args[0], NumArgs,
6302                                                   Context.DependentTy,
6303                                                   OpLoc));
6304  }
6305
6306  // Build an empty overload set.
6307  OverloadCandidateSet CandidateSet(OpLoc);
6308
6309  // Add the candidates from the given function set.
6310  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
6311
6312  // Add operator candidates that are member functions.
6313  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6314
6315  // Add candidates from ADL.
6316  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6317                                       Args, NumArgs,
6318                                       /*ExplicitTemplateArgs*/ 0,
6319                                       CandidateSet);
6320
6321  // Add builtin operator candidates.
6322  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6323
6324  // Perform overload resolution.
6325  OverloadCandidateSet::iterator Best;
6326  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
6327  case OR_Success: {
6328    // We found a built-in operator or an overloaded operator.
6329    FunctionDecl *FnDecl = Best->Function;
6330
6331    if (FnDecl) {
6332      // We matched an overloaded operator. Build a call to that
6333      // operator.
6334
6335      // Convert the arguments.
6336      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
6337        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
6338
6339        if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6340                                                Best->FoundDecl, Method))
6341          return ExprError();
6342      } else {
6343        // Convert the arguments.
6344        OwningExprResult InputInit
6345          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6346                                                      FnDecl->getParamDecl(0)),
6347                                      SourceLocation(),
6348                                      move(input));
6349        if (InputInit.isInvalid())
6350          return ExprError();
6351
6352        input = move(InputInit);
6353        Input = (Expr *)input.get();
6354      }
6355
6356      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6357
6358      // Determine the result type
6359      QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
6360
6361      // Build the actual expression node.
6362      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6363                                               SourceLocation());
6364      UsualUnaryConversions(FnExpr);
6365
6366      input.release();
6367      Args[0] = Input;
6368      ExprOwningPtr<CallExpr> TheCall(this,
6369        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6370                                          Args, NumArgs, ResultTy, OpLoc));
6371
6372      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6373                              FnDecl))
6374        return ExprError();
6375
6376      return MaybeBindToTemporary(TheCall.release());
6377    } else {
6378      // We matched a built-in operator. Convert the arguments, then
6379      // break out so that we will build the appropriate built-in
6380      // operator node.
6381        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
6382                                      Best->Conversions[0], AA_Passing))
6383          return ExprError();
6384
6385        break;
6386      }
6387    }
6388
6389    case OR_No_Viable_Function:
6390      // No viable function; fall through to handling this as a
6391      // built-in operator, which will produce an error message for us.
6392      break;
6393
6394    case OR_Ambiguous:
6395      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
6396          << UnaryOperator::getOpcodeStr(Opc)
6397          << Input->getSourceRange();
6398      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
6399                              UnaryOperator::getOpcodeStr(Opc), OpLoc);
6400      return ExprError();
6401
6402    case OR_Deleted:
6403      Diag(OpLoc, diag::err_ovl_deleted_oper)
6404        << Best->Function->isDeleted()
6405        << UnaryOperator::getOpcodeStr(Opc)
6406        << Input->getSourceRange();
6407      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6408      return ExprError();
6409    }
6410
6411  // Either we found no viable overloaded operator or we matched a
6412  // built-in operator. In either case, fall through to trying to
6413  // build a built-in operation.
6414  input.release();
6415  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6416}
6417
6418/// \brief Create a binary operation that may resolve to an overloaded
6419/// operator.
6420///
6421/// \param OpLoc The location of the operator itself (e.g., '+').
6422///
6423/// \param OpcIn The BinaryOperator::Opcode that describes this
6424/// operator.
6425///
6426/// \param Functions The set of non-member functions that will be
6427/// considered by overload resolution. The caller needs to build this
6428/// set based on the context using, e.g.,
6429/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6430/// set should not contain any member functions; those will be added
6431/// by CreateOverloadedBinOp().
6432///
6433/// \param LHS Left-hand argument.
6434/// \param RHS Right-hand argument.
6435Sema::OwningExprResult
6436Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
6437                            unsigned OpcIn,
6438                            const UnresolvedSetImpl &Fns,
6439                            Expr *LHS, Expr *RHS) {
6440  Expr *Args[2] = { LHS, RHS };
6441  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
6442
6443  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6444  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6445  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6446
6447  // If either side is type-dependent, create an appropriate dependent
6448  // expression.
6449  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6450    if (Fns.empty()) {
6451      // If there are no functions to store, just build a dependent
6452      // BinaryOperator or CompoundAssignment.
6453      if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6454        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6455                                                  Context.DependentTy, OpLoc));
6456
6457      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6458                                                        Context.DependentTy,
6459                                                        Context.DependentTy,
6460                                                        Context.DependentTy,
6461                                                        OpLoc));
6462    }
6463
6464    // FIXME: save results of ADL from here?
6465    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
6466    UnresolvedLookupExpr *Fn
6467      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
6468                                     0, SourceRange(), OpName, OpLoc,
6469                                     /*ADL*/ true, IsOverloaded(Fns),
6470                                     Fns.begin(), Fns.end());
6471    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6472                                                   Args, 2,
6473                                                   Context.DependentTy,
6474                                                   OpLoc));
6475  }
6476
6477  // If this is the .* operator, which is not overloadable, just
6478  // create a built-in binary operator.
6479  if (Opc == BinaryOperator::PtrMemD)
6480    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
6481
6482  // If this is the assignment operator, we only perform overload resolution
6483  // if the left-hand side is a class or enumeration type. This is actually
6484  // a hack. The standard requires that we do overload resolution between the
6485  // various built-in candidates, but as DR507 points out, this can lead to
6486  // problems. So we do it this way, which pretty much follows what GCC does.
6487  // Note that we go the traditional code path for compound assignment forms.
6488  if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
6489    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
6490
6491  // Build an empty overload set.
6492  OverloadCandidateSet CandidateSet(OpLoc);
6493
6494  // Add the candidates from the given function set.
6495  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
6496
6497  // Add operator candidates that are member functions.
6498  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6499
6500  // Add candidates from ADL.
6501  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6502                                       Args, 2,
6503                                       /*ExplicitTemplateArgs*/ 0,
6504                                       CandidateSet);
6505
6506  // Add builtin operator candidates.
6507  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6508
6509  // Perform overload resolution.
6510  OverloadCandidateSet::iterator Best;
6511  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
6512    case OR_Success: {
6513      // We found a built-in operator or an overloaded operator.
6514      FunctionDecl *FnDecl = Best->Function;
6515
6516      if (FnDecl) {
6517        // We matched an overloaded operator. Build a call to that
6518        // operator.
6519
6520        // Convert the arguments.
6521        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
6522          // Best->Access is only meaningful for class members.
6523          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
6524
6525          OwningExprResult Arg1
6526            = PerformCopyInitialization(
6527                                        InitializedEntity::InitializeParameter(
6528                                                        FnDecl->getParamDecl(0)),
6529                                        SourceLocation(),
6530                                        Owned(Args[1]));
6531          if (Arg1.isInvalid())
6532            return ExprError();
6533
6534          if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
6535                                                  Best->FoundDecl, Method))
6536            return ExprError();
6537
6538          Args[1] = RHS = Arg1.takeAs<Expr>();
6539        } else {
6540          // Convert the arguments.
6541          OwningExprResult Arg0
6542            = PerformCopyInitialization(
6543                                        InitializedEntity::InitializeParameter(
6544                                                        FnDecl->getParamDecl(0)),
6545                                        SourceLocation(),
6546                                        Owned(Args[0]));
6547          if (Arg0.isInvalid())
6548            return ExprError();
6549
6550          OwningExprResult Arg1
6551            = PerformCopyInitialization(
6552                                        InitializedEntity::InitializeParameter(
6553                                                        FnDecl->getParamDecl(1)),
6554                                        SourceLocation(),
6555                                        Owned(Args[1]));
6556          if (Arg1.isInvalid())
6557            return ExprError();
6558          Args[0] = LHS = Arg0.takeAs<Expr>();
6559          Args[1] = RHS = Arg1.takeAs<Expr>();
6560        }
6561
6562        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6563
6564        // Determine the result type
6565        QualType ResultTy
6566          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6567        ResultTy = ResultTy.getNonReferenceType();
6568
6569        // Build the actual expression node.
6570        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6571                                                 OpLoc);
6572        UsualUnaryConversions(FnExpr);
6573
6574        ExprOwningPtr<CXXOperatorCallExpr>
6575          TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6576                                                          Args, 2, ResultTy,
6577                                                          OpLoc));
6578
6579        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6580                                FnDecl))
6581          return ExprError();
6582
6583        return MaybeBindToTemporary(TheCall.release());
6584      } else {
6585        // We matched a built-in operator. Convert the arguments, then
6586        // break out so that we will build the appropriate built-in
6587        // operator node.
6588        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
6589                                      Best->Conversions[0], AA_Passing) ||
6590            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
6591                                      Best->Conversions[1], AA_Passing))
6592          return ExprError();
6593
6594        break;
6595      }
6596    }
6597
6598    case OR_No_Viable_Function: {
6599      // C++ [over.match.oper]p9:
6600      //   If the operator is the operator , [...] and there are no
6601      //   viable functions, then the operator is assumed to be the
6602      //   built-in operator and interpreted according to clause 5.
6603      if (Opc == BinaryOperator::Comma)
6604        break;
6605
6606      // For class as left operand for assignment or compound assigment operator
6607      // do not fall through to handling in built-in, but report that no overloaded
6608      // assignment operator found
6609      OwningExprResult Result = ExprError();
6610      if (Args[0]->getType()->isRecordType() &&
6611          Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
6612        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
6613             << BinaryOperator::getOpcodeStr(Opc)
6614             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6615      } else {
6616        // No viable function; try to create a built-in operation, which will
6617        // produce an error. Then, show the non-viable candidates.
6618        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
6619      }
6620      assert(Result.isInvalid() &&
6621             "C++ binary operator overloading is missing candidates!");
6622      if (Result.isInvalid())
6623        PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
6624                                BinaryOperator::getOpcodeStr(Opc), OpLoc);
6625      return move(Result);
6626    }
6627
6628    case OR_Ambiguous:
6629      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
6630          << BinaryOperator::getOpcodeStr(Opc)
6631          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6632      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
6633                              BinaryOperator::getOpcodeStr(Opc), OpLoc);
6634      return ExprError();
6635
6636    case OR_Deleted:
6637      Diag(OpLoc, diag::err_ovl_deleted_oper)
6638        << Best->Function->isDeleted()
6639        << BinaryOperator::getOpcodeStr(Opc)
6640        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6641      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
6642      return ExprError();
6643  }
6644
6645  // We matched a built-in operator; build it.
6646  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
6647}
6648
6649Action::OwningExprResult
6650Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6651                                         SourceLocation RLoc,
6652                                         ExprArg Base, ExprArg Idx) {
6653  Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6654                    static_cast<Expr*>(Idx.get()) };
6655  DeclarationName OpName =
6656      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6657
6658  // If either side is type-dependent, create an appropriate dependent
6659  // expression.
6660  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6661
6662    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
6663    UnresolvedLookupExpr *Fn
6664      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
6665                                     0, SourceRange(), OpName, LLoc,
6666                                     /*ADL*/ true, /*Overloaded*/ false,
6667                                     UnresolvedSetIterator(),
6668                                     UnresolvedSetIterator());
6669    // Can't add any actual overloads yet
6670
6671    Base.release();
6672    Idx.release();
6673    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6674                                                   Args, 2,
6675                                                   Context.DependentTy,
6676                                                   RLoc));
6677  }
6678
6679  // Build an empty overload set.
6680  OverloadCandidateSet CandidateSet(LLoc);
6681
6682  // Subscript can only be overloaded as a member function.
6683
6684  // Add operator candidates that are member functions.
6685  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6686
6687  // Add builtin operator candidates.
6688  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6689
6690  // Perform overload resolution.
6691  OverloadCandidateSet::iterator Best;
6692  switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6693    case OR_Success: {
6694      // We found a built-in operator or an overloaded operator.
6695      FunctionDecl *FnDecl = Best->Function;
6696
6697      if (FnDecl) {
6698        // We matched an overloaded operator. Build a call to that
6699        // operator.
6700
6701        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
6702        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
6703
6704        // Convert the arguments.
6705        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
6706        if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
6707                                                Best->FoundDecl, Method))
6708          return ExprError();
6709
6710        // Convert the arguments.
6711        OwningExprResult InputInit
6712          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6713                                                      FnDecl->getParamDecl(0)),
6714                                      SourceLocation(),
6715                                      Owned(Args[1]));
6716        if (InputInit.isInvalid())
6717          return ExprError();
6718
6719        Args[1] = InputInit.takeAs<Expr>();
6720
6721        // Determine the result type
6722        QualType ResultTy
6723          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6724        ResultTy = ResultTy.getNonReferenceType();
6725
6726        // Build the actual expression node.
6727        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6728                                                 LLoc);
6729        UsualUnaryConversions(FnExpr);
6730
6731        Base.release();
6732        Idx.release();
6733        ExprOwningPtr<CXXOperatorCallExpr>
6734          TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6735                                                          FnExpr, Args, 2,
6736                                                          ResultTy, RLoc));
6737
6738        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6739                                FnDecl))
6740          return ExprError();
6741
6742        return MaybeBindToTemporary(TheCall.release());
6743      } else {
6744        // We matched a built-in operator. Convert the arguments, then
6745        // break out so that we will build the appropriate built-in
6746        // operator node.
6747        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
6748                                      Best->Conversions[0], AA_Passing) ||
6749            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
6750                                      Best->Conversions[1], AA_Passing))
6751          return ExprError();
6752
6753        break;
6754      }
6755    }
6756
6757    case OR_No_Viable_Function: {
6758      if (CandidateSet.empty())
6759        Diag(LLoc, diag::err_ovl_no_oper)
6760          << Args[0]->getType() << /*subscript*/ 0
6761          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6762      else
6763        Diag(LLoc, diag::err_ovl_no_viable_subscript)
6764          << Args[0]->getType()
6765          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6766      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
6767                              "[]", LLoc);
6768      return ExprError();
6769    }
6770
6771    case OR_Ambiguous:
6772      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
6773          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6774      PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
6775                              "[]", LLoc);
6776      return ExprError();
6777
6778    case OR_Deleted:
6779      Diag(LLoc, diag::err_ovl_deleted_oper)
6780        << Best->Function->isDeleted() << "[]"
6781        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6782      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
6783                              "[]", LLoc);
6784      return ExprError();
6785    }
6786
6787  // We matched a built-in operator; build it.
6788  Base.release();
6789  Idx.release();
6790  return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6791                                         Owned(Args[1]), RLoc);
6792}
6793
6794/// BuildCallToMemberFunction - Build a call to a member
6795/// function. MemExpr is the expression that refers to the member
6796/// function (and includes the object parameter), Args/NumArgs are the
6797/// arguments to the function call (not including the object
6798/// parameter). The caller needs to validate that the member
6799/// expression refers to a member function or an overloaded member
6800/// function.
6801Sema::OwningExprResult
6802Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6803                                SourceLocation LParenLoc, Expr **Args,
6804                                unsigned NumArgs, SourceLocation *CommaLocs,
6805                                SourceLocation RParenLoc) {
6806  // Dig out the member expression. This holds both the object
6807  // argument and the member function we're referring to.
6808  Expr *NakedMemExpr = MemExprE->IgnoreParens();
6809
6810  MemberExpr *MemExpr;
6811  CXXMethodDecl *Method = 0;
6812  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
6813  NestedNameSpecifier *Qualifier = 0;
6814  if (isa<MemberExpr>(NakedMemExpr)) {
6815    MemExpr = cast<MemberExpr>(NakedMemExpr);
6816    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
6817    FoundDecl = MemExpr->getFoundDecl();
6818    Qualifier = MemExpr->getQualifier();
6819  } else {
6820    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
6821    Qualifier = UnresExpr->getQualifier();
6822
6823    QualType ObjectType = UnresExpr->getBaseType();
6824
6825    // Add overload candidates
6826    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
6827
6828    // FIXME: avoid copy.
6829    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6830    if (UnresExpr->hasExplicitTemplateArgs()) {
6831      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6832      TemplateArgs = &TemplateArgsBuffer;
6833    }
6834
6835    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6836           E = UnresExpr->decls_end(); I != E; ++I) {
6837
6838      NamedDecl *Func = *I;
6839      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6840      if (isa<UsingShadowDecl>(Func))
6841        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6842
6843      if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
6844        // If explicit template arguments were provided, we can't call a
6845        // non-template member function.
6846        if (TemplateArgs)
6847          continue;
6848
6849        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
6850                           Args, NumArgs,
6851                           CandidateSet, /*SuppressUserConversions=*/false);
6852      } else {
6853        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
6854                                   I.getPair(), ActingDC, TemplateArgs,
6855                                   ObjectType, Args, NumArgs,
6856                                   CandidateSet,
6857                                   /*SuppressUsedConversions=*/false);
6858      }
6859    }
6860
6861    DeclarationName DeclName = UnresExpr->getMemberName();
6862
6863    OverloadCandidateSet::iterator Best;
6864    switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
6865    case OR_Success:
6866      Method = cast<CXXMethodDecl>(Best->Function);
6867      FoundDecl = Best->FoundDecl;
6868      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
6869      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
6870      break;
6871
6872    case OR_No_Viable_Function:
6873      Diag(UnresExpr->getMemberLoc(),
6874           diag::err_ovl_no_viable_member_function_in_call)
6875        << DeclName << MemExprE->getSourceRange();
6876      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6877      // FIXME: Leaking incoming expressions!
6878      return ExprError();
6879
6880    case OR_Ambiguous:
6881      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
6882        << DeclName << MemExprE->getSourceRange();
6883      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6884      // FIXME: Leaking incoming expressions!
6885      return ExprError();
6886
6887    case OR_Deleted:
6888      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
6889        << Best->Function->isDeleted()
6890        << DeclName << MemExprE->getSourceRange();
6891      PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
6892      // FIXME: Leaking incoming expressions!
6893      return ExprError();
6894    }
6895
6896    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
6897
6898    // If overload resolution picked a static member, build a
6899    // non-member call based on that function.
6900    if (Method->isStatic()) {
6901      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6902                                   Args, NumArgs, RParenLoc);
6903    }
6904
6905    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
6906  }
6907
6908  assert(Method && "Member call to something that isn't a method?");
6909  ExprOwningPtr<CXXMemberCallExpr>
6910    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
6911                                                  NumArgs,
6912                                  Method->getResultType().getNonReferenceType(),
6913                                  RParenLoc));
6914
6915  // Check for a valid return type.
6916  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6917                          TheCall.get(), Method))
6918    return ExprError();
6919
6920  // Convert the object argument (for a non-static member function call).
6921  // We only need to do this if there was actually an overload; otherwise
6922  // it was done at lookup.
6923  Expr *ObjectArg = MemExpr->getBase();
6924  if (!Method->isStatic() &&
6925      PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6926                                          FoundDecl, Method))
6927    return ExprError();
6928  MemExpr->setBase(ObjectArg);
6929
6930  // Convert the rest of the arguments
6931  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
6932  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
6933                              RParenLoc))
6934    return ExprError();
6935
6936  if (CheckFunctionCall(Method, TheCall.get()))
6937    return ExprError();
6938
6939  return MaybeBindToTemporary(TheCall.release());
6940}
6941
6942/// BuildCallToObjectOfClassType - Build a call to an object of class
6943/// type (C++ [over.call.object]), which can end up invoking an
6944/// overloaded function call operator (@c operator()) or performing a
6945/// user-defined conversion on the object argument.
6946Sema::ExprResult
6947Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
6948                                   SourceLocation LParenLoc,
6949                                   Expr **Args, unsigned NumArgs,
6950                                   SourceLocation *CommaLocs,
6951                                   SourceLocation RParenLoc) {
6952  assert(Object->getType()->isRecordType() && "Requires object type argument");
6953  const RecordType *Record = Object->getType()->getAs<RecordType>();
6954
6955  // C++ [over.call.object]p1:
6956  //  If the primary-expression E in the function call syntax
6957  //  evaluates to a class object of type "cv T", then the set of
6958  //  candidate functions includes at least the function call
6959  //  operators of T. The function call operators of T are obtained by
6960  //  ordinary lookup of the name operator() in the context of
6961  //  (E).operator().
6962  OverloadCandidateSet CandidateSet(LParenLoc);
6963  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
6964
6965  if (RequireCompleteType(LParenLoc, Object->getType(),
6966                          PDiag(diag::err_incomplete_object_call)
6967                          << Object->getSourceRange()))
6968    return true;
6969
6970  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6971  LookupQualifiedName(R, Record->getDecl());
6972  R.suppressDiagnostics();
6973
6974  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
6975       Oper != OperEnd; ++Oper) {
6976    AddMethodCandidate(Oper.getPair(), Object->getType(),
6977                       Args, NumArgs, CandidateSet,
6978                       /*SuppressUserConversions=*/ false);
6979  }
6980
6981  // C++ [over.call.object]p2:
6982  //   In addition, for each conversion function declared in T of the
6983  //   form
6984  //
6985  //        operator conversion-type-id () cv-qualifier;
6986  //
6987  //   where cv-qualifier is the same cv-qualification as, or a
6988  //   greater cv-qualification than, cv, and where conversion-type-id
6989  //   denotes the type "pointer to function of (P1,...,Pn) returning
6990  //   R", or the type "reference to pointer to function of
6991  //   (P1,...,Pn) returning R", or the type "reference to function
6992  //   of (P1,...,Pn) returning R", a surrogate call function [...]
6993  //   is also considered as a candidate function. Similarly,
6994  //   surrogate call functions are added to the set of candidate
6995  //   functions for each conversion function declared in an
6996  //   accessible base class provided the function is not hidden
6997  //   within T by another intervening declaration.
6998  const UnresolvedSetImpl *Conversions
6999    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
7000  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
7001         E = Conversions->end(); I != E; ++I) {
7002    NamedDecl *D = *I;
7003    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7004    if (isa<UsingShadowDecl>(D))
7005      D = cast<UsingShadowDecl>(D)->getTargetDecl();
7006
7007    // Skip over templated conversion functions; they aren't
7008    // surrogates.
7009    if (isa<FunctionTemplateDecl>(D))
7010      continue;
7011
7012    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7013
7014    // Strip the reference type (if any) and then the pointer type (if
7015    // any) to get down to what might be a function type.
7016    QualType ConvType = Conv->getConversionType().getNonReferenceType();
7017    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7018      ConvType = ConvPtrType->getPointeeType();
7019
7020    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
7021      AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
7022                            Object->getType(), Args, NumArgs,
7023                            CandidateSet);
7024  }
7025
7026  // Perform overload resolution.
7027  OverloadCandidateSet::iterator Best;
7028  switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
7029  case OR_Success:
7030    // Overload resolution succeeded; we'll build the appropriate call
7031    // below.
7032    break;
7033
7034  case OR_No_Viable_Function:
7035    if (CandidateSet.empty())
7036      Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7037        << Object->getType() << /*call*/ 1
7038        << Object->getSourceRange();
7039    else
7040      Diag(Object->getSourceRange().getBegin(),
7041           diag::err_ovl_no_viable_object_call)
7042        << Object->getType() << Object->getSourceRange();
7043    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
7044    break;
7045
7046  case OR_Ambiguous:
7047    Diag(Object->getSourceRange().getBegin(),
7048         diag::err_ovl_ambiguous_object_call)
7049      << Object->getType() << Object->getSourceRange();
7050    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
7051    break;
7052
7053  case OR_Deleted:
7054    Diag(Object->getSourceRange().getBegin(),
7055         diag::err_ovl_deleted_object_call)
7056      << Best->Function->isDeleted()
7057      << Object->getType() << Object->getSourceRange();
7058    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
7059    break;
7060  }
7061
7062  if (Best == CandidateSet.end()) {
7063    // We had an error; delete all of the subexpressions and return
7064    // the error.
7065    Object->Destroy(Context);
7066    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7067      Args[ArgIdx]->Destroy(Context);
7068    return true;
7069  }
7070
7071  if (Best->Function == 0) {
7072    // Since there is no function declaration, this is one of the
7073    // surrogate candidates. Dig out the conversion function.
7074    CXXConversionDecl *Conv
7075      = cast<CXXConversionDecl>(
7076                         Best->Conversions[0].UserDefined.ConversionFunction);
7077
7078    CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
7079    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
7080
7081    // We selected one of the surrogate functions that converts the
7082    // object parameter to a function pointer. Perform the conversion
7083    // on the object argument, then let ActOnCallExpr finish the job.
7084
7085    // Create an implicit member expr to refer to the conversion operator.
7086    // and then call it.
7087    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7088                                                   Conv);
7089
7090    return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
7091                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
7092                         CommaLocs, RParenLoc).result();
7093  }
7094
7095  CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
7096  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
7097
7098  // We found an overloaded operator(). Build a CXXOperatorCallExpr
7099  // that calls this method, using Object for the implicit object
7100  // parameter and passing along the remaining arguments.
7101  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
7102  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
7103
7104  unsigned NumArgsInProto = Proto->getNumArgs();
7105  unsigned NumArgsToCheck = NumArgs;
7106
7107  // Build the full argument list for the method call (the
7108  // implicit object parameter is placed at the beginning of the
7109  // list).
7110  Expr **MethodArgs;
7111  if (NumArgs < NumArgsInProto) {
7112    NumArgsToCheck = NumArgsInProto;
7113    MethodArgs = new Expr*[NumArgsInProto + 1];
7114  } else {
7115    MethodArgs = new Expr*[NumArgs + 1];
7116  }
7117  MethodArgs[0] = Object;
7118  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7119    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
7120
7121  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
7122                                          SourceLocation());
7123  UsualUnaryConversions(NewFn);
7124
7125  // Once we've built TheCall, all of the expressions are properly
7126  // owned.
7127  QualType ResultTy = Method->getResultType().getNonReferenceType();
7128  ExprOwningPtr<CXXOperatorCallExpr>
7129    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7130                                                    MethodArgs, NumArgs + 1,
7131                                                    ResultTy, RParenLoc));
7132  delete [] MethodArgs;
7133
7134  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7135                          Method))
7136    return true;
7137
7138  // We may have default arguments. If so, we need to allocate more
7139  // slots in the call for them.
7140  if (NumArgs < NumArgsInProto)
7141    TheCall->setNumArgs(Context, NumArgsInProto + 1);
7142  else if (NumArgs > NumArgsInProto)
7143    NumArgsToCheck = NumArgsInProto;
7144
7145  bool IsError = false;
7146
7147  // Initialize the implicit object parameter.
7148  IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
7149                                                 Best->FoundDecl, Method);
7150  TheCall->setArg(0, Object);
7151
7152
7153  // Check the argument types.
7154  for (unsigned i = 0; i != NumArgsToCheck; i++) {
7155    Expr *Arg;
7156    if (i < NumArgs) {
7157      Arg = Args[i];
7158
7159      // Pass the argument.
7160
7161      OwningExprResult InputInit
7162        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7163                                                    Method->getParamDecl(i)),
7164                                    SourceLocation(), Owned(Arg));
7165
7166      IsError |= InputInit.isInvalid();
7167      Arg = InputInit.takeAs<Expr>();
7168    } else {
7169      OwningExprResult DefArg
7170        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7171      if (DefArg.isInvalid()) {
7172        IsError = true;
7173        break;
7174      }
7175
7176      Arg = DefArg.takeAs<Expr>();
7177    }
7178
7179    TheCall->setArg(i + 1, Arg);
7180  }
7181
7182  // If this is a variadic call, handle args passed through "...".
7183  if (Proto->isVariadic()) {
7184    // Promote the arguments (C99 6.5.2.2p7).
7185    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7186      Expr *Arg = Args[i];
7187      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
7188      TheCall->setArg(i + 1, Arg);
7189    }
7190  }
7191
7192  if (IsError) return true;
7193
7194  if (CheckFunctionCall(Method, TheCall.get()))
7195    return true;
7196
7197  return MaybeBindToTemporary(TheCall.release()).result();
7198}
7199
7200/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
7201///  (if one exists), where @c Base is an expression of class type and
7202/// @c Member is the name of the member we're trying to find.
7203Sema::OwningExprResult
7204Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7205  Expr *Base = static_cast<Expr *>(BaseIn.get());
7206  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
7207
7208  SourceLocation Loc = Base->getExprLoc();
7209
7210  // C++ [over.ref]p1:
7211  //
7212  //   [...] An expression x->m is interpreted as (x.operator->())->m
7213  //   for a class object x of type T if T::operator->() exists and if
7214  //   the operator is selected as the best match function by the
7215  //   overload resolution mechanism (13.3).
7216  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
7217  OverloadCandidateSet CandidateSet(Loc);
7218  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
7219
7220  if (RequireCompleteType(Loc, Base->getType(),
7221                          PDiag(diag::err_typecheck_incomplete_tag)
7222                            << Base->getSourceRange()))
7223    return ExprError();
7224
7225  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7226  LookupQualifiedName(R, BaseRecord->getDecl());
7227  R.suppressDiagnostics();
7228
7229  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
7230       Oper != OperEnd; ++Oper) {
7231    AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
7232                       /*SuppressUserConversions=*/false);
7233  }
7234
7235  // Perform overload resolution.
7236  OverloadCandidateSet::iterator Best;
7237  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
7238  case OR_Success:
7239    // Overload resolution succeeded; we'll build the call below.
7240    break;
7241
7242  case OR_No_Viable_Function:
7243    if (CandidateSet.empty())
7244      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7245        << Base->getType() << Base->getSourceRange();
7246    else
7247      Diag(OpLoc, diag::err_ovl_no_viable_oper)
7248        << "operator->" << Base->getSourceRange();
7249    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
7250    return ExprError();
7251
7252  case OR_Ambiguous:
7253    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
7254      << "->" << Base->getSourceRange();
7255    PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
7256    return ExprError();
7257
7258  case OR_Deleted:
7259    Diag(OpLoc,  diag::err_ovl_deleted_oper)
7260      << Best->Function->isDeleted()
7261      << "->" << Base->getSourceRange();
7262    PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
7263    return ExprError();
7264  }
7265
7266  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
7267  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7268
7269  // Convert the object parameter.
7270  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
7271  if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7272                                          Best->FoundDecl, Method))
7273    return ExprError();
7274
7275  // No concerns about early exits now.
7276  BaseIn.release();
7277
7278  // Build the operator call.
7279  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7280                                           SourceLocation());
7281  UsualUnaryConversions(FnExpr);
7282
7283  QualType ResultTy = Method->getResultType().getNonReferenceType();
7284  ExprOwningPtr<CXXOperatorCallExpr>
7285    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7286                                                    &Base, 1, ResultTy, OpLoc));
7287
7288  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7289                          Method))
7290          return ExprError();
7291  return move(TheCall);
7292}
7293
7294/// FixOverloadedFunctionReference - E is an expression that refers to
7295/// a C++ overloaded function (possibly with some parentheses and
7296/// perhaps a '&' around it). We have resolved the overloaded function
7297/// to the function declaration Fn, so patch up the expression E to
7298/// refer (possibly indirectly) to Fn. Returns the new expr.
7299Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
7300                                           FunctionDecl *Fn) {
7301  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7302    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7303                                                   Found, Fn);
7304    if (SubExpr == PE->getSubExpr())
7305      return PE->Retain();
7306
7307    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7308  }
7309
7310  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
7311    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7312                                                   Found, Fn);
7313    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
7314                               SubExpr->getType()) &&
7315           "Implicit cast type cannot be determined from overload");
7316    if (SubExpr == ICE->getSubExpr())
7317      return ICE->Retain();
7318
7319    return new (Context) ImplicitCastExpr(ICE->getType(),
7320                                          ICE->getCastKind(),
7321                                          SubExpr, CXXBaseSpecifierArray(),
7322                                          ICE->isLvalueCast());
7323  }
7324
7325  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
7326    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
7327           "Can only take the address of an overloaded function");
7328    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7329      if (Method->isStatic()) {
7330        // Do nothing: static member functions aren't any different
7331        // from non-member functions.
7332      } else {
7333        // Fix the sub expression, which really has to be an
7334        // UnresolvedLookupExpr holding an overloaded member function
7335        // or template.
7336        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7337                                                       Found, Fn);
7338        if (SubExpr == UnOp->getSubExpr())
7339          return UnOp->Retain();
7340
7341        assert(isa<DeclRefExpr>(SubExpr)
7342               && "fixed to something other than a decl ref");
7343        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7344               && "fixed to a member ref with no nested name qualifier");
7345
7346        // We have taken the address of a pointer to member
7347        // function. Perform the computation here so that we get the
7348        // appropriate pointer to member type.
7349        QualType ClassType
7350          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7351        QualType MemPtrType
7352          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7353
7354        return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7355                                           MemPtrType, UnOp->getOperatorLoc());
7356      }
7357    }
7358    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7359                                                   Found, Fn);
7360    if (SubExpr == UnOp->getSubExpr())
7361      return UnOp->Retain();
7362
7363    return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7364                                     Context.getPointerType(SubExpr->getType()),
7365                                       UnOp->getOperatorLoc());
7366  }
7367
7368  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
7369    // FIXME: avoid copy.
7370    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7371    if (ULE->hasExplicitTemplateArgs()) {
7372      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7373      TemplateArgs = &TemplateArgsBuffer;
7374    }
7375
7376    return DeclRefExpr::Create(Context,
7377                               ULE->getQualifier(),
7378                               ULE->getQualifierRange(),
7379                               Fn,
7380                               ULE->getNameLoc(),
7381                               Fn->getType(),
7382                               TemplateArgs);
7383  }
7384
7385  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
7386    // FIXME: avoid copy.
7387    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7388    if (MemExpr->hasExplicitTemplateArgs()) {
7389      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7390      TemplateArgs = &TemplateArgsBuffer;
7391    }
7392
7393    Expr *Base;
7394
7395    // If we're filling in
7396    if (MemExpr->isImplicitAccess()) {
7397      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7398        return DeclRefExpr::Create(Context,
7399                                   MemExpr->getQualifier(),
7400                                   MemExpr->getQualifierRange(),
7401                                   Fn,
7402                                   MemExpr->getMemberLoc(),
7403                                   Fn->getType(),
7404                                   TemplateArgs);
7405      } else {
7406        SourceLocation Loc = MemExpr->getMemberLoc();
7407        if (MemExpr->getQualifier())
7408          Loc = MemExpr->getQualifierRange().getBegin();
7409        Base = new (Context) CXXThisExpr(Loc,
7410                                         MemExpr->getBaseType(),
7411                                         /*isImplicit=*/true);
7412      }
7413    } else
7414      Base = MemExpr->getBase()->Retain();
7415
7416    return MemberExpr::Create(Context, Base,
7417                              MemExpr->isArrow(),
7418                              MemExpr->getQualifier(),
7419                              MemExpr->getQualifierRange(),
7420                              Fn,
7421                              Found,
7422                              MemExpr->getMemberLoc(),
7423                              TemplateArgs,
7424                              Fn->getType());
7425  }
7426
7427  assert(false && "Invalid reference to overloaded function");
7428  return E->Retain();
7429}
7430
7431Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
7432                                                          DeclAccessPair Found,
7433                                                            FunctionDecl *Fn) {
7434  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
7435}
7436
7437} // end namespace clang
7438