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