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