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