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