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