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