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