SemaOverload.cpp revision b8b0313e84700b5c6d597b3be4de41c97b7550f1
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Sema/SemaInternal.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Template.h"
18#include "clang/Sema/TemplateDeduction.h"
19#include "clang/Basic/Diagnostic.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/AST/ASTContext.h"
22#include "clang/AST/CXXInheritance.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/TypeOrdering.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "llvm/ADT/DenseSet.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/STLExtras.h"
32#include <algorithm>
33
34namespace clang {
35using namespace sema;
36
37/// A convenience routine for creating a decayed reference to a
38/// function.
39static ExprResult
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41                      SourceLocation Loc = SourceLocation()) {
42  ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
43  E = S.DefaultFunctionArrayConversion(E.take());
44  if (E.isInvalid())
45    return ExprError();
46  return move(E);
47}
48
49static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
50                                 bool InOverloadResolution,
51                                 StandardConversionSequence &SCS,
52                                 bool CStyle,
53                                 bool AllowObjCWritebackConversion);
54
55static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
56                                                 QualType &ToType,
57                                                 bool InOverloadResolution,
58                                                 StandardConversionSequence &SCS,
59                                                 bool CStyle);
60static OverloadingResult
61IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
62                        UserDefinedConversionSequence& User,
63                        OverloadCandidateSet& Conversions,
64                        bool AllowExplicit);
65
66
67static ImplicitConversionSequence::CompareKind
68CompareStandardConversionSequences(Sema &S,
69                                   const StandardConversionSequence& SCS1,
70                                   const StandardConversionSequence& SCS2);
71
72static ImplicitConversionSequence::CompareKind
73CompareQualificationConversions(Sema &S,
74                                const StandardConversionSequence& SCS1,
75                                const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareDerivedToBaseConversions(Sema &S,
79                                const StandardConversionSequence& SCS1,
80                                const StandardConversionSequence& SCS2);
81
82
83
84/// GetConversionCategory - Retrieve the implicit conversion
85/// category corresponding to the given implicit conversion kind.
86ImplicitConversionCategory
87GetConversionCategory(ImplicitConversionKind Kind) {
88  static const ImplicitConversionCategory
89    Category[(int)ICK_Num_Conversion_Kinds] = {
90    ICC_Identity,
91    ICC_Lvalue_Transformation,
92    ICC_Lvalue_Transformation,
93    ICC_Lvalue_Transformation,
94    ICC_Identity,
95    ICC_Qualification_Adjustment,
96    ICC_Promotion,
97    ICC_Promotion,
98    ICC_Promotion,
99    ICC_Conversion,
100    ICC_Conversion,
101    ICC_Conversion,
102    ICC_Conversion,
103    ICC_Conversion,
104    ICC_Conversion,
105    ICC_Conversion,
106    ICC_Conversion,
107    ICC_Conversion,
108    ICC_Conversion,
109    ICC_Conversion,
110    ICC_Conversion,
111    ICC_Conversion
112  };
113  return Category[(int)Kind];
114}
115
116/// GetConversionRank - Retrieve the implicit conversion rank
117/// corresponding to the given implicit conversion kind.
118ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
119  static const ImplicitConversionRank
120    Rank[(int)ICK_Num_Conversion_Kinds] = {
121    ICR_Exact_Match,
122    ICR_Exact_Match,
123    ICR_Exact_Match,
124    ICR_Exact_Match,
125    ICR_Exact_Match,
126    ICR_Exact_Match,
127    ICR_Promotion,
128    ICR_Promotion,
129    ICR_Promotion,
130    ICR_Conversion,
131    ICR_Conversion,
132    ICR_Conversion,
133    ICR_Conversion,
134    ICR_Conversion,
135    ICR_Conversion,
136    ICR_Conversion,
137    ICR_Conversion,
138    ICR_Conversion,
139    ICR_Conversion,
140    ICR_Conversion,
141    ICR_Complex_Real_Conversion,
142    ICR_Conversion,
143    ICR_Conversion,
144    ICR_Writeback_Conversion
145  };
146  return Rank[(int)Kind];
147}
148
149/// GetImplicitConversionName - Return the name of this kind of
150/// implicit conversion.
151const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
152  static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
153    "No conversion",
154    "Lvalue-to-rvalue",
155    "Array-to-pointer",
156    "Function-to-pointer",
157    "Noreturn adjustment",
158    "Qualification",
159    "Integral promotion",
160    "Floating point promotion",
161    "Complex promotion",
162    "Integral conversion",
163    "Floating conversion",
164    "Complex conversion",
165    "Floating-integral conversion",
166    "Pointer conversion",
167    "Pointer-to-member conversion",
168    "Boolean conversion",
169    "Compatible-types conversion",
170    "Derived-to-base conversion",
171    "Vector conversion",
172    "Vector splat",
173    "Complex-real conversion",
174    "Block Pointer conversion",
175    "Transparent Union Conversion"
176    "Writeback conversion"
177  };
178  return Name[Kind];
179}
180
181/// StandardConversionSequence - Set the standard conversion
182/// sequence to the identity conversion.
183void StandardConversionSequence::setAsIdentityConversion() {
184  First = ICK_Identity;
185  Second = ICK_Identity;
186  Third = ICK_Identity;
187  DeprecatedStringLiteralToCharPtr = false;
188  QualificationIncludesObjCLifetime = false;
189  ReferenceBinding = false;
190  DirectBinding = false;
191  IsLvalueReference = true;
192  BindsToFunctionLvalue = false;
193  BindsToRvalue = false;
194  BindsImplicitObjectArgumentWithoutRefQualifier = false;
195  ObjCLifetimeConversionBinding = false;
196  CopyConstructor = 0;
197}
198
199/// getRank - Retrieve the rank of this standard conversion sequence
200/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
201/// implicit conversions.
202ImplicitConversionRank StandardConversionSequence::getRank() const {
203  ImplicitConversionRank Rank = ICR_Exact_Match;
204  if  (GetConversionRank(First) > Rank)
205    Rank = GetConversionRank(First);
206  if  (GetConversionRank(Second) > Rank)
207    Rank = GetConversionRank(Second);
208  if  (GetConversionRank(Third) > Rank)
209    Rank = GetConversionRank(Third);
210  return Rank;
211}
212
213/// isPointerConversionToBool - Determines whether this conversion is
214/// a conversion of a pointer or pointer-to-member to bool. This is
215/// used as part of the ranking of standard conversion sequences
216/// (C++ 13.3.3.2p4).
217bool StandardConversionSequence::isPointerConversionToBool() const {
218  // Note that FromType has not necessarily been transformed by the
219  // array-to-pointer or function-to-pointer implicit conversions, so
220  // check for their presence as well as checking whether FromType is
221  // a pointer.
222  if (getToType(1)->isBooleanType() &&
223      (getFromType()->isPointerType() ||
224       getFromType()->isObjCObjectPointerType() ||
225       getFromType()->isBlockPointerType() ||
226       getFromType()->isNullPtrType() ||
227       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
228    return true;
229
230  return false;
231}
232
233/// isPointerConversionToVoidPointer - Determines whether this
234/// conversion is a conversion of a pointer to a void pointer. This is
235/// used as part of the ranking of standard conversion sequences (C++
236/// 13.3.3.2p4).
237bool
238StandardConversionSequence::
239isPointerConversionToVoidPointer(ASTContext& Context) const {
240  QualType FromType = getFromType();
241  QualType ToType = getToType(1);
242
243  // Note that FromType has not necessarily been transformed by the
244  // array-to-pointer implicit conversion, so check for its presence
245  // and redo the conversion to get a pointer.
246  if (First == ICK_Array_To_Pointer)
247    FromType = Context.getArrayDecayedType(FromType);
248
249  if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
250    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
251      return ToPtrType->getPointeeType()->isVoidType();
252
253  return false;
254}
255
256/// DebugPrint - Print this standard conversion sequence to standard
257/// error. Useful for debugging overloading issues.
258void StandardConversionSequence::DebugPrint() const {
259  llvm::raw_ostream &OS = llvm::errs();
260  bool PrintedSomething = false;
261  if (First != ICK_Identity) {
262    OS << GetImplicitConversionName(First);
263    PrintedSomething = true;
264  }
265
266  if (Second != ICK_Identity) {
267    if (PrintedSomething) {
268      OS << " -> ";
269    }
270    OS << GetImplicitConversionName(Second);
271
272    if (CopyConstructor) {
273      OS << " (by copy constructor)";
274    } else if (DirectBinding) {
275      OS << " (direct reference binding)";
276    } else if (ReferenceBinding) {
277      OS << " (reference binding)";
278    }
279    PrintedSomething = true;
280  }
281
282  if (Third != ICK_Identity) {
283    if (PrintedSomething) {
284      OS << " -> ";
285    }
286    OS << GetImplicitConversionName(Third);
287    PrintedSomething = true;
288  }
289
290  if (!PrintedSomething) {
291    OS << "No conversions required";
292  }
293}
294
295/// DebugPrint - Print this user-defined conversion sequence to standard
296/// error. Useful for debugging overloading issues.
297void UserDefinedConversionSequence::DebugPrint() const {
298  llvm::raw_ostream &OS = llvm::errs();
299  if (Before.First || Before.Second || Before.Third) {
300    Before.DebugPrint();
301    OS << " -> ";
302  }
303  OS << '\'' << ConversionFunction << '\'';
304  if (After.First || After.Second || After.Third) {
305    OS << " -> ";
306    After.DebugPrint();
307  }
308}
309
310/// DebugPrint - Print this implicit conversion sequence to standard
311/// error. Useful for debugging overloading issues.
312void ImplicitConversionSequence::DebugPrint() const {
313  llvm::raw_ostream &OS = llvm::errs();
314  switch (ConversionKind) {
315  case StandardConversion:
316    OS << "Standard conversion: ";
317    Standard.DebugPrint();
318    break;
319  case UserDefinedConversion:
320    OS << "User-defined conversion: ";
321    UserDefined.DebugPrint();
322    break;
323  case EllipsisConversion:
324    OS << "Ellipsis conversion";
325    break;
326  case AmbiguousConversion:
327    OS << "Ambiguous conversion";
328    break;
329  case BadConversion:
330    OS << "Bad conversion";
331    break;
332  }
333
334  OS << "\n";
335}
336
337void AmbiguousConversionSequence::construct() {
338  new (&conversions()) ConversionSet();
339}
340
341void AmbiguousConversionSequence::destruct() {
342  conversions().~ConversionSet();
343}
344
345void
346AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
347  FromTypePtr = O.FromTypePtr;
348  ToTypePtr = O.ToTypePtr;
349  new (&conversions()) ConversionSet(O.conversions());
350}
351
352namespace {
353  // Structure used by OverloadCandidate::DeductionFailureInfo to store
354  // template parameter and template argument information.
355  struct DFIParamWithArguments {
356    TemplateParameter Param;
357    TemplateArgument FirstArg;
358    TemplateArgument SecondArg;
359  };
360}
361
362/// \brief Convert from Sema's representation of template deduction information
363/// to the form used in overload-candidate information.
364OverloadCandidate::DeductionFailureInfo
365static MakeDeductionFailureInfo(ASTContext &Context,
366                                Sema::TemplateDeductionResult TDK,
367                                TemplateDeductionInfo &Info) {
368  OverloadCandidate::DeductionFailureInfo Result;
369  Result.Result = static_cast<unsigned>(TDK);
370  Result.Data = 0;
371  switch (TDK) {
372  case Sema::TDK_Success:
373  case Sema::TDK_InstantiationDepth:
374  case Sema::TDK_TooManyArguments:
375  case Sema::TDK_TooFewArguments:
376    break;
377
378  case Sema::TDK_Incomplete:
379  case Sema::TDK_InvalidExplicitArguments:
380    Result.Data = Info.Param.getOpaqueValue();
381    break;
382
383  case Sema::TDK_Inconsistent:
384  case Sema::TDK_Underqualified: {
385    // FIXME: Should allocate from normal heap so that we can free this later.
386    DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
387    Saved->Param = Info.Param;
388    Saved->FirstArg = Info.FirstArg;
389    Saved->SecondArg = Info.SecondArg;
390    Result.Data = Saved;
391    break;
392  }
393
394  case Sema::TDK_SubstitutionFailure:
395    Result.Data = Info.take();
396    break;
397
398  case Sema::TDK_NonDeducedMismatch:
399  case Sema::TDK_FailedOverloadResolution:
400    break;
401  }
402
403  return Result;
404}
405
406void OverloadCandidate::DeductionFailureInfo::Destroy() {
407  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
408  case Sema::TDK_Success:
409  case Sema::TDK_InstantiationDepth:
410  case Sema::TDK_Incomplete:
411  case Sema::TDK_TooManyArguments:
412  case Sema::TDK_TooFewArguments:
413  case Sema::TDK_InvalidExplicitArguments:
414    break;
415
416  case Sema::TDK_Inconsistent:
417  case Sema::TDK_Underqualified:
418    // FIXME: Destroy the data?
419    Data = 0;
420    break;
421
422  case Sema::TDK_SubstitutionFailure:
423    // FIXME: Destroy the template arugment list?
424    Data = 0;
425    break;
426
427  // Unhandled
428  case Sema::TDK_NonDeducedMismatch:
429  case Sema::TDK_FailedOverloadResolution:
430    break;
431  }
432}
433
434TemplateParameter
435OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
436  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
437  case Sema::TDK_Success:
438  case Sema::TDK_InstantiationDepth:
439  case Sema::TDK_TooManyArguments:
440  case Sema::TDK_TooFewArguments:
441  case Sema::TDK_SubstitutionFailure:
442    return TemplateParameter();
443
444  case Sema::TDK_Incomplete:
445  case Sema::TDK_InvalidExplicitArguments:
446    return TemplateParameter::getFromOpaqueValue(Data);
447
448  case Sema::TDK_Inconsistent:
449  case Sema::TDK_Underqualified:
450    return static_cast<DFIParamWithArguments*>(Data)->Param;
451
452  // Unhandled
453  case Sema::TDK_NonDeducedMismatch:
454  case Sema::TDK_FailedOverloadResolution:
455    break;
456  }
457
458  return TemplateParameter();
459}
460
461TemplateArgumentList *
462OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
463  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
464    case Sema::TDK_Success:
465    case Sema::TDK_InstantiationDepth:
466    case Sema::TDK_TooManyArguments:
467    case Sema::TDK_TooFewArguments:
468    case Sema::TDK_Incomplete:
469    case Sema::TDK_InvalidExplicitArguments:
470    case Sema::TDK_Inconsistent:
471    case Sema::TDK_Underqualified:
472      return 0;
473
474    case Sema::TDK_SubstitutionFailure:
475      return static_cast<TemplateArgumentList*>(Data);
476
477    // Unhandled
478    case Sema::TDK_NonDeducedMismatch:
479    case Sema::TDK_FailedOverloadResolution:
480      break;
481  }
482
483  return 0;
484}
485
486const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
487  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
488  case Sema::TDK_Success:
489  case Sema::TDK_InstantiationDepth:
490  case Sema::TDK_Incomplete:
491  case Sema::TDK_TooManyArguments:
492  case Sema::TDK_TooFewArguments:
493  case Sema::TDK_InvalidExplicitArguments:
494  case Sema::TDK_SubstitutionFailure:
495    return 0;
496
497  case Sema::TDK_Inconsistent:
498  case Sema::TDK_Underqualified:
499    return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
500
501  // Unhandled
502  case Sema::TDK_NonDeducedMismatch:
503  case Sema::TDK_FailedOverloadResolution:
504    break;
505  }
506
507  return 0;
508}
509
510const TemplateArgument *
511OverloadCandidate::DeductionFailureInfo::getSecondArg() {
512  switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
513  case Sema::TDK_Success:
514  case Sema::TDK_InstantiationDepth:
515  case Sema::TDK_Incomplete:
516  case Sema::TDK_TooManyArguments:
517  case Sema::TDK_TooFewArguments:
518  case Sema::TDK_InvalidExplicitArguments:
519  case Sema::TDK_SubstitutionFailure:
520    return 0;
521
522  case Sema::TDK_Inconsistent:
523  case Sema::TDK_Underqualified:
524    return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
525
526  // Unhandled
527  case Sema::TDK_NonDeducedMismatch:
528  case Sema::TDK_FailedOverloadResolution:
529    break;
530  }
531
532  return 0;
533}
534
535void OverloadCandidateSet::clear() {
536  inherited::clear();
537  Functions.clear();
538}
539
540// IsOverload - Determine whether the given New declaration is an
541// overload of the declarations in Old. This routine returns false if
542// New and Old cannot be overloaded, e.g., if New has the same
543// signature as some function in Old (C++ 1.3.10) or if the Old
544// declarations aren't functions (or function templates) at all. When
545// it does return false, MatchedDecl will point to the decl that New
546// cannot be overloaded with.  This decl may be a UsingShadowDecl on
547// top of the underlying declaration.
548//
549// Example: Given the following input:
550//
551//   void f(int, float); // #1
552//   void f(int, int); // #2
553//   int f(int, int); // #3
554//
555// When we process #1, there is no previous declaration of "f",
556// so IsOverload will not be used.
557//
558// When we process #2, Old contains only the FunctionDecl for #1.  By
559// comparing the parameter types, we see that #1 and #2 are overloaded
560// (since they have different signatures), so this routine returns
561// false; MatchedDecl is unchanged.
562//
563// When we process #3, Old is an overload set containing #1 and #2. We
564// compare the signatures of #3 to #1 (they're overloaded, so we do
565// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
566// identical (return types of functions are not part of the
567// signature), IsOverload returns false and MatchedDecl will be set to
568// point to the FunctionDecl for #2.
569//
570// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
571// into a class by a using declaration.  The rules for whether to hide
572// shadow declarations ignore some properties which otherwise figure
573// into a function template's signature.
574Sema::OverloadKind
575Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
576                    NamedDecl *&Match, bool NewIsUsingDecl) {
577  for (LookupResult::iterator I = Old.begin(), E = Old.end();
578         I != E; ++I) {
579    NamedDecl *OldD = *I;
580
581    bool OldIsUsingDecl = false;
582    if (isa<UsingShadowDecl>(OldD)) {
583      OldIsUsingDecl = true;
584
585      // We can always introduce two using declarations into the same
586      // context, even if they have identical signatures.
587      if (NewIsUsingDecl) continue;
588
589      OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
590    }
591
592    // If either declaration was introduced by a using declaration,
593    // we'll need to use slightly different rules for matching.
594    // Essentially, these rules are the normal rules, except that
595    // function templates hide function templates with different
596    // return types or template parameter lists.
597    bool UseMemberUsingDeclRules =
598      (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
599
600    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
601      if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
602        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
603          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
604          continue;
605        }
606
607        Match = *I;
608        return Ovl_Match;
609      }
610    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
611      if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
612        if (UseMemberUsingDeclRules && OldIsUsingDecl) {
613          HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
614          continue;
615        }
616
617        Match = *I;
618        return Ovl_Match;
619      }
620    } else if (isa<UsingDecl>(OldD)) {
621      // We can overload with these, which can show up when doing
622      // redeclaration checks for UsingDecls.
623      assert(Old.getLookupKind() == LookupUsingDeclName);
624    } else if (isa<TagDecl>(OldD)) {
625      // We can always overload with tags by hiding them.
626    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
627      // Optimistically assume that an unresolved using decl will
628      // overload; if it doesn't, we'll have to diagnose during
629      // template instantiation.
630    } else {
631      // (C++ 13p1):
632      //   Only function declarations can be overloaded; object and type
633      //   declarations cannot be overloaded.
634      Match = *I;
635      return Ovl_NonFunction;
636    }
637  }
638
639  return Ovl_Overload;
640}
641
642bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
643                      bool UseUsingDeclRules) {
644  // If both of the functions are extern "C", then they are not
645  // overloads.
646  if (Old->isExternC() && New->isExternC())
647    return false;
648
649  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
650  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
651
652  // C++ [temp.fct]p2:
653  //   A function template can be overloaded with other function templates
654  //   and with normal (non-template) functions.
655  if ((OldTemplate == 0) != (NewTemplate == 0))
656    return true;
657
658  // Is the function New an overload of the function Old?
659  QualType OldQType = Context.getCanonicalType(Old->getType());
660  QualType NewQType = Context.getCanonicalType(New->getType());
661
662  // Compare the signatures (C++ 1.3.10) of the two functions to
663  // determine whether they are overloads. If we find any mismatch
664  // in the signature, they are overloads.
665
666  // If either of these functions is a K&R-style function (no
667  // prototype), then we consider them to have matching signatures.
668  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
669      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
670    return false;
671
672  const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
673  const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
674
675  // The signature of a function includes the types of its
676  // parameters (C++ 1.3.10), which includes the presence or absence
677  // of the ellipsis; see C++ DR 357).
678  if (OldQType != NewQType &&
679      (OldType->getNumArgs() != NewType->getNumArgs() ||
680       OldType->isVariadic() != NewType->isVariadic() ||
681       !FunctionArgTypesAreEqual(OldType, NewType)))
682    return true;
683
684  // C++ [temp.over.link]p4:
685  //   The signature of a function template consists of its function
686  //   signature, its return type and its template parameter list. The names
687  //   of the template parameters are significant only for establishing the
688  //   relationship between the template parameters and the rest of the
689  //   signature.
690  //
691  // We check the return type and template parameter lists for function
692  // templates first; the remaining checks follow.
693  //
694  // However, we don't consider either of these when deciding whether
695  // a member introduced by a shadow declaration is hidden.
696  if (!UseUsingDeclRules && NewTemplate &&
697      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
698                                       OldTemplate->getTemplateParameters(),
699                                       false, TPL_TemplateMatch) ||
700       OldType->getResultType() != NewType->getResultType()))
701    return true;
702
703  // If the function is a class member, its signature includes the
704  // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
705  //
706  // As part of this, also check whether one of the member functions
707  // is static, in which case they are not overloads (C++
708  // 13.1p2). While not part of the definition of the signature,
709  // this check is important to determine whether these functions
710  // can be overloaded.
711  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
712  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
713  if (OldMethod && NewMethod &&
714      !OldMethod->isStatic() && !NewMethod->isStatic() &&
715      (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
716       OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
717    if (!UseUsingDeclRules &&
718        OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
719        (OldMethod->getRefQualifier() == RQ_None ||
720         NewMethod->getRefQualifier() == RQ_None)) {
721      // C++0x [over.load]p2:
722      //   - Member function declarations with the same name and the same
723      //     parameter-type-list as well as member function template
724      //     declarations with the same name, the same parameter-type-list, and
725      //     the same template parameter lists cannot be overloaded if any of
726      //     them, but not all, have a ref-qualifier (8.3.5).
727      Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
728        << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
729      Diag(OldMethod->getLocation(), diag::note_previous_declaration);
730    }
731
732    return true;
733  }
734
735  // The signatures match; this is not an overload.
736  return false;
737}
738
739/// \brief Checks availability of the function depending on the current
740/// function context. Inside an unavailable function, unavailability is ignored.
741///
742/// \returns true if \arg FD is unavailable and current context is inside
743/// an available function, false otherwise.
744bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
745  return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
746}
747
748/// TryImplicitConversion - Attempt to perform an implicit conversion
749/// from the given expression (Expr) to the given type (ToType). This
750/// function returns an implicit conversion sequence that can be used
751/// to perform the initialization. Given
752///
753///   void f(float f);
754///   void g(int i) { f(i); }
755///
756/// this routine would produce an implicit conversion sequence to
757/// describe the initialization of f from i, which will be a standard
758/// conversion sequence containing an lvalue-to-rvalue conversion (C++
759/// 4.1) followed by a floating-integral conversion (C++ 4.9).
760//
761/// Note that this routine only determines how the conversion can be
762/// performed; it does not actually perform the conversion. As such,
763/// it will not produce any diagnostics if no conversion is available,
764/// but will instead return an implicit conversion sequence of kind
765/// "BadConversion".
766///
767/// If @p SuppressUserConversions, then user-defined conversions are
768/// not permitted.
769/// If @p AllowExplicit, then explicit user-defined conversions are
770/// permitted.
771///
772/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
773/// writeback conversion, which allows __autoreleasing id* parameters to
774/// be initialized with __strong id* or __weak id* arguments.
775static ImplicitConversionSequence
776TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
777                      bool SuppressUserConversions,
778                      bool AllowExplicit,
779                      bool InOverloadResolution,
780                      bool CStyle,
781                      bool AllowObjCWritebackConversion) {
782  ImplicitConversionSequence ICS;
783  if (IsStandardConversion(S, From, ToType, InOverloadResolution,
784                           ICS.Standard, CStyle, AllowObjCWritebackConversion)){
785    ICS.setStandard();
786    return ICS;
787  }
788
789  if (!S.getLangOptions().CPlusPlus) {
790    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
791    return ICS;
792  }
793
794  // C++ [over.ics.user]p4:
795  //   A conversion of an expression of class type to the same class
796  //   type is given Exact Match rank, and a conversion of an
797  //   expression of class type to a base class of that type is
798  //   given Conversion rank, in spite of the fact that a copy/move
799  //   constructor (i.e., a user-defined conversion function) is
800  //   called for those cases.
801  QualType FromType = From->getType();
802  if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
803      (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
804       S.IsDerivedFrom(FromType, ToType))) {
805    ICS.setStandard();
806    ICS.Standard.setAsIdentityConversion();
807    ICS.Standard.setFromType(FromType);
808    ICS.Standard.setAllToTypes(ToType);
809
810    // We don't actually check at this point whether there is a valid
811    // copy/move constructor, since overloading just assumes that it
812    // exists. When we actually perform initialization, we'll find the
813    // appropriate constructor to copy the returned object, if needed.
814    ICS.Standard.CopyConstructor = 0;
815
816    // Determine whether this is considered a derived-to-base conversion.
817    if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
818      ICS.Standard.Second = ICK_Derived_To_Base;
819
820    return ICS;
821  }
822
823  if (SuppressUserConversions) {
824    // We're not in the case above, so there is no conversion that
825    // we can perform.
826    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
827    return ICS;
828  }
829
830  // Attempt user-defined conversion.
831  OverloadCandidateSet Conversions(From->getExprLoc());
832  OverloadingResult UserDefResult
833    = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
834                              AllowExplicit);
835
836  if (UserDefResult == OR_Success) {
837    ICS.setUserDefined();
838    // C++ [over.ics.user]p4:
839    //   A conversion of an expression of class type to the same class
840    //   type is given Exact Match rank, and a conversion of an
841    //   expression of class type to a base class of that type is
842    //   given Conversion rank, in spite of the fact that a copy
843    //   constructor (i.e., a user-defined conversion function) is
844    //   called for those cases.
845    if (CXXConstructorDecl *Constructor
846          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
847      QualType FromCanon
848        = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
849      QualType ToCanon
850        = S.Context.getCanonicalType(ToType).getUnqualifiedType();
851      if (Constructor->isCopyConstructor() &&
852          (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
853        // Turn this into a "standard" conversion sequence, so that it
854        // gets ranked with standard conversion sequences.
855        ICS.setStandard();
856        ICS.Standard.setAsIdentityConversion();
857        ICS.Standard.setFromType(From->getType());
858        ICS.Standard.setAllToTypes(ToType);
859        ICS.Standard.CopyConstructor = Constructor;
860        if (ToCanon != FromCanon)
861          ICS.Standard.Second = ICK_Derived_To_Base;
862      }
863    }
864
865    // C++ [over.best.ics]p4:
866    //   However, when considering the argument of a user-defined
867    //   conversion function that is a candidate by 13.3.1.3 when
868    //   invoked for the copying of the temporary in the second step
869    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
870    //   13.3.1.6 in all cases, only standard conversion sequences and
871    //   ellipsis conversion sequences are allowed.
872    if (SuppressUserConversions && ICS.isUserDefined()) {
873      ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
874    }
875  } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
876    ICS.setAmbiguous();
877    ICS.Ambiguous.setFromType(From->getType());
878    ICS.Ambiguous.setToType(ToType);
879    for (OverloadCandidateSet::iterator Cand = Conversions.begin();
880         Cand != Conversions.end(); ++Cand)
881      if (Cand->Viable)
882        ICS.Ambiguous.addConversion(Cand->Function);
883  } else {
884    ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
885  }
886
887  return ICS;
888}
889
890ImplicitConversionSequence
891Sema::TryImplicitConversion(Expr *From, QualType ToType,
892                            bool SuppressUserConversions,
893                            bool AllowExplicit,
894                            bool InOverloadResolution,
895                            bool CStyle,
896                            bool AllowObjCWritebackConversion) {
897  return clang::TryImplicitConversion(*this, From, ToType,
898                                      SuppressUserConversions, AllowExplicit,
899                                      InOverloadResolution, CStyle,
900                                      AllowObjCWritebackConversion);
901}
902
903/// PerformImplicitConversion - Perform an implicit conversion of the
904/// expression From to the type ToType. Returns the
905/// converted expression. Flavor is the kind of conversion we're
906/// performing, used in the error message. If @p AllowExplicit,
907/// explicit user-defined conversions are permitted.
908ExprResult
909Sema::PerformImplicitConversion(Expr *From, QualType ToType,
910                                AssignmentAction Action, bool AllowExplicit) {
911  ImplicitConversionSequence ICS;
912  return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
913}
914
915ExprResult
916Sema::PerformImplicitConversion(Expr *From, QualType ToType,
917                                AssignmentAction Action, bool AllowExplicit,
918                                ImplicitConversionSequence& ICS) {
919  // Objective-C ARC: Determine whether we will allow the writeback conversion.
920  bool AllowObjCWritebackConversion
921    = getLangOptions().ObjCAutoRefCount &&
922      (Action == AA_Passing || Action == AA_Sending);
923
924
925  ICS = clang::TryImplicitConversion(*this, From, ToType,
926                                     /*SuppressUserConversions=*/false,
927                                     AllowExplicit,
928                                     /*InOverloadResolution=*/false,
929                                     /*CStyle=*/false,
930                                     AllowObjCWritebackConversion);
931  return PerformImplicitConversion(From, ToType, ICS, Action);
932}
933
934/// \brief Determine whether the conversion from FromType to ToType is a valid
935/// conversion that strips "noreturn" off the nested function type.
936bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
937                                QualType &ResultTy) {
938  if (Context.hasSameUnqualifiedType(FromType, ToType))
939    return false;
940
941  // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
942  // where F adds one of the following at most once:
943  //   - a pointer
944  //   - a member pointer
945  //   - a block pointer
946  CanQualType CanTo = Context.getCanonicalType(ToType);
947  CanQualType CanFrom = Context.getCanonicalType(FromType);
948  Type::TypeClass TyClass = CanTo->getTypeClass();
949  if (TyClass != CanFrom->getTypeClass()) return false;
950  if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
951    if (TyClass == Type::Pointer) {
952      CanTo = CanTo.getAs<PointerType>()->getPointeeType();
953      CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
954    } else if (TyClass == Type::BlockPointer) {
955      CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
956      CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
957    } else if (TyClass == Type::MemberPointer) {
958      CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
959      CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
960    } else {
961      return false;
962    }
963
964    TyClass = CanTo->getTypeClass();
965    if (TyClass != CanFrom->getTypeClass()) return false;
966    if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
967      return false;
968  }
969
970  const FunctionType *FromFn = cast<FunctionType>(CanFrom);
971  FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
972  if (!EInfo.getNoReturn()) return false;
973
974  FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
975  assert(QualType(FromFn, 0).isCanonical());
976  if (QualType(FromFn, 0) != CanTo) return false;
977
978  ResultTy = ToType;
979  return true;
980}
981
982/// \brief Determine whether the conversion from FromType to ToType is a valid
983/// vector conversion.
984///
985/// \param ICK Will be set to the vector conversion kind, if this is a vector
986/// conversion.
987static bool IsVectorConversion(ASTContext &Context, QualType FromType,
988                               QualType ToType, ImplicitConversionKind &ICK) {
989  // We need at least one of these types to be a vector type to have a vector
990  // conversion.
991  if (!ToType->isVectorType() && !FromType->isVectorType())
992    return false;
993
994  // Identical types require no conversions.
995  if (Context.hasSameUnqualifiedType(FromType, ToType))
996    return false;
997
998  // There are no conversions between extended vector types, only identity.
999  if (ToType->isExtVectorType()) {
1000    // There are no conversions between extended vector types other than the
1001    // identity conversion.
1002    if (FromType->isExtVectorType())
1003      return false;
1004
1005    // Vector splat from any arithmetic type to a vector.
1006    if (FromType->isArithmeticType()) {
1007      ICK = ICK_Vector_Splat;
1008      return true;
1009    }
1010  }
1011
1012  // We can perform the conversion between vector types in the following cases:
1013  // 1)vector types are equivalent AltiVec and GCC vector types
1014  // 2)lax vector conversions are permitted and the vector types are of the
1015  //   same size
1016  if (ToType->isVectorType() && FromType->isVectorType()) {
1017    if (Context.areCompatibleVectorTypes(FromType, ToType) ||
1018        (Context.getLangOptions().LaxVectorConversions &&
1019         (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1020      ICK = ICK_Vector_Conversion;
1021      return true;
1022    }
1023  }
1024
1025  return false;
1026}
1027
1028/// IsStandardConversion - Determines whether there is a standard
1029/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1030/// expression From to the type ToType. Standard conversion sequences
1031/// only consider non-class types; for conversions that involve class
1032/// types, use TryImplicitConversion. If a conversion exists, SCS will
1033/// contain the standard conversion sequence required to perform this
1034/// conversion and this routine will return true. Otherwise, this
1035/// routine will return false and the value of SCS is unspecified.
1036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1037                                 bool InOverloadResolution,
1038                                 StandardConversionSequence &SCS,
1039                                 bool CStyle,
1040                                 bool AllowObjCWritebackConversion) {
1041  QualType FromType = From->getType();
1042
1043  // Standard conversions (C++ [conv])
1044  SCS.setAsIdentityConversion();
1045  SCS.DeprecatedStringLiteralToCharPtr = false;
1046  SCS.IncompatibleObjC = false;
1047  SCS.setFromType(FromType);
1048  SCS.CopyConstructor = 0;
1049
1050  // There are no standard conversions for class types in C++, so
1051  // abort early. When overloading in C, however, we do permit
1052  if (FromType->isRecordType() || ToType->isRecordType()) {
1053    if (S.getLangOptions().CPlusPlus)
1054      return false;
1055
1056    // When we're overloading in C, we allow, as standard conversions,
1057  }
1058
1059  // The first conversion can be an lvalue-to-rvalue conversion,
1060  // array-to-pointer conversion, or function-to-pointer conversion
1061  // (C++ 4p1).
1062
1063  if (FromType == S.Context.OverloadTy) {
1064    DeclAccessPair AccessPair;
1065    if (FunctionDecl *Fn
1066          = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1067                                                 AccessPair)) {
1068      // We were able to resolve the address of the overloaded function,
1069      // so we can convert to the type of that function.
1070      FromType = Fn->getType();
1071
1072      // we can sometimes resolve &foo<int> regardless of ToType, so check
1073      // if the type matches (identity) or we are converting to bool
1074      if (!S.Context.hasSameUnqualifiedType(
1075                      S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1076        QualType resultTy;
1077        // if the function type matches except for [[noreturn]], it's ok
1078        if (!S.IsNoReturnConversion(FromType,
1079              S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1080          // otherwise, only a boolean conversion is standard
1081          if (!ToType->isBooleanType())
1082            return false;
1083      }
1084
1085      // Check if the "from" expression is taking the address of an overloaded
1086      // function and recompute the FromType accordingly. Take advantage of the
1087      // fact that non-static member functions *must* have such an address-of
1088      // expression.
1089      CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1090      if (Method && !Method->isStatic()) {
1091        assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1092               "Non-unary operator on non-static member address");
1093        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1094               == UO_AddrOf &&
1095               "Non-address-of operator on non-static member address");
1096        const Type *ClassType
1097          = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1098        FromType = S.Context.getMemberPointerType(FromType, ClassType);
1099      } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1100        assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1101               UO_AddrOf &&
1102               "Non-address-of operator for overloaded function expression");
1103        FromType = S.Context.getPointerType(FromType);
1104      }
1105
1106      // Check that we've computed the proper type after overload resolution.
1107      assert(S.Context.hasSameType(
1108        FromType,
1109        S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1110    } else {
1111      return false;
1112    }
1113  }
1114  // Lvalue-to-rvalue conversion (C++ 4.1):
1115  //   An lvalue (3.10) of a non-function, non-array type T can be
1116  //   converted to an rvalue.
1117  bool argIsLValue = From->isLValue();
1118  if (argIsLValue &&
1119      !FromType->isFunctionType() && !FromType->isArrayType() &&
1120      S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1121    SCS.First = ICK_Lvalue_To_Rvalue;
1122
1123    // If T is a non-class type, the type of the rvalue is the
1124    // cv-unqualified version of T. Otherwise, the type of the rvalue
1125    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1126    // just strip the qualifiers because they don't matter.
1127    FromType = FromType.getUnqualifiedType();
1128  } else if (FromType->isArrayType()) {
1129    // Array-to-pointer conversion (C++ 4.2)
1130    SCS.First = ICK_Array_To_Pointer;
1131
1132    // An lvalue or rvalue of type "array of N T" or "array of unknown
1133    // bound of T" can be converted to an rvalue of type "pointer to
1134    // T" (C++ 4.2p1).
1135    FromType = S.Context.getArrayDecayedType(FromType);
1136
1137    if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1138      // This conversion is deprecated. (C++ D.4).
1139      SCS.DeprecatedStringLiteralToCharPtr = true;
1140
1141      // For the purpose of ranking in overload resolution
1142      // (13.3.3.1.1), this conversion is considered an
1143      // array-to-pointer conversion followed by a qualification
1144      // conversion (4.4). (C++ 4.2p2)
1145      SCS.Second = ICK_Identity;
1146      SCS.Third = ICK_Qualification;
1147      SCS.QualificationIncludesObjCLifetime = false;
1148      SCS.setAllToTypes(FromType);
1149      return true;
1150    }
1151  } else if (FromType->isFunctionType() && argIsLValue) {
1152    // Function-to-pointer conversion (C++ 4.3).
1153    SCS.First = ICK_Function_To_Pointer;
1154
1155    // An lvalue of function type T can be converted to an rvalue of
1156    // type "pointer to T." The result is a pointer to the
1157    // function. (C++ 4.3p1).
1158    FromType = S.Context.getPointerType(FromType);
1159  } else {
1160    // We don't require any conversions for the first step.
1161    SCS.First = ICK_Identity;
1162  }
1163  SCS.setToType(0, FromType);
1164
1165  // The second conversion can be an integral promotion, floating
1166  // point promotion, integral conversion, floating point conversion,
1167  // floating-integral conversion, pointer conversion,
1168  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1169  // For overloading in C, this can also be a "compatible-type"
1170  // conversion.
1171  bool IncompatibleObjC = false;
1172  ImplicitConversionKind SecondICK = ICK_Identity;
1173  if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1174    // The unqualified versions of the types are the same: there's no
1175    // conversion to do.
1176    SCS.Second = ICK_Identity;
1177  } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1178    // Integral promotion (C++ 4.5).
1179    SCS.Second = ICK_Integral_Promotion;
1180    FromType = ToType.getUnqualifiedType();
1181  } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1182    // Floating point promotion (C++ 4.6).
1183    SCS.Second = ICK_Floating_Promotion;
1184    FromType = ToType.getUnqualifiedType();
1185  } else if (S.IsComplexPromotion(FromType, ToType)) {
1186    // Complex promotion (Clang extension)
1187    SCS.Second = ICK_Complex_Promotion;
1188    FromType = ToType.getUnqualifiedType();
1189  } else if (ToType->isBooleanType() &&
1190             (FromType->isArithmeticType() ||
1191              FromType->isAnyPointerType() ||
1192              FromType->isBlockPointerType() ||
1193              FromType->isMemberPointerType() ||
1194              FromType->isNullPtrType())) {
1195    // Boolean conversions (C++ 4.12).
1196    SCS.Second = ICK_Boolean_Conversion;
1197    FromType = S.Context.BoolTy;
1198  } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1199             ToType->isIntegralType(S.Context)) {
1200    // Integral conversions (C++ 4.7).
1201    SCS.Second = ICK_Integral_Conversion;
1202    FromType = ToType.getUnqualifiedType();
1203  } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1204    // Complex conversions (C99 6.3.1.6)
1205    SCS.Second = ICK_Complex_Conversion;
1206    FromType = ToType.getUnqualifiedType();
1207  } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1208             (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1209    // Complex-real conversions (C99 6.3.1.7)
1210    SCS.Second = ICK_Complex_Real;
1211    FromType = ToType.getUnqualifiedType();
1212  } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1213    // Floating point conversions (C++ 4.8).
1214    SCS.Second = ICK_Floating_Conversion;
1215    FromType = ToType.getUnqualifiedType();
1216  } else if ((FromType->isRealFloatingType() &&
1217              ToType->isIntegralType(S.Context)) ||
1218             (FromType->isIntegralOrUnscopedEnumerationType() &&
1219              ToType->isRealFloatingType())) {
1220    // Floating-integral conversions (C++ 4.9).
1221    SCS.Second = ICK_Floating_Integral;
1222    FromType = ToType.getUnqualifiedType();
1223  } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1224    SCS.Second = ICK_Block_Pointer_Conversion;
1225  } else if (AllowObjCWritebackConversion &&
1226             S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1227    SCS.Second = ICK_Writeback_Conversion;
1228  } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1229                                   FromType, IncompatibleObjC)) {
1230    // Pointer conversions (C++ 4.10).
1231    SCS.Second = ICK_Pointer_Conversion;
1232    SCS.IncompatibleObjC = IncompatibleObjC;
1233    FromType = FromType.getUnqualifiedType();
1234  } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1235                                         InOverloadResolution, FromType)) {
1236    // Pointer to member conversions (4.11).
1237    SCS.Second = ICK_Pointer_Member;
1238  } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1239    SCS.Second = SecondICK;
1240    FromType = ToType.getUnqualifiedType();
1241  } else if (!S.getLangOptions().CPlusPlus &&
1242             S.Context.typesAreCompatible(ToType, FromType)) {
1243    // Compatible conversions (Clang extension for C function overloading)
1244    SCS.Second = ICK_Compatible_Conversion;
1245    FromType = ToType.getUnqualifiedType();
1246  } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1247    // Treat a conversion that strips "noreturn" as an identity conversion.
1248    SCS.Second = ICK_NoReturn_Adjustment;
1249  } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1250                                             InOverloadResolution,
1251                                             SCS, CStyle)) {
1252    SCS.Second = ICK_TransparentUnionConversion;
1253    FromType = ToType;
1254  } else {
1255    // No second conversion required.
1256    SCS.Second = ICK_Identity;
1257  }
1258  SCS.setToType(1, FromType);
1259
1260  QualType CanonFrom;
1261  QualType CanonTo;
1262  // The third conversion can be a qualification conversion (C++ 4p1).
1263  bool ObjCLifetimeConversion;
1264  if (S.IsQualificationConversion(FromType, ToType, CStyle,
1265                                  ObjCLifetimeConversion)) {
1266    SCS.Third = ICK_Qualification;
1267    SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1268    FromType = ToType;
1269    CanonFrom = S.Context.getCanonicalType(FromType);
1270    CanonTo = S.Context.getCanonicalType(ToType);
1271  } else {
1272    // No conversion required
1273    SCS.Third = ICK_Identity;
1274
1275    // C++ [over.best.ics]p6:
1276    //   [...] Any difference in top-level cv-qualification is
1277    //   subsumed by the initialization itself and does not constitute
1278    //   a conversion. [...]
1279    CanonFrom = S.Context.getCanonicalType(FromType);
1280    CanonTo = S.Context.getCanonicalType(ToType);
1281    if (CanonFrom.getLocalUnqualifiedType()
1282                                       == CanonTo.getLocalUnqualifiedType() &&
1283        (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1284         || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1285         || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
1286      FromType = ToType;
1287      CanonFrom = CanonTo;
1288    }
1289  }
1290  SCS.setToType(2, FromType);
1291
1292  // If we have not converted the argument type to the parameter type,
1293  // this is a bad conversion sequence.
1294  if (CanonFrom != CanonTo)
1295    return false;
1296
1297  return true;
1298}
1299
1300static bool
1301IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1302                                     QualType &ToType,
1303                                     bool InOverloadResolution,
1304                                     StandardConversionSequence &SCS,
1305                                     bool CStyle) {
1306
1307  const RecordType *UT = ToType->getAsUnionType();
1308  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1309    return false;
1310  // The field to initialize within the transparent union.
1311  RecordDecl *UD = UT->getDecl();
1312  // It's compatible if the expression matches any of the fields.
1313  for (RecordDecl::field_iterator it = UD->field_begin(),
1314       itend = UD->field_end();
1315       it != itend; ++it) {
1316    if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1317                             CStyle, /*ObjCWritebackConversion=*/false)) {
1318      ToType = it->getType();
1319      return true;
1320    }
1321  }
1322  return false;
1323}
1324
1325/// IsIntegralPromotion - Determines whether the conversion from the
1326/// expression From (whose potentially-adjusted type is FromType) to
1327/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1328/// sets PromotedType to the promoted type.
1329bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1330  const BuiltinType *To = ToType->getAs<BuiltinType>();
1331  // All integers are built-in.
1332  if (!To) {
1333    return false;
1334  }
1335
1336  // An rvalue of type char, signed char, unsigned char, short int, or
1337  // unsigned short int can be converted to an rvalue of type int if
1338  // int can represent all the values of the source type; otherwise,
1339  // the source rvalue can be converted to an rvalue of type unsigned
1340  // int (C++ 4.5p1).
1341  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1342      !FromType->isEnumeralType()) {
1343    if (// We can promote any signed, promotable integer type to an int
1344        (FromType->isSignedIntegerType() ||
1345         // We can promote any unsigned integer type whose size is
1346         // less than int to an int.
1347         (!FromType->isSignedIntegerType() &&
1348          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1349      return To->getKind() == BuiltinType::Int;
1350    }
1351
1352    return To->getKind() == BuiltinType::UInt;
1353  }
1354
1355  // C++0x [conv.prom]p3:
1356  //   A prvalue of an unscoped enumeration type whose underlying type is not
1357  //   fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1358  //   following types that can represent all the values of the enumeration
1359  //   (i.e., the values in the range bmin to bmax as described in 7.2): int,
1360  //   unsigned int, long int, unsigned long int, long long int, or unsigned
1361  //   long long int. If none of the types in that list can represent all the
1362  //   values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1363  //   type can be converted to an rvalue a prvalue of the extended integer type
1364  //   with lowest integer conversion rank (4.13) greater than the rank of long
1365  //   long in which all the values of the enumeration can be represented. If
1366  //   there are two such extended types, the signed one is chosen.
1367  if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1368    // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1369    // provided for a scoped enumeration.
1370    if (FromEnumType->getDecl()->isScoped())
1371      return false;
1372
1373    // We have already pre-calculated the promotion type, so this is trivial.
1374    if (ToType->isIntegerType() &&
1375        !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
1376      return Context.hasSameUnqualifiedType(ToType,
1377                                FromEnumType->getDecl()->getPromotionType());
1378  }
1379
1380  // C++0x [conv.prom]p2:
1381  //   A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1382  //   to an rvalue a prvalue of the first of the following types that can
1383  //   represent all the values of its underlying type: int, unsigned int,
1384  //   long int, unsigned long int, long long int, or unsigned long long int.
1385  //   If none of the types in that list can represent all the values of its
1386  //   underlying type, an rvalue a prvalue of type char16_t, char32_t,
1387  //   or wchar_t can be converted to an rvalue a prvalue of its underlying
1388  //   type.
1389  if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1390      ToType->isIntegerType()) {
1391    // Determine whether the type we're converting from is signed or
1392    // unsigned.
1393    bool FromIsSigned;
1394    uint64_t FromSize = Context.getTypeSize(FromType);
1395
1396    // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1397    FromIsSigned = true;
1398
1399    // The types we'll try to promote to, in the appropriate
1400    // order. Try each of these types.
1401    QualType PromoteTypes[6] = {
1402      Context.IntTy, Context.UnsignedIntTy,
1403      Context.LongTy, Context.UnsignedLongTy ,
1404      Context.LongLongTy, Context.UnsignedLongLongTy
1405    };
1406    for (int Idx = 0; Idx < 6; ++Idx) {
1407      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1408      if (FromSize < ToSize ||
1409          (FromSize == ToSize &&
1410           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1411        // We found the type that we can promote to. If this is the
1412        // type we wanted, we have a promotion. Otherwise, no
1413        // promotion.
1414        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1415      }
1416    }
1417  }
1418
1419  // An rvalue for an integral bit-field (9.6) can be converted to an
1420  // rvalue of type int if int can represent all the values of the
1421  // bit-field; otherwise, it can be converted to unsigned int if
1422  // unsigned int can represent all the values of the bit-field. If
1423  // the bit-field is larger yet, no integral promotion applies to
1424  // it. If the bit-field has an enumerated type, it is treated as any
1425  // other value of that type for promotion purposes (C++ 4.5p3).
1426  // FIXME: We should delay checking of bit-fields until we actually perform the
1427  // conversion.
1428  using llvm::APSInt;
1429  if (From)
1430    if (FieldDecl *MemberDecl = From->getBitField()) {
1431      APSInt BitWidth;
1432      if (FromType->isIntegralType(Context) &&
1433          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1434        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1435        ToSize = Context.getTypeSize(ToType);
1436
1437        // Are we promoting to an int from a bitfield that fits in an int?
1438        if (BitWidth < ToSize ||
1439            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1440          return To->getKind() == BuiltinType::Int;
1441        }
1442
1443        // Are we promoting to an unsigned int from an unsigned bitfield
1444        // that fits into an unsigned int?
1445        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1446          return To->getKind() == BuiltinType::UInt;
1447        }
1448
1449        return false;
1450      }
1451    }
1452
1453  // An rvalue of type bool can be converted to an rvalue of type int,
1454  // with false becoming zero and true becoming one (C++ 4.5p4).
1455  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1456    return true;
1457  }
1458
1459  return false;
1460}
1461
1462/// IsFloatingPointPromotion - Determines whether the conversion from
1463/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1464/// returns true and sets PromotedType to the promoted type.
1465bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1466  /// An rvalue of type float can be converted to an rvalue of type
1467  /// double. (C++ 4.6p1).
1468  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1469    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1470      if (FromBuiltin->getKind() == BuiltinType::Float &&
1471          ToBuiltin->getKind() == BuiltinType::Double)
1472        return true;
1473
1474      // C99 6.3.1.5p1:
1475      //   When a float is promoted to double or long double, or a
1476      //   double is promoted to long double [...].
1477      if (!getLangOptions().CPlusPlus &&
1478          (FromBuiltin->getKind() == BuiltinType::Float ||
1479           FromBuiltin->getKind() == BuiltinType::Double) &&
1480          (ToBuiltin->getKind() == BuiltinType::LongDouble))
1481        return true;
1482    }
1483
1484  return false;
1485}
1486
1487/// \brief Determine if a conversion is a complex promotion.
1488///
1489/// A complex promotion is defined as a complex -> complex conversion
1490/// where the conversion between the underlying real types is a
1491/// floating-point or integral promotion.
1492bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1493  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1494  if (!FromComplex)
1495    return false;
1496
1497  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1498  if (!ToComplex)
1499    return false;
1500
1501  return IsFloatingPointPromotion(FromComplex->getElementType(),
1502                                  ToComplex->getElementType()) ||
1503    IsIntegralPromotion(0, FromComplex->getElementType(),
1504                        ToComplex->getElementType());
1505}
1506
1507/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1508/// the pointer type FromPtr to a pointer to type ToPointee, with the
1509/// same type qualifiers as FromPtr has on its pointee type. ToType,
1510/// if non-empty, will be a pointer to ToType that may or may not have
1511/// the right set of qualifiers on its pointee.
1512///
1513static QualType
1514BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1515                                   QualType ToPointee, QualType ToType,
1516                                   ASTContext &Context,
1517                                   bool StripObjCLifetime = false) {
1518  assert((FromPtr->getTypeClass() == Type::Pointer ||
1519          FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1520         "Invalid similarly-qualified pointer type");
1521
1522  /// Conversions to 'id' subsume cv-qualifier conversions.
1523  if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1524    return ToType.getUnqualifiedType();
1525
1526  QualType CanonFromPointee
1527    = Context.getCanonicalType(FromPtr->getPointeeType());
1528  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1529  Qualifiers Quals = CanonFromPointee.getQualifiers();
1530
1531  if (StripObjCLifetime)
1532    Quals.removeObjCLifetime();
1533
1534  // Exact qualifier match -> return the pointer type we're converting to.
1535  if (CanonToPointee.getLocalQualifiers() == Quals) {
1536    // ToType is exactly what we need. Return it.
1537    if (!ToType.isNull())
1538      return ToType.getUnqualifiedType();
1539
1540    // Build a pointer to ToPointee. It has the right qualifiers
1541    // already.
1542    if (isa<ObjCObjectPointerType>(ToType))
1543      return Context.getObjCObjectPointerType(ToPointee);
1544    return Context.getPointerType(ToPointee);
1545  }
1546
1547  // Just build a canonical type that has the right qualifiers.
1548  QualType QualifiedCanonToPointee
1549    = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1550
1551  if (isa<ObjCObjectPointerType>(ToType))
1552    return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1553  return Context.getPointerType(QualifiedCanonToPointee);
1554}
1555
1556static bool isNullPointerConstantForConversion(Expr *Expr,
1557                                               bool InOverloadResolution,
1558                                               ASTContext &Context) {
1559  // Handle value-dependent integral null pointer constants correctly.
1560  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1561  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1562      Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1563    return !InOverloadResolution;
1564
1565  return Expr->isNullPointerConstant(Context,
1566                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1567                                        : Expr::NPC_ValueDependentIsNull);
1568}
1569
1570/// IsPointerConversion - Determines whether the conversion of the
1571/// expression From, which has the (possibly adjusted) type FromType,
1572/// can be converted to the type ToType via a pointer conversion (C++
1573/// 4.10). If so, returns true and places the converted type (that
1574/// might differ from ToType in its cv-qualifiers at some level) into
1575/// ConvertedType.
1576///
1577/// This routine also supports conversions to and from block pointers
1578/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1579/// pointers to interfaces. FIXME: Once we've determined the
1580/// appropriate overloading rules for Objective-C, we may want to
1581/// split the Objective-C checks into a different routine; however,
1582/// GCC seems to consider all of these conversions to be pointer
1583/// conversions, so for now they live here. IncompatibleObjC will be
1584/// set if the conversion is an allowed Objective-C conversion that
1585/// should result in a warning.
1586bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1587                               bool InOverloadResolution,
1588                               QualType& ConvertedType,
1589                               bool &IncompatibleObjC) {
1590  IncompatibleObjC = false;
1591  if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1592                              IncompatibleObjC))
1593    return true;
1594
1595  // Conversion from a null pointer constant to any Objective-C pointer type.
1596  if (ToType->isObjCObjectPointerType() &&
1597      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1598    ConvertedType = ToType;
1599    return true;
1600  }
1601
1602  // Blocks: Block pointers can be converted to void*.
1603  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1604      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1605    ConvertedType = ToType;
1606    return true;
1607  }
1608  // Blocks: A null pointer constant can be converted to a block
1609  // pointer type.
1610  if (ToType->isBlockPointerType() &&
1611      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1612    ConvertedType = ToType;
1613    return true;
1614  }
1615
1616  // If the left-hand-side is nullptr_t, the right side can be a null
1617  // pointer constant.
1618  if (ToType->isNullPtrType() &&
1619      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1620    ConvertedType = ToType;
1621    return true;
1622  }
1623
1624  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1625  if (!ToTypePtr)
1626    return false;
1627
1628  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1629  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1630    ConvertedType = ToType;
1631    return true;
1632  }
1633
1634  // Beyond this point, both types need to be pointers
1635  // , including objective-c pointers.
1636  QualType ToPointeeType = ToTypePtr->getPointeeType();
1637  if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1638      !getLangOptions().ObjCAutoRefCount) {
1639    ConvertedType = BuildSimilarlyQualifiedPointerType(
1640                                      FromType->getAs<ObjCObjectPointerType>(),
1641                                                       ToPointeeType,
1642                                                       ToType, Context);
1643    return true;
1644  }
1645  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1646  if (!FromTypePtr)
1647    return false;
1648
1649  QualType FromPointeeType = FromTypePtr->getPointeeType();
1650
1651  // If the unqualified pointee types are the same, this can't be a
1652  // pointer conversion, so don't do all of the work below.
1653  if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1654    return false;
1655
1656  // An rvalue of type "pointer to cv T," where T is an object type,
1657  // can be converted to an rvalue of type "pointer to cv void" (C++
1658  // 4.10p2).
1659  if (FromPointeeType->isIncompleteOrObjectType() &&
1660      ToPointeeType->isVoidType()) {
1661    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1662                                                       ToPointeeType,
1663                                                       ToType, Context,
1664                                                   /*StripObjCLifetime=*/true);
1665    return true;
1666  }
1667
1668  // MSVC allows implicit function to void* type conversion.
1669  if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() &&
1670      ToPointeeType->isVoidType()) {
1671    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1672                                                       ToPointeeType,
1673                                                       ToType, Context);
1674    return true;
1675  }
1676
1677  // When we're overloading in C, we allow a special kind of pointer
1678  // conversion for compatible-but-not-identical pointee types.
1679  if (!getLangOptions().CPlusPlus &&
1680      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1681    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1682                                                       ToPointeeType,
1683                                                       ToType, Context);
1684    return true;
1685  }
1686
1687  // C++ [conv.ptr]p3:
1688  //
1689  //   An rvalue of type "pointer to cv D," where D is a class type,
1690  //   can be converted to an rvalue of type "pointer to cv B," where
1691  //   B is a base class (clause 10) of D. If B is an inaccessible
1692  //   (clause 11) or ambiguous (10.2) base class of D, a program that
1693  //   necessitates this conversion is ill-formed. The result of the
1694  //   conversion is a pointer to the base class sub-object of the
1695  //   derived class object. The null pointer value is converted to
1696  //   the null pointer value of the destination type.
1697  //
1698  // Note that we do not check for ambiguity or inaccessibility
1699  // here. That is handled by CheckPointerConversion.
1700  if (getLangOptions().CPlusPlus &&
1701      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1702      !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1703      !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1704      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1705    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1706                                                       ToPointeeType,
1707                                                       ToType, Context);
1708    return true;
1709  }
1710
1711  if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1712      Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1713    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1714                                                       ToPointeeType,
1715                                                       ToType, Context);
1716    return true;
1717  }
1718
1719  return false;
1720}
1721
1722/// \brief Adopt the given qualifiers for the given type.
1723static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1724  Qualifiers TQs = T.getQualifiers();
1725
1726  // Check whether qualifiers already match.
1727  if (TQs == Qs)
1728    return T;
1729
1730  if (Qs.compatiblyIncludes(TQs))
1731    return Context.getQualifiedType(T, Qs);
1732
1733  return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1734}
1735
1736/// isObjCPointerConversion - Determines whether this is an
1737/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1738/// with the same arguments and return values.
1739bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1740                                   QualType& ConvertedType,
1741                                   bool &IncompatibleObjC) {
1742  if (!getLangOptions().ObjC1)
1743    return false;
1744
1745  // The set of qualifiers on the type we're converting from.
1746  Qualifiers FromQualifiers = FromType.getQualifiers();
1747
1748  // First, we handle all conversions on ObjC object pointer types.
1749  const ObjCObjectPointerType* ToObjCPtr =
1750    ToType->getAs<ObjCObjectPointerType>();
1751  const ObjCObjectPointerType *FromObjCPtr =
1752    FromType->getAs<ObjCObjectPointerType>();
1753
1754  if (ToObjCPtr && FromObjCPtr) {
1755    // If the pointee types are the same (ignoring qualifications),
1756    // then this is not a pointer conversion.
1757    if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1758                                       FromObjCPtr->getPointeeType()))
1759      return false;
1760
1761    // Check for compatible
1762    // Objective C++: We're able to convert between "id" or "Class" and a
1763    // pointer to any interface (in both directions).
1764    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1765      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1766      return true;
1767    }
1768    // Conversions with Objective-C's id<...>.
1769    if ((FromObjCPtr->isObjCQualifiedIdType() ||
1770         ToObjCPtr->isObjCQualifiedIdType()) &&
1771        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1772                                                  /*compare=*/false)) {
1773      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1774      return true;
1775    }
1776    // Objective C++: We're able to convert from a pointer to an
1777    // interface to a pointer to a different interface.
1778    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1779      const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1780      const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1781      if (getLangOptions().CPlusPlus && LHS && RHS &&
1782          !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1783                                                FromObjCPtr->getPointeeType()))
1784        return false;
1785      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1786                                                   ToObjCPtr->getPointeeType(),
1787                                                         ToType, Context);
1788      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1789      return true;
1790    }
1791
1792    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1793      // Okay: this is some kind of implicit downcast of Objective-C
1794      // interfaces, which is permitted. However, we're going to
1795      // complain about it.
1796      IncompatibleObjC = true;
1797      ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1798                                                   ToObjCPtr->getPointeeType(),
1799                                                         ToType, Context);
1800      ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1801      return true;
1802    }
1803  }
1804  // Beyond this point, both types need to be C pointers or block pointers.
1805  QualType ToPointeeType;
1806  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1807    ToPointeeType = ToCPtr->getPointeeType();
1808  else if (const BlockPointerType *ToBlockPtr =
1809            ToType->getAs<BlockPointerType>()) {
1810    // Objective C++: We're able to convert from a pointer to any object
1811    // to a block pointer type.
1812    if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1813      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1814      return true;
1815    }
1816    ToPointeeType = ToBlockPtr->getPointeeType();
1817  }
1818  else if (FromType->getAs<BlockPointerType>() &&
1819           ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1820    // Objective C++: We're able to convert from a block pointer type to a
1821    // pointer to any object.
1822    ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1823    return true;
1824  }
1825  else
1826    return false;
1827
1828  QualType FromPointeeType;
1829  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1830    FromPointeeType = FromCPtr->getPointeeType();
1831  else if (const BlockPointerType *FromBlockPtr =
1832           FromType->getAs<BlockPointerType>())
1833    FromPointeeType = FromBlockPtr->getPointeeType();
1834  else
1835    return false;
1836
1837  // If we have pointers to pointers, recursively check whether this
1838  // is an Objective-C conversion.
1839  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1840      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1841                              IncompatibleObjC)) {
1842    // We always complain about this conversion.
1843    IncompatibleObjC = true;
1844    ConvertedType = Context.getPointerType(ConvertedType);
1845    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1846    return true;
1847  }
1848  // Allow conversion of pointee being objective-c pointer to another one;
1849  // as in I* to id.
1850  if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1851      ToPointeeType->getAs<ObjCObjectPointerType>() &&
1852      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1853                              IncompatibleObjC)) {
1854
1855    ConvertedType = Context.getPointerType(ConvertedType);
1856    ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1857    return true;
1858  }
1859
1860  // If we have pointers to functions or blocks, check whether the only
1861  // differences in the argument and result types are in Objective-C
1862  // pointer conversions. If so, we permit the conversion (but
1863  // complain about it).
1864  const FunctionProtoType *FromFunctionType
1865    = FromPointeeType->getAs<FunctionProtoType>();
1866  const FunctionProtoType *ToFunctionType
1867    = ToPointeeType->getAs<FunctionProtoType>();
1868  if (FromFunctionType && ToFunctionType) {
1869    // If the function types are exactly the same, this isn't an
1870    // Objective-C pointer conversion.
1871    if (Context.getCanonicalType(FromPointeeType)
1872          == Context.getCanonicalType(ToPointeeType))
1873      return false;
1874
1875    // Perform the quick checks that will tell us whether these
1876    // function types are obviously different.
1877    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1878        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1879        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1880      return false;
1881
1882    bool HasObjCConversion = false;
1883    if (Context.getCanonicalType(FromFunctionType->getResultType())
1884          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1885      // Okay, the types match exactly. Nothing to do.
1886    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1887                                       ToFunctionType->getResultType(),
1888                                       ConvertedType, IncompatibleObjC)) {
1889      // Okay, we have an Objective-C pointer conversion.
1890      HasObjCConversion = true;
1891    } else {
1892      // Function types are too different. Abort.
1893      return false;
1894    }
1895
1896    // Check argument types.
1897    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1898         ArgIdx != NumArgs; ++ArgIdx) {
1899      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1900      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1901      if (Context.getCanonicalType(FromArgType)
1902            == Context.getCanonicalType(ToArgType)) {
1903        // Okay, the types match exactly. Nothing to do.
1904      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1905                                         ConvertedType, IncompatibleObjC)) {
1906        // Okay, we have an Objective-C pointer conversion.
1907        HasObjCConversion = true;
1908      } else {
1909        // Argument types are too different. Abort.
1910        return false;
1911      }
1912    }
1913
1914    if (HasObjCConversion) {
1915      // We had an Objective-C conversion. Allow this pointer
1916      // conversion, but complain about it.
1917      ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1918      IncompatibleObjC = true;
1919      return true;
1920    }
1921  }
1922
1923  return false;
1924}
1925
1926/// \brief Determine whether this is an Objective-C writeback conversion,
1927/// used for parameter passing when performing automatic reference counting.
1928///
1929/// \param FromType The type we're converting form.
1930///
1931/// \param ToType The type we're converting to.
1932///
1933/// \param ConvertedType The type that will be produced after applying
1934/// this conversion.
1935bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1936                                     QualType &ConvertedType) {
1937  if (!getLangOptions().ObjCAutoRefCount ||
1938      Context.hasSameUnqualifiedType(FromType, ToType))
1939    return false;
1940
1941  // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1942  QualType ToPointee;
1943  if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1944    ToPointee = ToPointer->getPointeeType();
1945  else
1946    return false;
1947
1948  Qualifiers ToQuals = ToPointee.getQualifiers();
1949  if (!ToPointee->isObjCLifetimeType() ||
1950      ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1951      !ToQuals.withoutObjCGLifetime().empty())
1952    return false;
1953
1954  // Argument must be a pointer to __strong to __weak.
1955  QualType FromPointee;
1956  if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1957    FromPointee = FromPointer->getPointeeType();
1958  else
1959    return false;
1960
1961  Qualifiers FromQuals = FromPointee.getQualifiers();
1962  if (!FromPointee->isObjCLifetimeType() ||
1963      (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1964       FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1965    return false;
1966
1967  // Make sure that we have compatible qualifiers.
1968  FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1969  if (!ToQuals.compatiblyIncludes(FromQuals))
1970    return false;
1971
1972  // Remove qualifiers from the pointee type we're converting from; they
1973  // aren't used in the compatibility check belong, and we'll be adding back
1974  // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1975  FromPointee = FromPointee.getUnqualifiedType();
1976
1977  // The unqualified form of the pointee types must be compatible.
1978  ToPointee = ToPointee.getUnqualifiedType();
1979  bool IncompatibleObjC;
1980  if (Context.typesAreCompatible(FromPointee, ToPointee))
1981    FromPointee = ToPointee;
1982  else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1983                                    IncompatibleObjC))
1984    return false;
1985
1986  /// \brief Construct the type we're converting to, which is a pointer to
1987  /// __autoreleasing pointee.
1988  FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1989  ConvertedType = Context.getPointerType(FromPointee);
1990  return true;
1991}
1992
1993bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1994                                    QualType& ConvertedType) {
1995  QualType ToPointeeType;
1996  if (const BlockPointerType *ToBlockPtr =
1997        ToType->getAs<BlockPointerType>())
1998    ToPointeeType = ToBlockPtr->getPointeeType();
1999  else
2000    return false;
2001
2002  QualType FromPointeeType;
2003  if (const BlockPointerType *FromBlockPtr =
2004      FromType->getAs<BlockPointerType>())
2005    FromPointeeType = FromBlockPtr->getPointeeType();
2006  else
2007    return false;
2008  // We have pointer to blocks, check whether the only
2009  // differences in the argument and result types are in Objective-C
2010  // pointer conversions. If so, we permit the conversion.
2011
2012  const FunctionProtoType *FromFunctionType
2013    = FromPointeeType->getAs<FunctionProtoType>();
2014  const FunctionProtoType *ToFunctionType
2015    = ToPointeeType->getAs<FunctionProtoType>();
2016
2017  if (!FromFunctionType || !ToFunctionType)
2018    return false;
2019
2020  if (Context.hasSameType(FromPointeeType, ToPointeeType))
2021    return true;
2022
2023  // Perform the quick checks that will tell us whether these
2024  // function types are obviously different.
2025  if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2026      FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2027    return false;
2028
2029  FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2030  FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2031  if (FromEInfo != ToEInfo)
2032    return false;
2033
2034  bool IncompatibleObjC = false;
2035  if (Context.hasSameType(FromFunctionType->getResultType(),
2036                          ToFunctionType->getResultType())) {
2037    // Okay, the types match exactly. Nothing to do.
2038  } else {
2039    QualType RHS = FromFunctionType->getResultType();
2040    QualType LHS = ToFunctionType->getResultType();
2041    if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2042        !RHS.hasQualifiers() && LHS.hasQualifiers())
2043       LHS = LHS.getUnqualifiedType();
2044
2045     if (Context.hasSameType(RHS,LHS)) {
2046       // OK exact match.
2047     } else if (isObjCPointerConversion(RHS, LHS,
2048                                        ConvertedType, IncompatibleObjC)) {
2049     if (IncompatibleObjC)
2050       return false;
2051     // Okay, we have an Objective-C pointer conversion.
2052     }
2053     else
2054       return false;
2055   }
2056
2057   // Check argument types.
2058   for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2059        ArgIdx != NumArgs; ++ArgIdx) {
2060     IncompatibleObjC = false;
2061     QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2062     QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2063     if (Context.hasSameType(FromArgType, ToArgType)) {
2064       // Okay, the types match exactly. Nothing to do.
2065     } else if (isObjCPointerConversion(ToArgType, FromArgType,
2066                                        ConvertedType, IncompatibleObjC)) {
2067       if (IncompatibleObjC)
2068         return false;
2069       // Okay, we have an Objective-C pointer conversion.
2070     } else
2071       // Argument types are too different. Abort.
2072       return false;
2073   }
2074   ConvertedType = ToType;
2075   return true;
2076}
2077
2078/// FunctionArgTypesAreEqual - This routine checks two function proto types
2079/// for equlity of their argument types. Caller has already checked that
2080/// they have same number of arguments. This routine assumes that Objective-C
2081/// pointer types which only differ in their protocol qualifiers are equal.
2082bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
2083                                    const FunctionProtoType *NewType) {
2084  if (!getLangOptions().ObjC1)
2085    return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2086                      NewType->arg_type_begin());
2087
2088  for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2089       N = NewType->arg_type_begin(),
2090       E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2091    QualType ToType = (*O);
2092    QualType FromType = (*N);
2093    if (ToType != FromType) {
2094      if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2095        if (const PointerType *PTFr = FromType->getAs<PointerType>())
2096          if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2097               PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2098              (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2099               PTFr->getPointeeType()->isObjCQualifiedClassType()))
2100            continue;
2101      }
2102      else if (const ObjCObjectPointerType *PTTo =
2103                 ToType->getAs<ObjCObjectPointerType>()) {
2104        if (const ObjCObjectPointerType *PTFr =
2105              FromType->getAs<ObjCObjectPointerType>())
2106          if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2107            continue;
2108      }
2109      return false;
2110    }
2111  }
2112  return true;
2113}
2114
2115/// CheckPointerConversion - Check the pointer conversion from the
2116/// expression From to the type ToType. This routine checks for
2117/// ambiguous or inaccessible derived-to-base pointer
2118/// conversions for which IsPointerConversion has already returned
2119/// true. It returns true and produces a diagnostic if there was an
2120/// error, or returns false otherwise.
2121bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2122                                  CastKind &Kind,
2123                                  CXXCastPath& BasePath,
2124                                  bool IgnoreBaseAccess) {
2125  QualType FromType = From->getType();
2126  bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2127
2128  Kind = CK_BitCast;
2129
2130  if (!IsCStyleOrFunctionalCast &&
2131      Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2132      From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2133    DiagRuntimeBehavior(From->getExprLoc(), From,
2134                        PDiag(diag::warn_impcast_bool_to_null_pointer)
2135                          << ToType << From->getSourceRange());
2136
2137  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2138    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2139      QualType FromPointeeType = FromPtrType->getPointeeType(),
2140               ToPointeeType   = ToPtrType->getPointeeType();
2141
2142      if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2143          !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2144        // We must have a derived-to-base conversion. Check an
2145        // ambiguous or inaccessible conversion.
2146        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2147                                         From->getExprLoc(),
2148                                         From->getSourceRange(), &BasePath,
2149                                         IgnoreBaseAccess))
2150          return true;
2151
2152        // The conversion was successful.
2153        Kind = CK_DerivedToBase;
2154      }
2155    }
2156  if (const ObjCObjectPointerType *FromPtrType =
2157        FromType->getAs<ObjCObjectPointerType>()) {
2158    if (const ObjCObjectPointerType *ToPtrType =
2159          ToType->getAs<ObjCObjectPointerType>()) {
2160      // Objective-C++ conversions are always okay.
2161      // FIXME: We should have a different class of conversions for the
2162      // Objective-C++ implicit conversions.
2163      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2164        return false;
2165    }
2166  }
2167
2168  // We shouldn't fall into this case unless it's valid for other
2169  // reasons.
2170  if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2171    Kind = CK_NullToPointer;
2172
2173  return false;
2174}
2175
2176/// IsMemberPointerConversion - Determines whether the conversion of the
2177/// expression From, which has the (possibly adjusted) type FromType, can be
2178/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2179/// If so, returns true and places the converted type (that might differ from
2180/// ToType in its cv-qualifiers at some level) into ConvertedType.
2181bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2182                                     QualType ToType,
2183                                     bool InOverloadResolution,
2184                                     QualType &ConvertedType) {
2185  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2186  if (!ToTypePtr)
2187    return false;
2188
2189  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2190  if (From->isNullPointerConstant(Context,
2191                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2192                                        : Expr::NPC_ValueDependentIsNull)) {
2193    ConvertedType = ToType;
2194    return true;
2195  }
2196
2197  // Otherwise, both types have to be member pointers.
2198  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2199  if (!FromTypePtr)
2200    return false;
2201
2202  // A pointer to member of B can be converted to a pointer to member of D,
2203  // where D is derived from B (C++ 4.11p2).
2204  QualType FromClass(FromTypePtr->getClass(), 0);
2205  QualType ToClass(ToTypePtr->getClass(), 0);
2206
2207  if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2208      !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2209      IsDerivedFrom(ToClass, FromClass)) {
2210    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2211                                                 ToClass.getTypePtr());
2212    return true;
2213  }
2214
2215  return false;
2216}
2217
2218/// CheckMemberPointerConversion - Check the member pointer conversion from the
2219/// expression From to the type ToType. This routine checks for ambiguous or
2220/// virtual or inaccessible base-to-derived member pointer conversions
2221/// for which IsMemberPointerConversion has already returned true. It returns
2222/// true and produces a diagnostic if there was an error, or returns false
2223/// otherwise.
2224bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2225                                        CastKind &Kind,
2226                                        CXXCastPath &BasePath,
2227                                        bool IgnoreBaseAccess) {
2228  QualType FromType = From->getType();
2229  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2230  if (!FromPtrType) {
2231    // This must be a null pointer to member pointer conversion
2232    assert(From->isNullPointerConstant(Context,
2233                                       Expr::NPC_ValueDependentIsNull) &&
2234           "Expr must be null pointer constant!");
2235    Kind = CK_NullToMemberPointer;
2236    return false;
2237  }
2238
2239  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2240  assert(ToPtrType && "No member pointer cast has a target type "
2241                      "that is not a member pointer.");
2242
2243  QualType FromClass = QualType(FromPtrType->getClass(), 0);
2244  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
2245
2246  // FIXME: What about dependent types?
2247  assert(FromClass->isRecordType() && "Pointer into non-class.");
2248  assert(ToClass->isRecordType() && "Pointer into non-class.");
2249
2250  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2251                     /*DetectVirtual=*/true);
2252  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2253  assert(DerivationOkay &&
2254         "Should not have been called if derivation isn't OK.");
2255  (void)DerivationOkay;
2256
2257  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2258                                  getUnqualifiedType())) {
2259    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2260    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2261      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2262    return true;
2263  }
2264
2265  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2266    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2267      << FromClass << ToClass << QualType(VBase, 0)
2268      << From->getSourceRange();
2269    return true;
2270  }
2271
2272  if (!IgnoreBaseAccess)
2273    CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2274                         Paths.front(),
2275                         diag::err_downcast_from_inaccessible_base);
2276
2277  // Must be a base to derived member conversion.
2278  BuildBasePathArray(Paths, BasePath);
2279  Kind = CK_BaseToDerivedMemberPointer;
2280  return false;
2281}
2282
2283/// IsQualificationConversion - Determines whether the conversion from
2284/// an rvalue of type FromType to ToType is a qualification conversion
2285/// (C++ 4.4).
2286///
2287/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2288/// when the qualification conversion involves a change in the Objective-C
2289/// object lifetime.
2290bool
2291Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2292                                bool CStyle, bool &ObjCLifetimeConversion) {
2293  FromType = Context.getCanonicalType(FromType);
2294  ToType = Context.getCanonicalType(ToType);
2295  ObjCLifetimeConversion = false;
2296
2297  // If FromType and ToType are the same type, this is not a
2298  // qualification conversion.
2299  if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2300    return false;
2301
2302  // (C++ 4.4p4):
2303  //   A conversion can add cv-qualifiers at levels other than the first
2304  //   in multi-level pointers, subject to the following rules: [...]
2305  bool PreviousToQualsIncludeConst = true;
2306  bool UnwrappedAnyPointer = false;
2307  while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2308    // Within each iteration of the loop, we check the qualifiers to
2309    // determine if this still looks like a qualification
2310    // conversion. Then, if all is well, we unwrap one more level of
2311    // pointers or pointers-to-members and do it all again
2312    // until there are no more pointers or pointers-to-members left to
2313    // unwrap.
2314    UnwrappedAnyPointer = true;
2315
2316    Qualifiers FromQuals = FromType.getQualifiers();
2317    Qualifiers ToQuals = ToType.getQualifiers();
2318
2319    // Objective-C ARC:
2320    //   Check Objective-C lifetime conversions.
2321    if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2322        UnwrappedAnyPointer) {
2323      if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2324        ObjCLifetimeConversion = true;
2325        FromQuals.removeObjCLifetime();
2326        ToQuals.removeObjCLifetime();
2327      } else {
2328        // Qualification conversions cannot cast between different
2329        // Objective-C lifetime qualifiers.
2330        return false;
2331      }
2332    }
2333
2334    // Allow addition/removal of GC attributes but not changing GC attributes.
2335    if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2336        (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2337      FromQuals.removeObjCGCAttr();
2338      ToQuals.removeObjCGCAttr();
2339    }
2340
2341    //   -- for every j > 0, if const is in cv 1,j then const is in cv
2342    //      2,j, and similarly for volatile.
2343    if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2344      return false;
2345
2346    //   -- if the cv 1,j and cv 2,j are different, then const is in
2347    //      every cv for 0 < k < j.
2348    if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2349        && !PreviousToQualsIncludeConst)
2350      return false;
2351
2352    // Keep track of whether all prior cv-qualifiers in the "to" type
2353    // include const.
2354    PreviousToQualsIncludeConst
2355      = PreviousToQualsIncludeConst && ToQuals.hasConst();
2356  }
2357
2358  // We are left with FromType and ToType being the pointee types
2359  // after unwrapping the original FromType and ToType the same number
2360  // of types. If we unwrapped any pointers, and if FromType and
2361  // ToType have the same unqualified type (since we checked
2362  // qualifiers above), then this is a qualification conversion.
2363  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2364}
2365
2366/// Determines whether there is a user-defined conversion sequence
2367/// (C++ [over.ics.user]) that converts expression From to the type
2368/// ToType. If such a conversion exists, User will contain the
2369/// user-defined conversion sequence that performs such a conversion
2370/// and this routine will return true. Otherwise, this routine returns
2371/// false and User is unspecified.
2372///
2373/// \param AllowExplicit  true if the conversion should consider C++0x
2374/// "explicit" conversion functions as well as non-explicit conversion
2375/// functions (C++0x [class.conv.fct]p2).
2376static OverloadingResult
2377IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2378                        UserDefinedConversionSequence& User,
2379                        OverloadCandidateSet& CandidateSet,
2380                        bool AllowExplicit) {
2381  // Whether we will only visit constructors.
2382  bool ConstructorsOnly = false;
2383
2384  // If the type we are conversion to is a class type, enumerate its
2385  // constructors.
2386  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2387    // C++ [over.match.ctor]p1:
2388    //   When objects of class type are direct-initialized (8.5), or
2389    //   copy-initialized from an expression of the same or a
2390    //   derived class type (8.5), overload resolution selects the
2391    //   constructor. [...] For copy-initialization, the candidate
2392    //   functions are all the converting constructors (12.3.1) of
2393    //   that class. The argument list is the expression-list within
2394    //   the parentheses of the initializer.
2395    if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2396        (From->getType()->getAs<RecordType>() &&
2397         S.IsDerivedFrom(From->getType(), ToType)))
2398      ConstructorsOnly = true;
2399
2400    S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2401    // RequireCompleteType may have returned true due to some invalid decl
2402    // during template instantiation, but ToType may be complete enough now
2403    // to try to recover.
2404    if (ToType->isIncompleteType()) {
2405      // We're not going to find any constructors.
2406    } else if (CXXRecordDecl *ToRecordDecl
2407                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2408      DeclContext::lookup_iterator Con, ConEnd;
2409      for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2410           Con != ConEnd; ++Con) {
2411        NamedDecl *D = *Con;
2412        DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2413
2414        // Find the constructor (which may be a template).
2415        CXXConstructorDecl *Constructor = 0;
2416        FunctionTemplateDecl *ConstructorTmpl
2417          = dyn_cast<FunctionTemplateDecl>(D);
2418        if (ConstructorTmpl)
2419          Constructor
2420            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2421        else
2422          Constructor = cast<CXXConstructorDecl>(D);
2423
2424        if (!Constructor->isInvalidDecl() &&
2425            Constructor->isConvertingConstructor(AllowExplicit)) {
2426          if (ConstructorTmpl)
2427            S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2428                                           /*ExplicitArgs*/ 0,
2429                                           &From, 1, CandidateSet,
2430                                           /*SuppressUserConversions=*/
2431                                             !ConstructorsOnly);
2432          else
2433            // Allow one user-defined conversion when user specifies a
2434            // From->ToType conversion via an static cast (c-style, etc).
2435            S.AddOverloadCandidate(Constructor, FoundDecl,
2436                                   &From, 1, CandidateSet,
2437                                   /*SuppressUserConversions=*/
2438                                     !ConstructorsOnly);
2439        }
2440      }
2441    }
2442  }
2443
2444  // Enumerate conversion functions, if we're allowed to.
2445  if (ConstructorsOnly) {
2446  } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2447                                   S.PDiag(0) << From->getSourceRange())) {
2448    // No conversion functions from incomplete types.
2449  } else if (const RecordType *FromRecordType
2450                                   = From->getType()->getAs<RecordType>()) {
2451    if (CXXRecordDecl *FromRecordDecl
2452         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2453      // Add all of the conversion functions as candidates.
2454      const UnresolvedSetImpl *Conversions
2455        = FromRecordDecl->getVisibleConversionFunctions();
2456      for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2457             E = Conversions->end(); I != E; ++I) {
2458        DeclAccessPair FoundDecl = I.getPair();
2459        NamedDecl *D = FoundDecl.getDecl();
2460        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2461        if (isa<UsingShadowDecl>(D))
2462          D = cast<UsingShadowDecl>(D)->getTargetDecl();
2463
2464        CXXConversionDecl *Conv;
2465        FunctionTemplateDecl *ConvTemplate;
2466        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2467          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2468        else
2469          Conv = cast<CXXConversionDecl>(D);
2470
2471        if (AllowExplicit || !Conv->isExplicit()) {
2472          if (ConvTemplate)
2473            S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2474                                             ActingContext, From, ToType,
2475                                             CandidateSet);
2476          else
2477            S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2478                                     From, ToType, CandidateSet);
2479        }
2480      }
2481    }
2482  }
2483
2484  OverloadCandidateSet::iterator Best;
2485  switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2486  case OR_Success:
2487    // Record the standard conversion we used and the conversion function.
2488    if (CXXConstructorDecl *Constructor
2489          = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2490      S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2491
2492      // C++ [over.ics.user]p1:
2493      //   If the user-defined conversion is specified by a
2494      //   constructor (12.3.1), the initial standard conversion
2495      //   sequence converts the source type to the type required by
2496      //   the argument of the constructor.
2497      //
2498      QualType ThisType = Constructor->getThisType(S.Context);
2499      if (Best->Conversions[0].isEllipsis())
2500        User.EllipsisConversion = true;
2501      else {
2502        User.Before = Best->Conversions[0].Standard;
2503        User.EllipsisConversion = false;
2504      }
2505      User.ConversionFunction = Constructor;
2506      User.FoundConversionFunction = Best->FoundDecl.getDecl();
2507      User.After.setAsIdentityConversion();
2508      User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2509      User.After.setAllToTypes(ToType);
2510      return OR_Success;
2511    } else if (CXXConversionDecl *Conversion
2512                 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2513      S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2514
2515      // C++ [over.ics.user]p1:
2516      //
2517      //   [...] If the user-defined conversion is specified by a
2518      //   conversion function (12.3.2), the initial standard
2519      //   conversion sequence converts the source type to the
2520      //   implicit object parameter of the conversion function.
2521      User.Before = Best->Conversions[0].Standard;
2522      User.ConversionFunction = Conversion;
2523      User.FoundConversionFunction = Best->FoundDecl.getDecl();
2524      User.EllipsisConversion = false;
2525
2526      // C++ [over.ics.user]p2:
2527      //   The second standard conversion sequence converts the
2528      //   result of the user-defined conversion to the target type
2529      //   for the sequence. Since an implicit conversion sequence
2530      //   is an initialization, the special rules for
2531      //   initialization by user-defined conversion apply when
2532      //   selecting the best user-defined conversion for a
2533      //   user-defined conversion sequence (see 13.3.3 and
2534      //   13.3.3.1).
2535      User.After = Best->FinalConversion;
2536      return OR_Success;
2537    } else {
2538      llvm_unreachable("Not a constructor or conversion function?");
2539      return OR_No_Viable_Function;
2540    }
2541
2542  case OR_No_Viable_Function:
2543    return OR_No_Viable_Function;
2544  case OR_Deleted:
2545    // No conversion here! We're done.
2546    return OR_Deleted;
2547
2548  case OR_Ambiguous:
2549    return OR_Ambiguous;
2550  }
2551
2552  return OR_No_Viable_Function;
2553}
2554
2555bool
2556Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
2557  ImplicitConversionSequence ICS;
2558  OverloadCandidateSet CandidateSet(From->getExprLoc());
2559  OverloadingResult OvResult =
2560    IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
2561                            CandidateSet, false);
2562  if (OvResult == OR_Ambiguous)
2563    Diag(From->getSourceRange().getBegin(),
2564         diag::err_typecheck_ambiguous_condition)
2565          << From->getType() << ToType << From->getSourceRange();
2566  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2567    Diag(From->getSourceRange().getBegin(),
2568         diag::err_typecheck_nonviable_condition)
2569    << From->getType() << ToType << From->getSourceRange();
2570  else
2571    return false;
2572  CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
2573  return true;
2574}
2575
2576/// CompareImplicitConversionSequences - Compare two implicit
2577/// conversion sequences to determine whether one is better than the
2578/// other or if they are indistinguishable (C++ 13.3.3.2).
2579static ImplicitConversionSequence::CompareKind
2580CompareImplicitConversionSequences(Sema &S,
2581                                   const ImplicitConversionSequence& ICS1,
2582                                   const ImplicitConversionSequence& ICS2)
2583{
2584  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2585  // conversion sequences (as defined in 13.3.3.1)
2586  //   -- a standard conversion sequence (13.3.3.1.1) is a better
2587  //      conversion sequence than a user-defined conversion sequence or
2588  //      an ellipsis conversion sequence, and
2589  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
2590  //      conversion sequence than an ellipsis conversion sequence
2591  //      (13.3.3.1.3).
2592  //
2593  // C++0x [over.best.ics]p10:
2594  //   For the purpose of ranking implicit conversion sequences as
2595  //   described in 13.3.3.2, the ambiguous conversion sequence is
2596  //   treated as a user-defined sequence that is indistinguishable
2597  //   from any other user-defined conversion sequence.
2598  if (ICS1.getKindRank() < ICS2.getKindRank())
2599    return ImplicitConversionSequence::Better;
2600  else if (ICS2.getKindRank() < ICS1.getKindRank())
2601    return ImplicitConversionSequence::Worse;
2602
2603  // The following checks require both conversion sequences to be of
2604  // the same kind.
2605  if (ICS1.getKind() != ICS2.getKind())
2606    return ImplicitConversionSequence::Indistinguishable;
2607
2608  // Two implicit conversion sequences of the same form are
2609  // indistinguishable conversion sequences unless one of the
2610  // following rules apply: (C++ 13.3.3.2p3):
2611  if (ICS1.isStandard())
2612    return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
2613  else if (ICS1.isUserDefined()) {
2614    // User-defined conversion sequence U1 is a better conversion
2615    // sequence than another user-defined conversion sequence U2 if
2616    // they contain the same user-defined conversion function or
2617    // constructor and if the second standard conversion sequence of
2618    // U1 is better than the second standard conversion sequence of
2619    // U2 (C++ 13.3.3.2p3).
2620    if (ICS1.UserDefined.ConversionFunction ==
2621          ICS2.UserDefined.ConversionFunction)
2622      return CompareStandardConversionSequences(S,
2623                                                ICS1.UserDefined.After,
2624                                                ICS2.UserDefined.After);
2625  }
2626
2627  return ImplicitConversionSequence::Indistinguishable;
2628}
2629
2630static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2631  while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2632    Qualifiers Quals;
2633    T1 = Context.getUnqualifiedArrayType(T1, Quals);
2634    T2 = Context.getUnqualifiedArrayType(T2, Quals);
2635  }
2636
2637  return Context.hasSameUnqualifiedType(T1, T2);
2638}
2639
2640// Per 13.3.3.2p3, compare the given standard conversion sequences to
2641// determine if one is a proper subset of the other.
2642static ImplicitConversionSequence::CompareKind
2643compareStandardConversionSubsets(ASTContext &Context,
2644                                 const StandardConversionSequence& SCS1,
2645                                 const StandardConversionSequence& SCS2) {
2646  ImplicitConversionSequence::CompareKind Result
2647    = ImplicitConversionSequence::Indistinguishable;
2648
2649  // the identity conversion sequence is considered to be a subsequence of
2650  // any non-identity conversion sequence
2651  if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2652    return ImplicitConversionSequence::Better;
2653  else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2654    return ImplicitConversionSequence::Worse;
2655
2656  if (SCS1.Second != SCS2.Second) {
2657    if (SCS1.Second == ICK_Identity)
2658      Result = ImplicitConversionSequence::Better;
2659    else if (SCS2.Second == ICK_Identity)
2660      Result = ImplicitConversionSequence::Worse;
2661    else
2662      return ImplicitConversionSequence::Indistinguishable;
2663  } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
2664    return ImplicitConversionSequence::Indistinguishable;
2665
2666  if (SCS1.Third == SCS2.Third) {
2667    return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2668                             : ImplicitConversionSequence::Indistinguishable;
2669  }
2670
2671  if (SCS1.Third == ICK_Identity)
2672    return Result == ImplicitConversionSequence::Worse
2673             ? ImplicitConversionSequence::Indistinguishable
2674             : ImplicitConversionSequence::Better;
2675
2676  if (SCS2.Third == ICK_Identity)
2677    return Result == ImplicitConversionSequence::Better
2678             ? ImplicitConversionSequence::Indistinguishable
2679             : ImplicitConversionSequence::Worse;
2680
2681  return ImplicitConversionSequence::Indistinguishable;
2682}
2683
2684/// \brief Determine whether one of the given reference bindings is better
2685/// than the other based on what kind of bindings they are.
2686static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2687                                       const StandardConversionSequence &SCS2) {
2688  // C++0x [over.ics.rank]p3b4:
2689  //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2690  //      implicit object parameter of a non-static member function declared
2691  //      without a ref-qualifier, and *either* S1 binds an rvalue reference
2692  //      to an rvalue and S2 binds an lvalue reference *or S1 binds an
2693  //      lvalue reference to a function lvalue and S2 binds an rvalue
2694  //      reference*.
2695  //
2696  // FIXME: Rvalue references. We're going rogue with the above edits,
2697  // because the semantics in the current C++0x working paper (N3225 at the
2698  // time of this writing) break the standard definition of std::forward
2699  // and std::reference_wrapper when dealing with references to functions.
2700  // Proposed wording changes submitted to CWG for consideration.
2701  if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2702      SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2703    return false;
2704
2705  return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2706          SCS2.IsLvalueReference) ||
2707         (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2708          !SCS2.IsLvalueReference);
2709}
2710
2711/// CompareStandardConversionSequences - Compare two standard
2712/// conversion sequences to determine whether one is better than the
2713/// other or if they are indistinguishable (C++ 13.3.3.2p3).
2714static ImplicitConversionSequence::CompareKind
2715CompareStandardConversionSequences(Sema &S,
2716                                   const StandardConversionSequence& SCS1,
2717                                   const StandardConversionSequence& SCS2)
2718{
2719  // Standard conversion sequence S1 is a better conversion sequence
2720  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2721
2722  //  -- S1 is a proper subsequence of S2 (comparing the conversion
2723  //     sequences in the canonical form defined by 13.3.3.1.1,
2724  //     excluding any Lvalue Transformation; the identity conversion
2725  //     sequence is considered to be a subsequence of any
2726  //     non-identity conversion sequence) or, if not that,
2727  if (ImplicitConversionSequence::CompareKind CK
2728        = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
2729    return CK;
2730
2731  //  -- the rank of S1 is better than the rank of S2 (by the rules
2732  //     defined below), or, if not that,
2733  ImplicitConversionRank Rank1 = SCS1.getRank();
2734  ImplicitConversionRank Rank2 = SCS2.getRank();
2735  if (Rank1 < Rank2)
2736    return ImplicitConversionSequence::Better;
2737  else if (Rank2 < Rank1)
2738    return ImplicitConversionSequence::Worse;
2739
2740  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2741  // are indistinguishable unless one of the following rules
2742  // applies:
2743
2744  //   A conversion that is not a conversion of a pointer, or
2745  //   pointer to member, to bool is better than another conversion
2746  //   that is such a conversion.
2747  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2748    return SCS2.isPointerConversionToBool()
2749             ? ImplicitConversionSequence::Better
2750             : ImplicitConversionSequence::Worse;
2751
2752  // C++ [over.ics.rank]p4b2:
2753  //
2754  //   If class B is derived directly or indirectly from class A,
2755  //   conversion of B* to A* is better than conversion of B* to
2756  //   void*, and conversion of A* to void* is better than conversion
2757  //   of B* to void*.
2758  bool SCS1ConvertsToVoid
2759    = SCS1.isPointerConversionToVoidPointer(S.Context);
2760  bool SCS2ConvertsToVoid
2761    = SCS2.isPointerConversionToVoidPointer(S.Context);
2762  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2763    // Exactly one of the conversion sequences is a conversion to
2764    // a void pointer; it's the worse conversion.
2765    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2766                              : ImplicitConversionSequence::Worse;
2767  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2768    // Neither conversion sequence converts to a void pointer; compare
2769    // their derived-to-base conversions.
2770    if (ImplicitConversionSequence::CompareKind DerivedCK
2771          = CompareDerivedToBaseConversions(S, SCS1, SCS2))
2772      return DerivedCK;
2773  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2774             !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
2775    // Both conversion sequences are conversions to void
2776    // pointers. Compare the source types to determine if there's an
2777    // inheritance relationship in their sources.
2778    QualType FromType1 = SCS1.getFromType();
2779    QualType FromType2 = SCS2.getFromType();
2780
2781    // Adjust the types we're converting from via the array-to-pointer
2782    // conversion, if we need to.
2783    if (SCS1.First == ICK_Array_To_Pointer)
2784      FromType1 = S.Context.getArrayDecayedType(FromType1);
2785    if (SCS2.First == ICK_Array_To_Pointer)
2786      FromType2 = S.Context.getArrayDecayedType(FromType2);
2787
2788    QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2789    QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
2790
2791    if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2792      return ImplicitConversionSequence::Better;
2793    else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2794      return ImplicitConversionSequence::Worse;
2795
2796    // Objective-C++: If one interface is more specific than the
2797    // other, it is the better one.
2798    const ObjCObjectPointerType* FromObjCPtr1
2799      = FromType1->getAs<ObjCObjectPointerType>();
2800    const ObjCObjectPointerType* FromObjCPtr2
2801      = FromType2->getAs<ObjCObjectPointerType>();
2802    if (FromObjCPtr1 && FromObjCPtr2) {
2803      bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2804                                                          FromObjCPtr2);
2805      bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2806                                                           FromObjCPtr1);
2807      if (AssignLeft != AssignRight) {
2808        return AssignLeft? ImplicitConversionSequence::Better
2809                         : ImplicitConversionSequence::Worse;
2810      }
2811    }
2812  }
2813
2814  // Compare based on qualification conversions (C++ 13.3.3.2p3,
2815  // bullet 3).
2816  if (ImplicitConversionSequence::CompareKind QualCK
2817        = CompareQualificationConversions(S, SCS1, SCS2))
2818    return QualCK;
2819
2820  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
2821    // Check for a better reference binding based on the kind of bindings.
2822    if (isBetterReferenceBindingKind(SCS1, SCS2))
2823      return ImplicitConversionSequence::Better;
2824    else if (isBetterReferenceBindingKind(SCS2, SCS1))
2825      return ImplicitConversionSequence::Worse;
2826
2827    // C++ [over.ics.rank]p3b4:
2828    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
2829    //      which the references refer are the same type except for
2830    //      top-level cv-qualifiers, and the type to which the reference
2831    //      initialized by S2 refers is more cv-qualified than the type
2832    //      to which the reference initialized by S1 refers.
2833    QualType T1 = SCS1.getToType(2);
2834    QualType T2 = SCS2.getToType(2);
2835    T1 = S.Context.getCanonicalType(T1);
2836    T2 = S.Context.getCanonicalType(T2);
2837    Qualifiers T1Quals, T2Quals;
2838    QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2839    QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2840    if (UnqualT1 == UnqualT2) {
2841      // Objective-C++ ARC: If the references refer to objects with different
2842      // lifetimes, prefer bindings that don't change lifetime.
2843      if (SCS1.ObjCLifetimeConversionBinding !=
2844                                          SCS2.ObjCLifetimeConversionBinding) {
2845        return SCS1.ObjCLifetimeConversionBinding
2846                                           ? ImplicitConversionSequence::Worse
2847                                           : ImplicitConversionSequence::Better;
2848      }
2849
2850      // If the type is an array type, promote the element qualifiers to the
2851      // type for comparison.
2852      if (isa<ArrayType>(T1) && T1Quals)
2853        T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2854      if (isa<ArrayType>(T2) && T2Quals)
2855        T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2856      if (T2.isMoreQualifiedThan(T1))
2857        return ImplicitConversionSequence::Better;
2858      else if (T1.isMoreQualifiedThan(T2))
2859        return ImplicitConversionSequence::Worse;
2860    }
2861  }
2862
2863  return ImplicitConversionSequence::Indistinguishable;
2864}
2865
2866/// CompareQualificationConversions - Compares two standard conversion
2867/// sequences to determine whether they can be ranked based on their
2868/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2869ImplicitConversionSequence::CompareKind
2870CompareQualificationConversions(Sema &S,
2871                                const StandardConversionSequence& SCS1,
2872                                const StandardConversionSequence& SCS2) {
2873  // C++ 13.3.3.2p3:
2874  //  -- S1 and S2 differ only in their qualification conversion and
2875  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
2876  //     cv-qualification signature of type T1 is a proper subset of
2877  //     the cv-qualification signature of type T2, and S1 is not the
2878  //     deprecated string literal array-to-pointer conversion (4.2).
2879  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2880      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2881    return ImplicitConversionSequence::Indistinguishable;
2882
2883  // FIXME: the example in the standard doesn't use a qualification
2884  // conversion (!)
2885  QualType T1 = SCS1.getToType(2);
2886  QualType T2 = SCS2.getToType(2);
2887  T1 = S.Context.getCanonicalType(T1);
2888  T2 = S.Context.getCanonicalType(T2);
2889  Qualifiers T1Quals, T2Quals;
2890  QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2891  QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2892
2893  // If the types are the same, we won't learn anything by unwrapped
2894  // them.
2895  if (UnqualT1 == UnqualT2)
2896    return ImplicitConversionSequence::Indistinguishable;
2897
2898  // If the type is an array type, promote the element qualifiers to the type
2899  // for comparison.
2900  if (isa<ArrayType>(T1) && T1Quals)
2901    T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2902  if (isa<ArrayType>(T2) && T2Quals)
2903    T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2904
2905  ImplicitConversionSequence::CompareKind Result
2906    = ImplicitConversionSequence::Indistinguishable;
2907
2908  // Objective-C++ ARC:
2909  //   Prefer qualification conversions not involving a change in lifetime
2910  //   to qualification conversions that do not change lifetime.
2911  if (SCS1.QualificationIncludesObjCLifetime !=
2912                                      SCS2.QualificationIncludesObjCLifetime) {
2913    Result = SCS1.QualificationIncludesObjCLifetime
2914               ? ImplicitConversionSequence::Worse
2915               : ImplicitConversionSequence::Better;
2916  }
2917
2918  while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
2919    // Within each iteration of the loop, we check the qualifiers to
2920    // determine if this still looks like a qualification
2921    // conversion. Then, if all is well, we unwrap one more level of
2922    // pointers or pointers-to-members and do it all again
2923    // until there are no more pointers or pointers-to-members left
2924    // to unwrap. This essentially mimics what
2925    // IsQualificationConversion does, but here we're checking for a
2926    // strict subset of qualifiers.
2927    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2928      // The qualifiers are the same, so this doesn't tell us anything
2929      // about how the sequences rank.
2930      ;
2931    else if (T2.isMoreQualifiedThan(T1)) {
2932      // T1 has fewer qualifiers, so it could be the better sequence.
2933      if (Result == ImplicitConversionSequence::Worse)
2934        // Neither has qualifiers that are a subset of the other's
2935        // qualifiers.
2936        return ImplicitConversionSequence::Indistinguishable;
2937
2938      Result = ImplicitConversionSequence::Better;
2939    } else if (T1.isMoreQualifiedThan(T2)) {
2940      // T2 has fewer qualifiers, so it could be the better sequence.
2941      if (Result == ImplicitConversionSequence::Better)
2942        // Neither has qualifiers that are a subset of the other's
2943        // qualifiers.
2944        return ImplicitConversionSequence::Indistinguishable;
2945
2946      Result = ImplicitConversionSequence::Worse;
2947    } else {
2948      // Qualifiers are disjoint.
2949      return ImplicitConversionSequence::Indistinguishable;
2950    }
2951
2952    // If the types after this point are equivalent, we're done.
2953    if (S.Context.hasSameUnqualifiedType(T1, T2))
2954      break;
2955  }
2956
2957  // Check that the winning standard conversion sequence isn't using
2958  // the deprecated string literal array to pointer conversion.
2959  switch (Result) {
2960  case ImplicitConversionSequence::Better:
2961    if (SCS1.DeprecatedStringLiteralToCharPtr)
2962      Result = ImplicitConversionSequence::Indistinguishable;
2963    break;
2964
2965  case ImplicitConversionSequence::Indistinguishable:
2966    break;
2967
2968  case ImplicitConversionSequence::Worse:
2969    if (SCS2.DeprecatedStringLiteralToCharPtr)
2970      Result = ImplicitConversionSequence::Indistinguishable;
2971    break;
2972  }
2973
2974  return Result;
2975}
2976
2977/// CompareDerivedToBaseConversions - Compares two standard conversion
2978/// sequences to determine whether they can be ranked based on their
2979/// various kinds of derived-to-base conversions (C++
2980/// [over.ics.rank]p4b3).  As part of these checks, we also look at
2981/// conversions between Objective-C interface types.
2982ImplicitConversionSequence::CompareKind
2983CompareDerivedToBaseConversions(Sema &S,
2984                                const StandardConversionSequence& SCS1,
2985                                const StandardConversionSequence& SCS2) {
2986  QualType FromType1 = SCS1.getFromType();
2987  QualType ToType1 = SCS1.getToType(1);
2988  QualType FromType2 = SCS2.getFromType();
2989  QualType ToType2 = SCS2.getToType(1);
2990
2991  // Adjust the types we're converting from via the array-to-pointer
2992  // conversion, if we need to.
2993  if (SCS1.First == ICK_Array_To_Pointer)
2994    FromType1 = S.Context.getArrayDecayedType(FromType1);
2995  if (SCS2.First == ICK_Array_To_Pointer)
2996    FromType2 = S.Context.getArrayDecayedType(FromType2);
2997
2998  // Canonicalize all of the types.
2999  FromType1 = S.Context.getCanonicalType(FromType1);
3000  ToType1 = S.Context.getCanonicalType(ToType1);
3001  FromType2 = S.Context.getCanonicalType(FromType2);
3002  ToType2 = S.Context.getCanonicalType(ToType2);
3003
3004  // C++ [over.ics.rank]p4b3:
3005  //
3006  //   If class B is derived directly or indirectly from class A and
3007  //   class C is derived directly or indirectly from B,
3008  //
3009  // Compare based on pointer conversions.
3010  if (SCS1.Second == ICK_Pointer_Conversion &&
3011      SCS2.Second == ICK_Pointer_Conversion &&
3012      /*FIXME: Remove if Objective-C id conversions get their own rank*/
3013      FromType1->isPointerType() && FromType2->isPointerType() &&
3014      ToType1->isPointerType() && ToType2->isPointerType()) {
3015    QualType FromPointee1
3016      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3017    QualType ToPointee1
3018      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3019    QualType FromPointee2
3020      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3021    QualType ToPointee2
3022      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3023
3024    //   -- conversion of C* to B* is better than conversion of C* to A*,
3025    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3026      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3027        return ImplicitConversionSequence::Better;
3028      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3029        return ImplicitConversionSequence::Worse;
3030    }
3031
3032    //   -- conversion of B* to A* is better than conversion of C* to A*,
3033    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3034      if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3035        return ImplicitConversionSequence::Better;
3036      else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3037        return ImplicitConversionSequence::Worse;
3038    }
3039  } else if (SCS1.Second == ICK_Pointer_Conversion &&
3040             SCS2.Second == ICK_Pointer_Conversion) {
3041    const ObjCObjectPointerType *FromPtr1
3042      = FromType1->getAs<ObjCObjectPointerType>();
3043    const ObjCObjectPointerType *FromPtr2
3044      = FromType2->getAs<ObjCObjectPointerType>();
3045    const ObjCObjectPointerType *ToPtr1
3046      = ToType1->getAs<ObjCObjectPointerType>();
3047    const ObjCObjectPointerType *ToPtr2
3048      = ToType2->getAs<ObjCObjectPointerType>();
3049
3050    if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3051      // Apply the same conversion ranking rules for Objective-C pointer types
3052      // that we do for C++ pointers to class types. However, we employ the
3053      // Objective-C pseudo-subtyping relationship used for assignment of
3054      // Objective-C pointer types.
3055      bool FromAssignLeft
3056        = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3057      bool FromAssignRight
3058        = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3059      bool ToAssignLeft
3060        = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3061      bool ToAssignRight
3062        = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3063
3064      // A conversion to an a non-id object pointer type or qualified 'id'
3065      // type is better than a conversion to 'id'.
3066      if (ToPtr1->isObjCIdType() &&
3067          (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3068        return ImplicitConversionSequence::Worse;
3069      if (ToPtr2->isObjCIdType() &&
3070          (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3071        return ImplicitConversionSequence::Better;
3072
3073      // A conversion to a non-id object pointer type is better than a
3074      // conversion to a qualified 'id' type
3075      if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3076        return ImplicitConversionSequence::Worse;
3077      if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3078        return ImplicitConversionSequence::Better;
3079
3080      // A conversion to an a non-Class object pointer type or qualified 'Class'
3081      // type is better than a conversion to 'Class'.
3082      if (ToPtr1->isObjCClassType() &&
3083          (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3084        return ImplicitConversionSequence::Worse;
3085      if (ToPtr2->isObjCClassType() &&
3086          (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3087        return ImplicitConversionSequence::Better;
3088
3089      // A conversion to a non-Class object pointer type is better than a
3090      // conversion to a qualified 'Class' type.
3091      if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3092        return ImplicitConversionSequence::Worse;
3093      if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3094        return ImplicitConversionSequence::Better;
3095
3096      //   -- "conversion of C* to B* is better than conversion of C* to A*,"
3097      if (S.Context.hasSameType(FromType1, FromType2) &&
3098          !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3099          (ToAssignLeft != ToAssignRight))
3100        return ToAssignLeft? ImplicitConversionSequence::Worse
3101                           : ImplicitConversionSequence::Better;
3102
3103      //   -- "conversion of B* to A* is better than conversion of C* to A*,"
3104      if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3105          (FromAssignLeft != FromAssignRight))
3106        return FromAssignLeft? ImplicitConversionSequence::Better
3107        : ImplicitConversionSequence::Worse;
3108    }
3109  }
3110
3111  // Ranking of member-pointer types.
3112  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3113      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3114      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3115    const MemberPointerType * FromMemPointer1 =
3116                                        FromType1->getAs<MemberPointerType>();
3117    const MemberPointerType * ToMemPointer1 =
3118                                          ToType1->getAs<MemberPointerType>();
3119    const MemberPointerType * FromMemPointer2 =
3120                                          FromType2->getAs<MemberPointerType>();
3121    const MemberPointerType * ToMemPointer2 =
3122                                          ToType2->getAs<MemberPointerType>();
3123    const Type *FromPointeeType1 = FromMemPointer1->getClass();
3124    const Type *ToPointeeType1 = ToMemPointer1->getClass();
3125    const Type *FromPointeeType2 = FromMemPointer2->getClass();
3126    const Type *ToPointeeType2 = ToMemPointer2->getClass();
3127    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3128    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3129    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3130    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3131    // conversion of A::* to B::* is better than conversion of A::* to C::*,
3132    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3133      if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3134        return ImplicitConversionSequence::Worse;
3135      else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3136        return ImplicitConversionSequence::Better;
3137    }
3138    // conversion of B::* to C::* is better than conversion of A::* to C::*
3139    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3140      if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3141        return ImplicitConversionSequence::Better;
3142      else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3143        return ImplicitConversionSequence::Worse;
3144    }
3145  }
3146
3147  if (SCS1.Second == ICK_Derived_To_Base) {
3148    //   -- conversion of C to B is better than conversion of C to A,
3149    //   -- binding of an expression of type C to a reference of type
3150    //      B& is better than binding an expression of type C to a
3151    //      reference of type A&,
3152    if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3153        !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3154      if (S.IsDerivedFrom(ToType1, ToType2))
3155        return ImplicitConversionSequence::Better;
3156      else if (S.IsDerivedFrom(ToType2, ToType1))
3157        return ImplicitConversionSequence::Worse;
3158    }
3159
3160    //   -- conversion of B to A is better than conversion of C to A.
3161    //   -- binding of an expression of type B to a reference of type
3162    //      A& is better than binding an expression of type C to a
3163    //      reference of type A&,
3164    if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3165        S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3166      if (S.IsDerivedFrom(FromType2, FromType1))
3167        return ImplicitConversionSequence::Better;
3168      else if (S.IsDerivedFrom(FromType1, FromType2))
3169        return ImplicitConversionSequence::Worse;
3170    }
3171  }
3172
3173  return ImplicitConversionSequence::Indistinguishable;
3174}
3175
3176/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3177/// determine whether they are reference-related,
3178/// reference-compatible, reference-compatible with added
3179/// qualification, or incompatible, for use in C++ initialization by
3180/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3181/// type, and the first type (T1) is the pointee type of the reference
3182/// type being initialized.
3183Sema::ReferenceCompareResult
3184Sema::CompareReferenceRelationship(SourceLocation Loc,
3185                                   QualType OrigT1, QualType OrigT2,
3186                                   bool &DerivedToBase,
3187                                   bool &ObjCConversion,
3188                                   bool &ObjCLifetimeConversion) {
3189  assert(!OrigT1->isReferenceType() &&
3190    "T1 must be the pointee type of the reference type");
3191  assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3192
3193  QualType T1 = Context.getCanonicalType(OrigT1);
3194  QualType T2 = Context.getCanonicalType(OrigT2);
3195  Qualifiers T1Quals, T2Quals;
3196  QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3197  QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3198
3199  // C++ [dcl.init.ref]p4:
3200  //   Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3201  //   reference-related to "cv2 T2" if T1 is the same type as T2, or
3202  //   T1 is a base class of T2.
3203  DerivedToBase = false;
3204  ObjCConversion = false;
3205  ObjCLifetimeConversion = false;
3206  if (UnqualT1 == UnqualT2) {
3207    // Nothing to do.
3208  } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
3209           IsDerivedFrom(UnqualT2, UnqualT1))
3210    DerivedToBase = true;
3211  else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3212           UnqualT2->isObjCObjectOrInterfaceType() &&
3213           Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3214    ObjCConversion = true;
3215  else
3216    return Ref_Incompatible;
3217
3218  // At this point, we know that T1 and T2 are reference-related (at
3219  // least).
3220
3221  // If the type is an array type, promote the element qualifiers to the type
3222  // for comparison.
3223  if (isa<ArrayType>(T1) && T1Quals)
3224    T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3225  if (isa<ArrayType>(T2) && T2Quals)
3226    T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3227
3228  // C++ [dcl.init.ref]p4:
3229  //   "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3230  //   reference-related to T2 and cv1 is the same cv-qualification
3231  //   as, or greater cv-qualification than, cv2. For purposes of
3232  //   overload resolution, cases for which cv1 is greater
3233  //   cv-qualification than cv2 are identified as
3234  //   reference-compatible with added qualification (see 13.3.3.2).
3235  //
3236  // Note that we also require equivalence of Objective-C GC and address-space
3237  // qualifiers when performing these computations, so that e.g., an int in
3238  // address space 1 is not reference-compatible with an int in address
3239  // space 2.
3240  if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3241      T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3242    T1Quals.removeObjCLifetime();
3243    T2Quals.removeObjCLifetime();
3244    ObjCLifetimeConversion = true;
3245  }
3246
3247  if (T1Quals == T2Quals)
3248    return Ref_Compatible;
3249  else if (T1Quals.compatiblyIncludes(T2Quals))
3250    return Ref_Compatible_With_Added_Qualification;
3251  else
3252    return Ref_Related;
3253}
3254
3255/// \brief Look for a user-defined conversion to an value reference-compatible
3256///        with DeclType. Return true if something definite is found.
3257static bool
3258FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3259                         QualType DeclType, SourceLocation DeclLoc,
3260                         Expr *Init, QualType T2, bool AllowRvalues,
3261                         bool AllowExplicit) {
3262  assert(T2->isRecordType() && "Can only find conversions of record types.");
3263  CXXRecordDecl *T2RecordDecl
3264    = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3265
3266  OverloadCandidateSet CandidateSet(DeclLoc);
3267  const UnresolvedSetImpl *Conversions
3268    = T2RecordDecl->getVisibleConversionFunctions();
3269  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3270         E = Conversions->end(); I != E; ++I) {
3271    NamedDecl *D = *I;
3272    CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3273    if (isa<UsingShadowDecl>(D))
3274      D = cast<UsingShadowDecl>(D)->getTargetDecl();
3275
3276    FunctionTemplateDecl *ConvTemplate
3277      = dyn_cast<FunctionTemplateDecl>(D);
3278    CXXConversionDecl *Conv;
3279    if (ConvTemplate)
3280      Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3281    else
3282      Conv = cast<CXXConversionDecl>(D);
3283
3284    // If this is an explicit conversion, and we're not allowed to consider
3285    // explicit conversions, skip it.
3286    if (!AllowExplicit && Conv->isExplicit())
3287      continue;
3288
3289    if (AllowRvalues) {
3290      bool DerivedToBase = false;
3291      bool ObjCConversion = false;
3292      bool ObjCLifetimeConversion = false;
3293      if (!ConvTemplate &&
3294          S.CompareReferenceRelationship(
3295            DeclLoc,
3296            Conv->getConversionType().getNonReferenceType()
3297              .getUnqualifiedType(),
3298            DeclType.getNonReferenceType().getUnqualifiedType(),
3299            DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
3300          Sema::Ref_Incompatible)
3301        continue;
3302    } else {
3303      // If the conversion function doesn't return a reference type,
3304      // it can't be considered for this conversion. An rvalue reference
3305      // is only acceptable if its referencee is a function type.
3306
3307      const ReferenceType *RefType =
3308        Conv->getConversionType()->getAs<ReferenceType>();
3309      if (!RefType ||
3310          (!RefType->isLValueReferenceType() &&
3311           !RefType->getPointeeType()->isFunctionType()))
3312        continue;
3313    }
3314
3315    if (ConvTemplate)
3316      S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
3317                                       Init, DeclType, CandidateSet);
3318    else
3319      S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
3320                               DeclType, CandidateSet);
3321  }
3322
3323  OverloadCandidateSet::iterator Best;
3324  switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3325  case OR_Success:
3326    // C++ [over.ics.ref]p1:
3327    //
3328    //   [...] If the parameter binds directly to the result of
3329    //   applying a conversion function to the argument
3330    //   expression, the implicit conversion sequence is a
3331    //   user-defined conversion sequence (13.3.3.1.2), with the
3332    //   second standard conversion sequence either an identity
3333    //   conversion or, if the conversion function returns an
3334    //   entity of a type that is a derived class of the parameter
3335    //   type, a derived-to-base Conversion.
3336    if (!Best->FinalConversion.DirectBinding)
3337      return false;
3338
3339    if (Best->Function)
3340      S.MarkDeclarationReferenced(DeclLoc, Best->Function);
3341    ICS.setUserDefined();
3342    ICS.UserDefined.Before = Best->Conversions[0].Standard;
3343    ICS.UserDefined.After = Best->FinalConversion;
3344    ICS.UserDefined.ConversionFunction = Best->Function;
3345    ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
3346    ICS.UserDefined.EllipsisConversion = false;
3347    assert(ICS.UserDefined.After.ReferenceBinding &&
3348           ICS.UserDefined.After.DirectBinding &&
3349           "Expected a direct reference binding!");
3350    return true;
3351
3352  case OR_Ambiguous:
3353    ICS.setAmbiguous();
3354    for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3355         Cand != CandidateSet.end(); ++Cand)
3356      if (Cand->Viable)
3357        ICS.Ambiguous.addConversion(Cand->Function);
3358    return true;
3359
3360  case OR_No_Viable_Function:
3361  case OR_Deleted:
3362    // There was no suitable conversion, or we found a deleted
3363    // conversion; continue with other checks.
3364    return false;
3365  }
3366
3367  return false;
3368}
3369
3370/// \brief Compute an implicit conversion sequence for reference
3371/// initialization.
3372static ImplicitConversionSequence
3373TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3374                 SourceLocation DeclLoc,
3375                 bool SuppressUserConversions,
3376                 bool AllowExplicit) {
3377  assert(DeclType->isReferenceType() && "Reference init needs a reference");
3378
3379  // Most paths end in a failed conversion.
3380  ImplicitConversionSequence ICS;
3381  ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3382
3383  QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3384  QualType T2 = Init->getType();
3385
3386  // If the initializer is the address of an overloaded function, try
3387  // to resolve the overloaded function. If all goes well, T2 is the
3388  // type of the resulting function.
3389  if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3390    DeclAccessPair Found;
3391    if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3392                                                                false, Found))
3393      T2 = Fn->getType();
3394  }
3395
3396  // Compute some basic properties of the types and the initializer.
3397  bool isRValRef = DeclType->isRValueReferenceType();
3398  bool DerivedToBase = false;
3399  bool ObjCConversion = false;
3400  bool ObjCLifetimeConversion = false;
3401  Expr::Classification InitCategory = Init->Classify(S.Context);
3402  Sema::ReferenceCompareResult RefRelationship
3403    = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3404                                     ObjCConversion, ObjCLifetimeConversion);
3405
3406
3407  // C++0x [dcl.init.ref]p5:
3408  //   A reference to type "cv1 T1" is initialized by an expression
3409  //   of type "cv2 T2" as follows:
3410
3411  //     -- If reference is an lvalue reference and the initializer expression
3412  if (!isRValRef) {
3413    //     -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3414    //        reference-compatible with "cv2 T2," or
3415    //
3416    // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3417    if (InitCategory.isLValue() &&
3418        RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3419      // C++ [over.ics.ref]p1:
3420      //   When a parameter of reference type binds directly (8.5.3)
3421      //   to an argument expression, the implicit conversion sequence
3422      //   is the identity conversion, unless the argument expression
3423      //   has a type that is a derived class of the parameter type,
3424      //   in which case the implicit conversion sequence is a
3425      //   derived-to-base Conversion (13.3.3.1).
3426      ICS.setStandard();
3427      ICS.Standard.First = ICK_Identity;
3428      ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3429                         : ObjCConversion? ICK_Compatible_Conversion
3430                         : ICK_Identity;
3431      ICS.Standard.Third = ICK_Identity;
3432      ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3433      ICS.Standard.setToType(0, T2);
3434      ICS.Standard.setToType(1, T1);
3435      ICS.Standard.setToType(2, T1);
3436      ICS.Standard.ReferenceBinding = true;
3437      ICS.Standard.DirectBinding = true;
3438      ICS.Standard.IsLvalueReference = !isRValRef;
3439      ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3440      ICS.Standard.BindsToRvalue = false;
3441      ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3442      ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
3443      ICS.Standard.CopyConstructor = 0;
3444
3445      // Nothing more to do: the inaccessibility/ambiguity check for
3446      // derived-to-base conversions is suppressed when we're
3447      // computing the implicit conversion sequence (C++
3448      // [over.best.ics]p2).
3449      return ICS;
3450    }
3451
3452    //       -- has a class type (i.e., T2 is a class type), where T1 is
3453    //          not reference-related to T2, and can be implicitly
3454    //          converted to an lvalue of type "cv3 T3," where "cv1 T1"
3455    //          is reference-compatible with "cv3 T3" 92) (this
3456    //          conversion is selected by enumerating the applicable
3457    //          conversion functions (13.3.1.6) and choosing the best
3458    //          one through overload resolution (13.3)),
3459    if (!SuppressUserConversions && T2->isRecordType() &&
3460        !S.RequireCompleteType(DeclLoc, T2, 0) &&
3461        RefRelationship == Sema::Ref_Incompatible) {
3462      if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3463                                   Init, T2, /*AllowRvalues=*/false,
3464                                   AllowExplicit))
3465        return ICS;
3466    }
3467  }
3468
3469  //     -- Otherwise, the reference shall be an lvalue reference to a
3470  //        non-volatile const type (i.e., cv1 shall be const), or the reference
3471  //        shall be an rvalue reference.
3472  //
3473  // We actually handle one oddity of C++ [over.ics.ref] at this
3474  // point, which is that, due to p2 (which short-circuits reference
3475  // binding by only attempting a simple conversion for non-direct
3476  // bindings) and p3's strange wording, we allow a const volatile
3477  // reference to bind to an rvalue. Hence the check for the presence
3478  // of "const" rather than checking for "const" being the only
3479  // qualifier.
3480  // This is also the point where rvalue references and lvalue inits no longer
3481  // go together.
3482  if (!isRValRef && !T1.isConstQualified())
3483    return ICS;
3484
3485  //       -- If the initializer expression
3486  //
3487  //            -- is an xvalue, class prvalue, array prvalue or function
3488  //               lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
3489  if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3490      (InitCategory.isXValue() ||
3491      (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3492      (InitCategory.isLValue() && T2->isFunctionType()))) {
3493    ICS.setStandard();
3494    ICS.Standard.First = ICK_Identity;
3495    ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3496                      : ObjCConversion? ICK_Compatible_Conversion
3497                      : ICK_Identity;
3498    ICS.Standard.Third = ICK_Identity;
3499    ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3500    ICS.Standard.setToType(0, T2);
3501    ICS.Standard.setToType(1, T1);
3502    ICS.Standard.setToType(2, T1);
3503    ICS.Standard.ReferenceBinding = true;
3504    // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3505    // binding unless we're binding to a class prvalue.
3506    // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3507    // allow the use of rvalue references in C++98/03 for the benefit of
3508    // standard library implementors; therefore, we need the xvalue check here.
3509    ICS.Standard.DirectBinding =
3510      S.getLangOptions().CPlusPlus0x ||
3511      (InitCategory.isPRValue() && !T2->isRecordType());
3512    ICS.Standard.IsLvalueReference = !isRValRef;
3513    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3514    ICS.Standard.BindsToRvalue = InitCategory.isRValue();
3515    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3516    ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
3517    ICS.Standard.CopyConstructor = 0;
3518    return ICS;
3519  }
3520
3521  //            -- has a class type (i.e., T2 is a class type), where T1 is not
3522  //               reference-related to T2, and can be implicitly converted to
3523  //               an xvalue, class prvalue, or function lvalue of type
3524  //               "cv3 T3", where "cv1 T1" is reference-compatible with
3525  //               "cv3 T3",
3526  //
3527  //          then the reference is bound to the value of the initializer
3528  //          expression in the first case and to the result of the conversion
3529  //          in the second case (or, in either case, to an appropriate base
3530  //          class subobject).
3531  if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3532      T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3533      FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3534                               Init, T2, /*AllowRvalues=*/true,
3535                               AllowExplicit)) {
3536    // In the second case, if the reference is an rvalue reference
3537    // and the second standard conversion sequence of the
3538    // user-defined conversion sequence includes an lvalue-to-rvalue
3539    // conversion, the program is ill-formed.
3540    if (ICS.isUserDefined() && isRValRef &&
3541        ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3542      ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3543
3544    return ICS;
3545  }
3546
3547  //       -- Otherwise, a temporary of type "cv1 T1" is created and
3548  //          initialized from the initializer expression using the
3549  //          rules for a non-reference copy initialization (8.5). The
3550  //          reference is then bound to the temporary. If T1 is
3551  //          reference-related to T2, cv1 must be the same
3552  //          cv-qualification as, or greater cv-qualification than,
3553  //          cv2; otherwise, the program is ill-formed.
3554  if (RefRelationship == Sema::Ref_Related) {
3555    // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3556    // we would be reference-compatible or reference-compatible with
3557    // added qualification. But that wasn't the case, so the reference
3558    // initialization fails.
3559    //
3560    // Note that we only want to check address spaces and cvr-qualifiers here.
3561    // ObjC GC and lifetime qualifiers aren't important.
3562    Qualifiers T1Quals = T1.getQualifiers();
3563    Qualifiers T2Quals = T2.getQualifiers();
3564    T1Quals.removeObjCGCAttr();
3565    T1Quals.removeObjCLifetime();
3566    T2Quals.removeObjCGCAttr();
3567    T2Quals.removeObjCLifetime();
3568    if (!T1Quals.compatiblyIncludes(T2Quals))
3569      return ICS;
3570  }
3571
3572  // If at least one of the types is a class type, the types are not
3573  // related, and we aren't allowed any user conversions, the
3574  // reference binding fails. This case is important for breaking
3575  // recursion, since TryImplicitConversion below will attempt to
3576  // create a temporary through the use of a copy constructor.
3577  if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3578      (T1->isRecordType() || T2->isRecordType()))
3579    return ICS;
3580
3581  // If T1 is reference-related to T2 and the reference is an rvalue
3582  // reference, the initializer expression shall not be an lvalue.
3583  if (RefRelationship >= Sema::Ref_Related &&
3584      isRValRef && Init->Classify(S.Context).isLValue())
3585    return ICS;
3586
3587  // C++ [over.ics.ref]p2:
3588  //   When a parameter of reference type is not bound directly to
3589  //   an argument expression, the conversion sequence is the one
3590  //   required to convert the argument expression to the
3591  //   underlying type of the reference according to
3592  //   13.3.3.1. Conceptually, this conversion sequence corresponds
3593  //   to copy-initializing a temporary of the underlying type with
3594  //   the argument expression. Any difference in top-level
3595  //   cv-qualification is subsumed by the initialization itself
3596  //   and does not constitute a conversion.
3597  ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3598                              /*AllowExplicit=*/false,
3599                              /*InOverloadResolution=*/false,
3600                              /*CStyle=*/false,
3601                              /*AllowObjCWritebackConversion=*/false);
3602
3603  // Of course, that's still a reference binding.
3604  if (ICS.isStandard()) {
3605    ICS.Standard.ReferenceBinding = true;
3606    ICS.Standard.IsLvalueReference = !isRValRef;
3607    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3608    ICS.Standard.BindsToRvalue = true;
3609    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3610    ICS.Standard.ObjCLifetimeConversionBinding = false;
3611  } else if (ICS.isUserDefined()) {
3612    ICS.UserDefined.After.ReferenceBinding = true;
3613    ICS.Standard.IsLvalueReference = !isRValRef;
3614    ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3615    ICS.Standard.BindsToRvalue = true;
3616    ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3617    ICS.Standard.ObjCLifetimeConversionBinding = false;
3618  }
3619
3620  return ICS;
3621}
3622
3623/// TryCopyInitialization - Try to copy-initialize a value of type
3624/// ToType from the expression From. Return the implicit conversion
3625/// sequence required to pass this argument, which may be a bad
3626/// conversion sequence (meaning that the argument cannot be passed to
3627/// a parameter of this type). If @p SuppressUserConversions, then we
3628/// do not permit any user-defined conversion sequences.
3629static ImplicitConversionSequence
3630TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3631                      bool SuppressUserConversions,
3632                      bool InOverloadResolution,
3633                      bool AllowObjCWritebackConversion) {
3634  if (ToType->isReferenceType())
3635    return TryReferenceInit(S, From, ToType,
3636                            /*FIXME:*/From->getLocStart(),
3637                            SuppressUserConversions,
3638                            /*AllowExplicit=*/false);
3639
3640  return TryImplicitConversion(S, From, ToType,
3641                               SuppressUserConversions,
3642                               /*AllowExplicit=*/false,
3643                               InOverloadResolution,
3644                               /*CStyle=*/false,
3645                               AllowObjCWritebackConversion);
3646}
3647
3648/// TryObjectArgumentInitialization - Try to initialize the object
3649/// parameter of the given member function (@c Method) from the
3650/// expression @p From.
3651static ImplicitConversionSequence
3652TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3653                                Expr::Classification FromClassification,
3654                                CXXMethodDecl *Method,
3655                                CXXRecordDecl *ActingContext) {
3656  QualType ClassType = S.Context.getTypeDeclType(ActingContext);
3657  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3658  //                 const volatile object.
3659  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3660    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3661  QualType ImplicitParamType =  S.Context.getCVRQualifiedType(ClassType, Quals);
3662
3663  // Set up the conversion sequence as a "bad" conversion, to allow us
3664  // to exit early.
3665  ImplicitConversionSequence ICS;
3666
3667  // We need to have an object of class type.
3668  QualType FromType = OrigFromType;
3669  if (const PointerType *PT = FromType->getAs<PointerType>()) {
3670    FromType = PT->getPointeeType();
3671
3672    // When we had a pointer, it's implicitly dereferenced, so we
3673    // better have an lvalue.
3674    assert(FromClassification.isLValue());
3675  }
3676
3677  assert(FromType->isRecordType());
3678
3679  // C++0x [over.match.funcs]p4:
3680  //   For non-static member functions, the type of the implicit object
3681  //   parameter is
3682  //
3683  //     - "lvalue reference to cv X" for functions declared without a
3684  //        ref-qualifier or with the & ref-qualifier
3685  //     - "rvalue reference to cv X" for functions declared with the &&
3686  //        ref-qualifier
3687  //
3688  // where X is the class of which the function is a member and cv is the
3689  // cv-qualification on the member function declaration.
3690  //
3691  // However, when finding an implicit conversion sequence for the argument, we
3692  // are not allowed to create temporaries or perform user-defined conversions
3693  // (C++ [over.match.funcs]p5). We perform a simplified version of
3694  // reference binding here, that allows class rvalues to bind to
3695  // non-constant references.
3696
3697  // First check the qualifiers.
3698  QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
3699  if (ImplicitParamType.getCVRQualifiers()
3700                                    != FromTypeCanon.getLocalCVRQualifiers() &&
3701      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
3702    ICS.setBad(BadConversionSequence::bad_qualifiers,
3703               OrigFromType, ImplicitParamType);
3704    return ICS;
3705  }
3706
3707  // Check that we have either the same type or a derived type. It
3708  // affects the conversion rank.
3709  QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
3710  ImplicitConversionKind SecondKind;
3711  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3712    SecondKind = ICK_Identity;
3713  } else if (S.IsDerivedFrom(FromType, ClassType))
3714    SecondKind = ICK_Derived_To_Base;
3715  else {
3716    ICS.setBad(BadConversionSequence::unrelated_class,
3717               FromType, ImplicitParamType);
3718    return ICS;
3719  }
3720
3721  // Check the ref-qualifier.
3722  switch (Method->getRefQualifier()) {
3723  case RQ_None:
3724    // Do nothing; we don't care about lvalueness or rvalueness.
3725    break;
3726
3727  case RQ_LValue:
3728    if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3729      // non-const lvalue reference cannot bind to an rvalue
3730      ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
3731                 ImplicitParamType);
3732      return ICS;
3733    }
3734    break;
3735
3736  case RQ_RValue:
3737    if (!FromClassification.isRValue()) {
3738      // rvalue reference cannot bind to an lvalue
3739      ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
3740                 ImplicitParamType);
3741      return ICS;
3742    }
3743    break;
3744  }
3745
3746  // Success. Mark this as a reference binding.
3747  ICS.setStandard();
3748  ICS.Standard.setAsIdentityConversion();
3749  ICS.Standard.Second = SecondKind;
3750  ICS.Standard.setFromType(FromType);
3751  ICS.Standard.setAllToTypes(ImplicitParamType);
3752  ICS.Standard.ReferenceBinding = true;
3753  ICS.Standard.DirectBinding = true;
3754  ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
3755  ICS.Standard.BindsToFunctionLvalue = false;
3756  ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3757  ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3758    = (Method->getRefQualifier() == RQ_None);
3759  return ICS;
3760}
3761
3762/// PerformObjectArgumentInitialization - Perform initialization of
3763/// the implicit object parameter for the given Method with the given
3764/// expression.
3765ExprResult
3766Sema::PerformObjectArgumentInitialization(Expr *From,
3767                                          NestedNameSpecifier *Qualifier,
3768                                          NamedDecl *FoundDecl,
3769                                          CXXMethodDecl *Method) {
3770  QualType FromRecordType, DestType;
3771  QualType ImplicitParamRecordType  =
3772    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
3773
3774  Expr::Classification FromClassification;
3775  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
3776    FromRecordType = PT->getPointeeType();
3777    DestType = Method->getThisType(Context);
3778    FromClassification = Expr::Classification::makeSimpleLValue();
3779  } else {
3780    FromRecordType = From->getType();
3781    DestType = ImplicitParamRecordType;
3782    FromClassification = From->Classify(Context);
3783  }
3784
3785  // Note that we always use the true parent context when performing
3786  // the actual argument initialization.
3787  ImplicitConversionSequence ICS
3788    = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3789                                      Method, Method->getParent());
3790  if (ICS.isBad()) {
3791    if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3792      Qualifiers FromQs = FromRecordType.getQualifiers();
3793      Qualifiers ToQs = DestType.getQualifiers();
3794      unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3795      if (CVR) {
3796        Diag(From->getSourceRange().getBegin(),
3797             diag::err_member_function_call_bad_cvr)
3798          << Method->getDeclName() << FromRecordType << (CVR - 1)
3799          << From->getSourceRange();
3800        Diag(Method->getLocation(), diag::note_previous_decl)
3801          << Method->getDeclName();
3802        return ExprError();
3803      }
3804    }
3805
3806    return Diag(From->getSourceRange().getBegin(),
3807                diag::err_implicit_object_parameter_init)
3808       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
3809  }
3810
3811  if (ICS.Standard.Second == ICK_Derived_To_Base) {
3812    ExprResult FromRes =
3813      PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3814    if (FromRes.isInvalid())
3815      return ExprError();
3816    From = FromRes.take();
3817  }
3818
3819  if (!Context.hasSameType(From->getType(), DestType))
3820    From = ImpCastExprToType(From, DestType, CK_NoOp,
3821                      From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3822  return Owned(From);
3823}
3824
3825/// TryContextuallyConvertToBool - Attempt to contextually convert the
3826/// expression From to bool (C++0x [conv]p3).
3827static ImplicitConversionSequence
3828TryContextuallyConvertToBool(Sema &S, Expr *From) {
3829  // FIXME: This is pretty broken.
3830  return TryImplicitConversion(S, From, S.Context.BoolTy,
3831                               // FIXME: Are these flags correct?
3832                               /*SuppressUserConversions=*/false,
3833                               /*AllowExplicit=*/true,
3834                               /*InOverloadResolution=*/false,
3835                               /*CStyle=*/false,
3836                               /*AllowObjCWritebackConversion=*/false);
3837}
3838
3839/// PerformContextuallyConvertToBool - Perform a contextual conversion
3840/// of the expression From to bool (C++0x [conv]p3).
3841ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
3842  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
3843  if (!ICS.isBad())
3844    return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
3845
3846  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
3847    return Diag(From->getSourceRange().getBegin(),
3848                diag::err_typecheck_bool_condition)
3849                  << From->getType() << From->getSourceRange();
3850  return ExprError();
3851}
3852
3853/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3854/// expression From to 'id'.
3855static ImplicitConversionSequence
3856TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3857  QualType Ty = S.Context.getObjCIdType();
3858  return TryImplicitConversion(S, From, Ty,
3859                               // FIXME: Are these flags correct?
3860                               /*SuppressUserConversions=*/false,
3861                               /*AllowExplicit=*/true,
3862                               /*InOverloadResolution=*/false,
3863                               /*CStyle=*/false,
3864                               /*AllowObjCWritebackConversion=*/false);
3865}
3866
3867/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3868/// of the expression From to 'id'.
3869ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
3870  QualType Ty = Context.getObjCIdType();
3871  ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
3872  if (!ICS.isBad())
3873    return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3874  return ExprError();
3875}
3876
3877/// \brief Attempt to convert the given expression to an integral or
3878/// enumeration type.
3879///
3880/// This routine will attempt to convert an expression of class type to an
3881/// integral or enumeration type, if that class type only has a single
3882/// conversion to an integral or enumeration type.
3883///
3884/// \param Loc The source location of the construct that requires the
3885/// conversion.
3886///
3887/// \param FromE The expression we're converting from.
3888///
3889/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3890/// have integral or enumeration type.
3891///
3892/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3893/// incomplete class type.
3894///
3895/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3896/// explicit conversion function (because no implicit conversion functions
3897/// were available). This is a recovery mode.
3898///
3899/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3900/// showing which conversion was picked.
3901///
3902/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3903/// conversion function that could convert to integral or enumeration type.
3904///
3905/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3906/// usable conversion function.
3907///
3908/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3909/// function, which may be an extension in this case.
3910///
3911/// \returns The expression, converted to an integral or enumeration type if
3912/// successful.
3913ExprResult
3914Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
3915                                         const PartialDiagnostic &NotIntDiag,
3916                                       const PartialDiagnostic &IncompleteDiag,
3917                                     const PartialDiagnostic &ExplicitConvDiag,
3918                                     const PartialDiagnostic &ExplicitConvNote,
3919                                         const PartialDiagnostic &AmbigDiag,
3920                                         const PartialDiagnostic &AmbigNote,
3921                                         const PartialDiagnostic &ConvDiag) {
3922  // We can't perform any more checking for type-dependent expressions.
3923  if (From->isTypeDependent())
3924    return Owned(From);
3925
3926  // If the expression already has integral or enumeration type, we're golden.
3927  QualType T = From->getType();
3928  if (T->isIntegralOrEnumerationType())
3929    return Owned(From);
3930
3931  // FIXME: Check for missing '()' if T is a function type?
3932
3933  // If we don't have a class type in C++, there's no way we can get an
3934  // expression of integral or enumeration type.
3935  const RecordType *RecordTy = T->getAs<RecordType>();
3936  if (!RecordTy || !getLangOptions().CPlusPlus) {
3937    Diag(Loc, NotIntDiag)
3938      << T << From->getSourceRange();
3939    return Owned(From);
3940  }
3941
3942  // We must have a complete class type.
3943  if (RequireCompleteType(Loc, T, IncompleteDiag))
3944    return Owned(From);
3945
3946  // Look for a conversion to an integral or enumeration type.
3947  UnresolvedSet<4> ViableConversions;
3948  UnresolvedSet<4> ExplicitConversions;
3949  const UnresolvedSetImpl *Conversions
3950    = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3951
3952  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3953                                   E = Conversions->end();
3954       I != E;
3955       ++I) {
3956    if (CXXConversionDecl *Conversion
3957          = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3958      if (Conversion->getConversionType().getNonReferenceType()
3959            ->isIntegralOrEnumerationType()) {
3960        if (Conversion->isExplicit())
3961          ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3962        else
3963          ViableConversions.addDecl(I.getDecl(), I.getAccess());
3964      }
3965  }
3966
3967  switch (ViableConversions.size()) {
3968  case 0:
3969    if (ExplicitConversions.size() == 1) {
3970      DeclAccessPair Found = ExplicitConversions[0];
3971      CXXConversionDecl *Conversion
3972        = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3973
3974      // The user probably meant to invoke the given explicit
3975      // conversion; use it.
3976      QualType ConvTy
3977        = Conversion->getConversionType().getNonReferenceType();
3978      std::string TypeStr;
3979      ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3980
3981      Diag(Loc, ExplicitConvDiag)
3982        << T << ConvTy
3983        << FixItHint::CreateInsertion(From->getLocStart(),
3984                                      "static_cast<" + TypeStr + ">(")
3985        << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3986                                      ")");
3987      Diag(Conversion->getLocation(), ExplicitConvNote)
3988        << ConvTy->isEnumeralType() << ConvTy;
3989
3990      // If we aren't in a SFINAE context, build a call to the
3991      // explicit conversion function.
3992      if (isSFINAEContext())
3993        return ExprError();
3994
3995      CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3996      ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3997      if (Result.isInvalid())
3998        return ExprError();
3999
4000      From = Result.get();
4001    }
4002
4003    // We'll complain below about a non-integral condition type.
4004    break;
4005
4006  case 1: {
4007    // Apply this conversion.
4008    DeclAccessPair Found = ViableConversions[0];
4009    CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
4010
4011    CXXConversionDecl *Conversion
4012      = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4013    QualType ConvTy
4014      = Conversion->getConversionType().getNonReferenceType();
4015    if (ConvDiag.getDiagID()) {
4016      if (isSFINAEContext())
4017        return ExprError();
4018
4019      Diag(Loc, ConvDiag)
4020        << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4021    }
4022
4023    ExprResult Result = BuildCXXMemberCallExpr(From, Found,
4024                          cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
4025    if (Result.isInvalid())
4026      return ExprError();
4027
4028    From = Result.get();
4029    break;
4030  }
4031
4032  default:
4033    Diag(Loc, AmbigDiag)
4034      << T << From->getSourceRange();
4035    for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4036      CXXConversionDecl *Conv
4037        = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4038      QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4039      Diag(Conv->getLocation(), AmbigNote)
4040        << ConvTy->isEnumeralType() << ConvTy;
4041    }
4042    return Owned(From);
4043  }
4044
4045  if (!From->getType()->isIntegralOrEnumerationType())
4046    Diag(Loc, NotIntDiag)
4047      << From->getType() << From->getSourceRange();
4048
4049  return Owned(From);
4050}
4051
4052/// AddOverloadCandidate - Adds the given function to the set of
4053/// candidate functions, using the given function call arguments.  If
4054/// @p SuppressUserConversions, then don't allow user-defined
4055/// conversions via constructors or conversion operators.
4056///
4057/// \para PartialOverloading true if we are performing "partial" overloading
4058/// based on an incomplete set of function arguments. This feature is used by
4059/// code completion.
4060void
4061Sema::AddOverloadCandidate(FunctionDecl *Function,
4062                           DeclAccessPair FoundDecl,
4063                           Expr **Args, unsigned NumArgs,
4064                           OverloadCandidateSet& CandidateSet,
4065                           bool SuppressUserConversions,
4066                           bool PartialOverloading) {
4067  const FunctionProtoType* Proto
4068    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
4069  assert(Proto && "Functions without a prototype cannot be overloaded");
4070  assert(!Function->getDescribedFunctionTemplate() &&
4071         "Use AddTemplateOverloadCandidate for function templates");
4072
4073  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
4074    if (!isa<CXXConstructorDecl>(Method)) {
4075      // If we get here, it's because we're calling a member function
4076      // that is named without a member access expression (e.g.,
4077      // "this->f") that was either written explicitly or created
4078      // implicitly. This can happen with a qualified call to a member
4079      // function, e.g., X::f(). We use an empty type for the implied
4080      // object argument (C++ [over.call.func]p3), and the acting context
4081      // is irrelevant.
4082      AddMethodCandidate(Method, FoundDecl, Method->getParent(),
4083                         QualType(), Expr::Classification::makeSimpleLValue(),
4084                         Args, NumArgs, CandidateSet,
4085                         SuppressUserConversions);
4086      return;
4087    }
4088    // We treat a constructor like a non-member function, since its object
4089    // argument doesn't participate in overload resolution.
4090  }
4091
4092  if (!CandidateSet.isNewCandidate(Function))
4093    return;
4094
4095  // Overload resolution is always an unevaluated context.
4096  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4097
4098  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4099    // C++ [class.copy]p3:
4100    //   A member function template is never instantiated to perform the copy
4101    //   of a class object to an object of its class type.
4102    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
4103    if (NumArgs == 1 &&
4104        Constructor->isSpecializationCopyingObject() &&
4105        (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4106         IsDerivedFrom(Args[0]->getType(), ClassType)))
4107      return;
4108  }
4109
4110  // Add this candidate
4111  CandidateSet.push_back(OverloadCandidate());
4112  OverloadCandidate& Candidate = CandidateSet.back();
4113  Candidate.FoundDecl = FoundDecl;
4114  Candidate.Function = Function;
4115  Candidate.Viable = true;
4116  Candidate.IsSurrogate = false;
4117  Candidate.IgnoreObjectArgument = false;
4118  Candidate.ExplicitCallArguments = NumArgs;
4119
4120  unsigned NumArgsInProto = Proto->getNumArgs();
4121
4122  // (C++ 13.3.2p2): A candidate function having fewer than m
4123  // parameters is viable only if it has an ellipsis in its parameter
4124  // list (8.3.5).
4125  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
4126      !Proto->isVariadic()) {
4127    Candidate.Viable = false;
4128    Candidate.FailureKind = ovl_fail_too_many_arguments;
4129    return;
4130  }
4131
4132  // (C++ 13.3.2p2): A candidate function having more than m parameters
4133  // is viable only if the (m+1)st parameter has a default argument
4134  // (8.3.6). For the purposes of overload resolution, the
4135  // parameter list is truncated on the right, so that there are
4136  // exactly m parameters.
4137  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
4138  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
4139    // Not enough arguments.
4140    Candidate.Viable = false;
4141    Candidate.FailureKind = ovl_fail_too_few_arguments;
4142    return;
4143  }
4144
4145  // Determine the implicit conversion sequences for each of the
4146  // arguments.
4147  Candidate.Conversions.resize(NumArgs);
4148  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4149    if (ArgIdx < NumArgsInProto) {
4150      // (C++ 13.3.2p3): for F to be a viable function, there shall
4151      // exist for each argument an implicit conversion sequence
4152      // (13.3.3.1) that converts that argument to the corresponding
4153      // parameter of F.
4154      QualType ParamType = Proto->getArgType(ArgIdx);
4155      Candidate.Conversions[ArgIdx]
4156        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4157                                SuppressUserConversions,
4158                                /*InOverloadResolution=*/true,
4159                                /*AllowObjCWritebackConversion=*/
4160                                  getLangOptions().ObjCAutoRefCount);
4161      if (Candidate.Conversions[ArgIdx].isBad()) {
4162        Candidate.Viable = false;
4163        Candidate.FailureKind = ovl_fail_bad_conversion;
4164        break;
4165      }
4166    } else {
4167      // (C++ 13.3.2p2): For the purposes of overload resolution, any
4168      // argument for which there is no corresponding parameter is
4169      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4170      Candidate.Conversions[ArgIdx].setEllipsis();
4171    }
4172  }
4173}
4174
4175/// \brief Add all of the function declarations in the given function set to
4176/// the overload canddiate set.
4177void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
4178                                 Expr **Args, unsigned NumArgs,
4179                                 OverloadCandidateSet& CandidateSet,
4180                                 bool SuppressUserConversions) {
4181  for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
4182    NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4183    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4184      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
4185        AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
4186                           cast<CXXMethodDecl>(FD)->getParent(),
4187                           Args[0]->getType(), Args[0]->Classify(Context),
4188                           Args + 1, NumArgs - 1,
4189                           CandidateSet, SuppressUserConversions);
4190      else
4191        AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
4192                             SuppressUserConversions);
4193    } else {
4194      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
4195      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4196          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
4197        AddMethodTemplateCandidate(FunTmpl, F.getPair(),
4198                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
4199                                   /*FIXME: explicit args */ 0,
4200                                   Args[0]->getType(),
4201                                   Args[0]->Classify(Context),
4202                                   Args + 1, NumArgs - 1,
4203                                   CandidateSet,
4204                                   SuppressUserConversions);
4205      else
4206        AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
4207                                     /*FIXME: explicit args */ 0,
4208                                     Args, NumArgs, CandidateSet,
4209                                     SuppressUserConversions);
4210    }
4211  }
4212}
4213
4214/// AddMethodCandidate - Adds a named decl (which is some kind of
4215/// method) as a method candidate to the given overload set.
4216void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
4217                              QualType ObjectType,
4218                              Expr::Classification ObjectClassification,
4219                              Expr **Args, unsigned NumArgs,
4220                              OverloadCandidateSet& CandidateSet,
4221                              bool SuppressUserConversions) {
4222  NamedDecl *Decl = FoundDecl.getDecl();
4223  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
4224
4225  if (isa<UsingShadowDecl>(Decl))
4226    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
4227
4228  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4229    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4230           "Expected a member function template");
4231    AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4232                               /*ExplicitArgs*/ 0,
4233                               ObjectType, ObjectClassification, Args, NumArgs,
4234                               CandidateSet,
4235                               SuppressUserConversions);
4236  } else {
4237    AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
4238                       ObjectType, ObjectClassification, Args, NumArgs,
4239                       CandidateSet, SuppressUserConversions);
4240  }
4241}
4242
4243/// AddMethodCandidate - Adds the given C++ member function to the set
4244/// of candidate functions, using the given function call arguments
4245/// and the object argument (@c Object). For example, in a call
4246/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4247/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4248/// allow user-defined conversions via constructors or conversion
4249/// operators.
4250void
4251Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
4252                         CXXRecordDecl *ActingContext, QualType ObjectType,
4253                         Expr::Classification ObjectClassification,
4254                         Expr **Args, unsigned NumArgs,
4255                         OverloadCandidateSet& CandidateSet,
4256                         bool SuppressUserConversions) {
4257  const FunctionProtoType* Proto
4258    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
4259  assert(Proto && "Methods without a prototype cannot be overloaded");
4260  assert(!isa<CXXConstructorDecl>(Method) &&
4261         "Use AddOverloadCandidate for constructors");
4262
4263  if (!CandidateSet.isNewCandidate(Method))
4264    return;
4265
4266  // Overload resolution is always an unevaluated context.
4267  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4268
4269  // Add this candidate
4270  CandidateSet.push_back(OverloadCandidate());
4271  OverloadCandidate& Candidate = CandidateSet.back();
4272  Candidate.FoundDecl = FoundDecl;
4273  Candidate.Function = Method;
4274  Candidate.IsSurrogate = false;
4275  Candidate.IgnoreObjectArgument = false;
4276  Candidate.ExplicitCallArguments = NumArgs;
4277
4278  unsigned NumArgsInProto = Proto->getNumArgs();
4279
4280  // (C++ 13.3.2p2): A candidate function having fewer than m
4281  // parameters is viable only if it has an ellipsis in its parameter
4282  // list (8.3.5).
4283  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4284    Candidate.Viable = false;
4285    Candidate.FailureKind = ovl_fail_too_many_arguments;
4286    return;
4287  }
4288
4289  // (C++ 13.3.2p2): A candidate function having more than m parameters
4290  // is viable only if the (m+1)st parameter has a default argument
4291  // (8.3.6). For the purposes of overload resolution, the
4292  // parameter list is truncated on the right, so that there are
4293  // exactly m parameters.
4294  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4295  if (NumArgs < MinRequiredArgs) {
4296    // Not enough arguments.
4297    Candidate.Viable = false;
4298    Candidate.FailureKind = ovl_fail_too_few_arguments;
4299    return;
4300  }
4301
4302  Candidate.Viable = true;
4303  Candidate.Conversions.resize(NumArgs + 1);
4304
4305  if (Method->isStatic() || ObjectType.isNull())
4306    // The implicit object argument is ignored.
4307    Candidate.IgnoreObjectArgument = true;
4308  else {
4309    // Determine the implicit conversion sequence for the object
4310    // parameter.
4311    Candidate.Conversions[0]
4312      = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4313                                        Method, ActingContext);
4314    if (Candidate.Conversions[0].isBad()) {
4315      Candidate.Viable = false;
4316      Candidate.FailureKind = ovl_fail_bad_conversion;
4317      return;
4318    }
4319  }
4320
4321  // Determine the implicit conversion sequences for each of the
4322  // arguments.
4323  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4324    if (ArgIdx < NumArgsInProto) {
4325      // (C++ 13.3.2p3): for F to be a viable function, there shall
4326      // exist for each argument an implicit conversion sequence
4327      // (13.3.3.1) that converts that argument to the corresponding
4328      // parameter of F.
4329      QualType ParamType = Proto->getArgType(ArgIdx);
4330      Candidate.Conversions[ArgIdx + 1]
4331        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4332                                SuppressUserConversions,
4333                                /*InOverloadResolution=*/true,
4334                                /*AllowObjCWritebackConversion=*/
4335                                  getLangOptions().ObjCAutoRefCount);
4336      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4337        Candidate.Viable = false;
4338        Candidate.FailureKind = ovl_fail_bad_conversion;
4339        break;
4340      }
4341    } else {
4342      // (C++ 13.3.2p2): For the purposes of overload resolution, any
4343      // argument for which there is no corresponding parameter is
4344      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4345      Candidate.Conversions[ArgIdx + 1].setEllipsis();
4346    }
4347  }
4348}
4349
4350/// \brief Add a C++ member function template as a candidate to the candidate
4351/// set, using template argument deduction to produce an appropriate member
4352/// function template specialization.
4353void
4354Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4355                                 DeclAccessPair FoundDecl,
4356                                 CXXRecordDecl *ActingContext,
4357                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
4358                                 QualType ObjectType,
4359                                 Expr::Classification ObjectClassification,
4360                                 Expr **Args, unsigned NumArgs,
4361                                 OverloadCandidateSet& CandidateSet,
4362                                 bool SuppressUserConversions) {
4363  if (!CandidateSet.isNewCandidate(MethodTmpl))
4364    return;
4365
4366  // C++ [over.match.funcs]p7:
4367  //   In each case where a candidate is a function template, candidate
4368  //   function template specializations are generated using template argument
4369  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
4370  //   candidate functions in the usual way.113) A given name can refer to one
4371  //   or more function templates and also to a set of overloaded non-template
4372  //   functions. In such a case, the candidate functions generated from each
4373  //   function template are combined with the set of non-template candidate
4374  //   functions.
4375  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4376  FunctionDecl *Specialization = 0;
4377  if (TemplateDeductionResult Result
4378      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
4379                                Args, NumArgs, Specialization, Info)) {
4380    CandidateSet.push_back(OverloadCandidate());
4381    OverloadCandidate &Candidate = CandidateSet.back();
4382    Candidate.FoundDecl = FoundDecl;
4383    Candidate.Function = MethodTmpl->getTemplatedDecl();
4384    Candidate.Viable = false;
4385    Candidate.FailureKind = ovl_fail_bad_deduction;
4386    Candidate.IsSurrogate = false;
4387    Candidate.IgnoreObjectArgument = false;
4388    Candidate.ExplicitCallArguments = NumArgs;
4389    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4390                                                          Info);
4391    return;
4392  }
4393
4394  // Add the function template specialization produced by template argument
4395  // deduction as a candidate.
4396  assert(Specialization && "Missing member function template specialization?");
4397  assert(isa<CXXMethodDecl>(Specialization) &&
4398         "Specialization is not a member function?");
4399  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
4400                     ActingContext, ObjectType, ObjectClassification,
4401                     Args, NumArgs, CandidateSet, SuppressUserConversions);
4402}
4403
4404/// \brief Add a C++ function template specialization as a candidate
4405/// in the candidate set, using template argument deduction to produce
4406/// an appropriate function template specialization.
4407void
4408Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
4409                                   DeclAccessPair FoundDecl,
4410                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
4411                                   Expr **Args, unsigned NumArgs,
4412                                   OverloadCandidateSet& CandidateSet,
4413                                   bool SuppressUserConversions) {
4414  if (!CandidateSet.isNewCandidate(FunctionTemplate))
4415    return;
4416
4417  // C++ [over.match.funcs]p7:
4418  //   In each case where a candidate is a function template, candidate
4419  //   function template specializations are generated using template argument
4420  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
4421  //   candidate functions in the usual way.113) A given name can refer to one
4422  //   or more function templates and also to a set of overloaded non-template
4423  //   functions. In such a case, the candidate functions generated from each
4424  //   function template are combined with the set of non-template candidate
4425  //   functions.
4426  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4427  FunctionDecl *Specialization = 0;
4428  if (TemplateDeductionResult Result
4429        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4430                                  Args, NumArgs, Specialization, Info)) {
4431    CandidateSet.push_back(OverloadCandidate());
4432    OverloadCandidate &Candidate = CandidateSet.back();
4433    Candidate.FoundDecl = FoundDecl;
4434    Candidate.Function = FunctionTemplate->getTemplatedDecl();
4435    Candidate.Viable = false;
4436    Candidate.FailureKind = ovl_fail_bad_deduction;
4437    Candidate.IsSurrogate = false;
4438    Candidate.IgnoreObjectArgument = false;
4439    Candidate.ExplicitCallArguments = NumArgs;
4440    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4441                                                          Info);
4442    return;
4443  }
4444
4445  // Add the function template specialization produced by template argument
4446  // deduction as a candidate.
4447  assert(Specialization && "Missing function template specialization?");
4448  AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
4449                       SuppressUserConversions);
4450}
4451
4452/// AddConversionCandidate - Add a C++ conversion function as a
4453/// candidate in the candidate set (C++ [over.match.conv],
4454/// C++ [over.match.copy]). From is the expression we're converting from,
4455/// and ToType is the type that we're eventually trying to convert to
4456/// (which may or may not be the same type as the type that the
4457/// conversion function produces).
4458void
4459Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
4460                             DeclAccessPair FoundDecl,
4461                             CXXRecordDecl *ActingContext,
4462                             Expr *From, QualType ToType,
4463                             OverloadCandidateSet& CandidateSet) {
4464  assert(!Conversion->getDescribedFunctionTemplate() &&
4465         "Conversion function templates use AddTemplateConversionCandidate");
4466  QualType ConvType = Conversion->getConversionType().getNonReferenceType();
4467  if (!CandidateSet.isNewCandidate(Conversion))
4468    return;
4469
4470  // Overload resolution is always an unevaluated context.
4471  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4472
4473  // Add this candidate
4474  CandidateSet.push_back(OverloadCandidate());
4475  OverloadCandidate& Candidate = CandidateSet.back();
4476  Candidate.FoundDecl = FoundDecl;
4477  Candidate.Function = Conversion;
4478  Candidate.IsSurrogate = false;
4479  Candidate.IgnoreObjectArgument = false;
4480  Candidate.FinalConversion.setAsIdentityConversion();
4481  Candidate.FinalConversion.setFromType(ConvType);
4482  Candidate.FinalConversion.setAllToTypes(ToType);
4483  Candidate.Viable = true;
4484  Candidate.Conversions.resize(1);
4485  Candidate.ExplicitCallArguments = 1;
4486
4487  // C++ [over.match.funcs]p4:
4488  //   For conversion functions, the function is considered to be a member of
4489  //   the class of the implicit implied object argument for the purpose of
4490  //   defining the type of the implicit object parameter.
4491  //
4492  // Determine the implicit conversion sequence for the implicit
4493  // object parameter.
4494  QualType ImplicitParamType = From->getType();
4495  if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4496    ImplicitParamType = FromPtrType->getPointeeType();
4497  CXXRecordDecl *ConversionContext
4498    = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
4499
4500  Candidate.Conversions[0]
4501    = TryObjectArgumentInitialization(*this, From->getType(),
4502                                      From->Classify(Context),
4503                                      Conversion, ConversionContext);
4504
4505  if (Candidate.Conversions[0].isBad()) {
4506    Candidate.Viable = false;
4507    Candidate.FailureKind = ovl_fail_bad_conversion;
4508    return;
4509  }
4510
4511  // We won't go through a user-define type conversion function to convert a
4512  // derived to base as such conversions are given Conversion Rank. They only
4513  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4514  QualType FromCanon
4515    = Context.getCanonicalType(From->getType().getUnqualifiedType());
4516  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4517  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4518    Candidate.Viable = false;
4519    Candidate.FailureKind = ovl_fail_trivial_conversion;
4520    return;
4521  }
4522
4523  // To determine what the conversion from the result of calling the
4524  // conversion function to the type we're eventually trying to
4525  // convert to (ToType), we need to synthesize a call to the
4526  // conversion function and attempt copy initialization from it. This
4527  // makes sure that we get the right semantics with respect to
4528  // lvalues/rvalues and the type. Fortunately, we can allocate this
4529  // call on the stack and we don't need its arguments to be
4530  // well-formed.
4531  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
4532                            VK_LValue, From->getLocStart());
4533  ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4534                                Context.getPointerType(Conversion->getType()),
4535                                CK_FunctionToPointerDecay,
4536                                &ConversionRef, VK_RValue);
4537
4538  QualType CallResultType
4539    = Conversion->getConversionType().getNonLValueExprType(Context);
4540  if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4541    Candidate.Viable = false;
4542    Candidate.FailureKind = ovl_fail_bad_final_conversion;
4543    return;
4544  }
4545
4546  ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4547
4548  // Note that it is safe to allocate CallExpr on the stack here because
4549  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4550  // allocator).
4551  CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
4552                From->getLocStart());
4553  ImplicitConversionSequence ICS =
4554    TryCopyInitialization(*this, &Call, ToType,
4555                          /*SuppressUserConversions=*/true,
4556                          /*InOverloadResolution=*/false,
4557                          /*AllowObjCWritebackConversion=*/false);
4558
4559  switch (ICS.getKind()) {
4560  case ImplicitConversionSequence::StandardConversion:
4561    Candidate.FinalConversion = ICS.Standard;
4562
4563    // C++ [over.ics.user]p3:
4564    //   If the user-defined conversion is specified by a specialization of a
4565    //   conversion function template, the second standard conversion sequence
4566    //   shall have exact match rank.
4567    if (Conversion->getPrimaryTemplate() &&
4568        GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4569      Candidate.Viable = false;
4570      Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4571    }
4572
4573    // C++0x [dcl.init.ref]p5:
4574    //    In the second case, if the reference is an rvalue reference and
4575    //    the second standard conversion sequence of the user-defined
4576    //    conversion sequence includes an lvalue-to-rvalue conversion, the
4577    //    program is ill-formed.
4578    if (ToType->isRValueReferenceType() &&
4579        ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4580      Candidate.Viable = false;
4581      Candidate.FailureKind = ovl_fail_bad_final_conversion;
4582    }
4583    break;
4584
4585  case ImplicitConversionSequence::BadConversion:
4586    Candidate.Viable = false;
4587    Candidate.FailureKind = ovl_fail_bad_final_conversion;
4588    break;
4589
4590  default:
4591    assert(false &&
4592           "Can only end up with a standard conversion sequence or failure");
4593  }
4594}
4595
4596/// \brief Adds a conversion function template specialization
4597/// candidate to the overload set, using template argument deduction
4598/// to deduce the template arguments of the conversion function
4599/// template from the type that we are converting to (C++
4600/// [temp.deduct.conv]).
4601void
4602Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
4603                                     DeclAccessPair FoundDecl,
4604                                     CXXRecordDecl *ActingDC,
4605                                     Expr *From, QualType ToType,
4606                                     OverloadCandidateSet &CandidateSet) {
4607  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4608         "Only conversion function templates permitted here");
4609
4610  if (!CandidateSet.isNewCandidate(FunctionTemplate))
4611    return;
4612
4613  TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4614  CXXConversionDecl *Specialization = 0;
4615  if (TemplateDeductionResult Result
4616        = DeduceTemplateArguments(FunctionTemplate, ToType,
4617                                  Specialization, Info)) {
4618    CandidateSet.push_back(OverloadCandidate());
4619    OverloadCandidate &Candidate = CandidateSet.back();
4620    Candidate.FoundDecl = FoundDecl;
4621    Candidate.Function = FunctionTemplate->getTemplatedDecl();
4622    Candidate.Viable = false;
4623    Candidate.FailureKind = ovl_fail_bad_deduction;
4624    Candidate.IsSurrogate = false;
4625    Candidate.IgnoreObjectArgument = false;
4626    Candidate.ExplicitCallArguments = 1;
4627    Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4628                                                          Info);
4629    return;
4630  }
4631
4632  // Add the conversion function template specialization produced by
4633  // template argument deduction as a candidate.
4634  assert(Specialization && "Missing function template specialization?");
4635  AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
4636                         CandidateSet);
4637}
4638
4639/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4640/// converts the given @c Object to a function pointer via the
4641/// conversion function @c Conversion, and then attempts to call it
4642/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4643/// the type of function that we'll eventually be calling.
4644void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
4645                                 DeclAccessPair FoundDecl,
4646                                 CXXRecordDecl *ActingContext,
4647                                 const FunctionProtoType *Proto,
4648                                 Expr *Object,
4649                                 Expr **Args, unsigned NumArgs,
4650                                 OverloadCandidateSet& CandidateSet) {
4651  if (!CandidateSet.isNewCandidate(Conversion))
4652    return;
4653
4654  // Overload resolution is always an unevaluated context.
4655  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4656
4657  CandidateSet.push_back(OverloadCandidate());
4658  OverloadCandidate& Candidate = CandidateSet.back();
4659  Candidate.FoundDecl = FoundDecl;
4660  Candidate.Function = 0;
4661  Candidate.Surrogate = Conversion;
4662  Candidate.Viable = true;
4663  Candidate.IsSurrogate = true;
4664  Candidate.IgnoreObjectArgument = false;
4665  Candidate.Conversions.resize(NumArgs + 1);
4666  Candidate.ExplicitCallArguments = NumArgs;
4667
4668  // Determine the implicit conversion sequence for the implicit
4669  // object parameter.
4670  ImplicitConversionSequence ObjectInit
4671    = TryObjectArgumentInitialization(*this, Object->getType(),
4672                                      Object->Classify(Context),
4673                                      Conversion, ActingContext);
4674  if (ObjectInit.isBad()) {
4675    Candidate.Viable = false;
4676    Candidate.FailureKind = ovl_fail_bad_conversion;
4677    Candidate.Conversions[0] = ObjectInit;
4678    return;
4679  }
4680
4681  // The first conversion is actually a user-defined conversion whose
4682  // first conversion is ObjectInit's standard conversion (which is
4683  // effectively a reference binding). Record it as such.
4684  Candidate.Conversions[0].setUserDefined();
4685  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
4686  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
4687  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
4688  Candidate.Conversions[0].UserDefined.FoundConversionFunction
4689    = FoundDecl.getDecl();
4690  Candidate.Conversions[0].UserDefined.After
4691    = Candidate.Conversions[0].UserDefined.Before;
4692  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4693
4694  // Find the
4695  unsigned NumArgsInProto = Proto->getNumArgs();
4696
4697  // (C++ 13.3.2p2): A candidate function having fewer than m
4698  // parameters is viable only if it has an ellipsis in its parameter
4699  // list (8.3.5).
4700  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4701    Candidate.Viable = false;
4702    Candidate.FailureKind = ovl_fail_too_many_arguments;
4703    return;
4704  }
4705
4706  // Function types don't have any default arguments, so just check if
4707  // we have enough arguments.
4708  if (NumArgs < NumArgsInProto) {
4709    // Not enough arguments.
4710    Candidate.Viable = false;
4711    Candidate.FailureKind = ovl_fail_too_few_arguments;
4712    return;
4713  }
4714
4715  // Determine the implicit conversion sequences for each of the
4716  // arguments.
4717  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4718    if (ArgIdx < NumArgsInProto) {
4719      // (C++ 13.3.2p3): for F to be a viable function, there shall
4720      // exist for each argument an implicit conversion sequence
4721      // (13.3.3.1) that converts that argument to the corresponding
4722      // parameter of F.
4723      QualType ParamType = Proto->getArgType(ArgIdx);
4724      Candidate.Conversions[ArgIdx + 1]
4725        = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4726                                /*SuppressUserConversions=*/false,
4727                                /*InOverloadResolution=*/false,
4728                                /*AllowObjCWritebackConversion=*/
4729                                  getLangOptions().ObjCAutoRefCount);
4730      if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4731        Candidate.Viable = false;
4732        Candidate.FailureKind = ovl_fail_bad_conversion;
4733        break;
4734      }
4735    } else {
4736      // (C++ 13.3.2p2): For the purposes of overload resolution, any
4737      // argument for which there is no corresponding parameter is
4738      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4739      Candidate.Conversions[ArgIdx + 1].setEllipsis();
4740    }
4741  }
4742}
4743
4744/// \brief Add overload candidates for overloaded operators that are
4745/// member functions.
4746///
4747/// Add the overloaded operator candidates that are member functions
4748/// for the operator Op that was used in an operator expression such
4749/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4750/// CandidateSet will store the added overload candidates. (C++
4751/// [over.match.oper]).
4752void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4753                                       SourceLocation OpLoc,
4754                                       Expr **Args, unsigned NumArgs,
4755                                       OverloadCandidateSet& CandidateSet,
4756                                       SourceRange OpRange) {
4757  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4758
4759  // C++ [over.match.oper]p3:
4760  //   For a unary operator @ with an operand of a type whose
4761  //   cv-unqualified version is T1, and for a binary operator @ with
4762  //   a left operand of a type whose cv-unqualified version is T1 and
4763  //   a right operand of a type whose cv-unqualified version is T2,
4764  //   three sets of candidate functions, designated member
4765  //   candidates, non-member candidates and built-in candidates, are
4766  //   constructed as follows:
4767  QualType T1 = Args[0]->getType();
4768
4769  //     -- If T1 is a class type, the set of member candidates is the
4770  //        result of the qualified lookup of T1::operator@
4771  //        (13.3.1.1.1); otherwise, the set of member candidates is
4772  //        empty.
4773  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
4774    // Complete the type if it can be completed. Otherwise, we're done.
4775    if (RequireCompleteType(OpLoc, T1, PDiag()))
4776      return;
4777
4778    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4779    LookupQualifiedName(Operators, T1Rec->getDecl());
4780    Operators.suppressDiagnostics();
4781
4782    for (LookupResult::iterator Oper = Operators.begin(),
4783                             OperEnd = Operators.end();
4784         Oper != OperEnd;
4785         ++Oper)
4786      AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
4787                         Args[0]->Classify(Context), Args + 1, NumArgs - 1,
4788                         CandidateSet,
4789                         /* SuppressUserConversions = */ false);
4790  }
4791}
4792
4793/// AddBuiltinCandidate - Add a candidate for a built-in
4794/// operator. ResultTy and ParamTys are the result and parameter types
4795/// of the built-in candidate, respectively. Args and NumArgs are the
4796/// arguments being passed to the candidate. IsAssignmentOperator
4797/// should be true when this built-in candidate is an assignment
4798/// operator. NumContextualBoolArguments is the number of arguments
4799/// (at the beginning of the argument list) that will be contextually
4800/// converted to bool.
4801void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
4802                               Expr **Args, unsigned NumArgs,
4803                               OverloadCandidateSet& CandidateSet,
4804                               bool IsAssignmentOperator,
4805                               unsigned NumContextualBoolArguments) {
4806  // Overload resolution is always an unevaluated context.
4807  EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4808
4809  // Add this candidate
4810  CandidateSet.push_back(OverloadCandidate());
4811  OverloadCandidate& Candidate = CandidateSet.back();
4812  Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
4813  Candidate.Function = 0;
4814  Candidate.IsSurrogate = false;
4815  Candidate.IgnoreObjectArgument = false;
4816  Candidate.BuiltinTypes.ResultTy = ResultTy;
4817  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4818    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4819
4820  // Determine the implicit conversion sequences for each of the
4821  // arguments.
4822  Candidate.Viable = true;
4823  Candidate.Conversions.resize(NumArgs);
4824  Candidate.ExplicitCallArguments = NumArgs;
4825  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4826    // C++ [over.match.oper]p4:
4827    //   For the built-in assignment operators, conversions of the
4828    //   left operand are restricted as follows:
4829    //     -- no temporaries are introduced to hold the left operand, and
4830    //     -- no user-defined conversions are applied to the left
4831    //        operand to achieve a type match with the left-most
4832    //        parameter of a built-in candidate.
4833    //
4834    // We block these conversions by turning off user-defined
4835    // conversions, since that is the only way that initialization of
4836    // a reference to a non-class type can occur from something that
4837    // is not of the same type.
4838    if (ArgIdx < NumContextualBoolArguments) {
4839      assert(ParamTys[ArgIdx] == Context.BoolTy &&
4840             "Contextual conversion to bool requires bool type");
4841      Candidate.Conversions[ArgIdx]
4842        = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
4843    } else {
4844      Candidate.Conversions[ArgIdx]
4845        = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
4846                                ArgIdx == 0 && IsAssignmentOperator,
4847                                /*InOverloadResolution=*/false,
4848                                /*AllowObjCWritebackConversion=*/
4849                                  getLangOptions().ObjCAutoRefCount);
4850    }
4851    if (Candidate.Conversions[ArgIdx].isBad()) {
4852      Candidate.Viable = false;
4853      Candidate.FailureKind = ovl_fail_bad_conversion;
4854      break;
4855    }
4856  }
4857}
4858
4859/// BuiltinCandidateTypeSet - A set of types that will be used for the
4860/// candidate operator functions for built-in operators (C++
4861/// [over.built]). The types are separated into pointer types and
4862/// enumeration types.
4863class BuiltinCandidateTypeSet  {
4864  /// TypeSet - A set of types.
4865  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
4866
4867  /// PointerTypes - The set of pointer types that will be used in the
4868  /// built-in candidates.
4869  TypeSet PointerTypes;
4870
4871  /// MemberPointerTypes - The set of member pointer types that will be
4872  /// used in the built-in candidates.
4873  TypeSet MemberPointerTypes;
4874
4875  /// EnumerationTypes - The set of enumeration types that will be
4876  /// used in the built-in candidates.
4877  TypeSet EnumerationTypes;
4878
4879  /// \brief The set of vector types that will be used in the built-in
4880  /// candidates.
4881  TypeSet VectorTypes;
4882
4883  /// \brief A flag indicating non-record types are viable candidates
4884  bool HasNonRecordTypes;
4885
4886  /// \brief A flag indicating whether either arithmetic or enumeration types
4887  /// were present in the candidate set.
4888  bool HasArithmeticOrEnumeralTypes;
4889
4890  /// \brief A flag indicating whether the nullptr type was present in the
4891  /// candidate set.
4892  bool HasNullPtrType;
4893
4894  /// Sema - The semantic analysis instance where we are building the
4895  /// candidate type set.
4896  Sema &SemaRef;
4897
4898  /// Context - The AST context in which we will build the type sets.
4899  ASTContext &Context;
4900
4901  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4902                                               const Qualifiers &VisibleQuals);
4903  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
4904
4905public:
4906  /// iterator - Iterates through the types that are part of the set.
4907  typedef TypeSet::iterator iterator;
4908
4909  BuiltinCandidateTypeSet(Sema &SemaRef)
4910    : HasNonRecordTypes(false),
4911      HasArithmeticOrEnumeralTypes(false),
4912      HasNullPtrType(false),
4913      SemaRef(SemaRef),
4914      Context(SemaRef.Context) { }
4915
4916  void AddTypesConvertedFrom(QualType Ty,
4917                             SourceLocation Loc,
4918                             bool AllowUserConversions,
4919                             bool AllowExplicitConversions,
4920                             const Qualifiers &VisibleTypeConversionsQuals);
4921
4922  /// pointer_begin - First pointer type found;
4923  iterator pointer_begin() { return PointerTypes.begin(); }
4924
4925  /// pointer_end - Past the last pointer type found;
4926  iterator pointer_end() { return PointerTypes.end(); }
4927
4928  /// member_pointer_begin - First member pointer type found;
4929  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4930
4931  /// member_pointer_end - Past the last member pointer type found;
4932  iterator member_pointer_end() { return MemberPointerTypes.end(); }
4933
4934  /// enumeration_begin - First enumeration type found;
4935  iterator enumeration_begin() { return EnumerationTypes.begin(); }
4936
4937  /// enumeration_end - Past the last enumeration type found;
4938  iterator enumeration_end() { return EnumerationTypes.end(); }
4939
4940  iterator vector_begin() { return VectorTypes.begin(); }
4941  iterator vector_end() { return VectorTypes.end(); }
4942
4943  bool hasNonRecordTypes() { return HasNonRecordTypes; }
4944  bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
4945  bool hasNullPtrType() const { return HasNullPtrType; }
4946};
4947
4948/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
4949/// the set of pointer types along with any more-qualified variants of
4950/// that type. For example, if @p Ty is "int const *", this routine
4951/// will add "int const *", "int const volatile *", "int const
4952/// restrict *", and "int const volatile restrict *" to the set of
4953/// pointer types. Returns true if the add of @p Ty itself succeeded,
4954/// false otherwise.
4955///
4956/// FIXME: what to do about extended qualifiers?
4957bool
4958BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4959                                             const Qualifiers &VisibleQuals) {
4960
4961  // Insert this type.
4962  if (!PointerTypes.insert(Ty))
4963    return false;
4964
4965  QualType PointeeTy;
4966  const PointerType *PointerTy = Ty->getAs<PointerType>();
4967  bool buildObjCPtr = false;
4968  if (!PointerTy) {
4969    if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
4970      PointeeTy = PTy->getPointeeType();
4971      buildObjCPtr = true;
4972    }
4973    else
4974      assert(false && "type was not a pointer type!");
4975  }
4976  else
4977    PointeeTy = PointerTy->getPointeeType();
4978
4979  // Don't add qualified variants of arrays. For one, they're not allowed
4980  // (the qualifier would sink to the element type), and for another, the
4981  // only overload situation where it matters is subscript or pointer +- int,
4982  // and those shouldn't have qualifier variants anyway.
4983  if (PointeeTy->isArrayType())
4984    return true;
4985  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4986  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
4987    BaseCVR = Array->getElementType().getCVRQualifiers();
4988  bool hasVolatile = VisibleQuals.hasVolatile();
4989  bool hasRestrict = VisibleQuals.hasRestrict();
4990
4991  // Iterate through all strict supersets of BaseCVR.
4992  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4993    if ((CVR | BaseCVR) != CVR) continue;
4994    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4995    // in the types.
4996    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4997    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
4998    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4999    if (!buildObjCPtr)
5000      PointerTypes.insert(Context.getPointerType(QPointeeTy));
5001    else
5002      PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
5003  }
5004
5005  return true;
5006}
5007
5008/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5009/// to the set of pointer types along with any more-qualified variants of
5010/// that type. For example, if @p Ty is "int const *", this routine
5011/// will add "int const *", "int const volatile *", "int const
5012/// restrict *", and "int const volatile restrict *" to the set of
5013/// pointer types. Returns true if the add of @p Ty itself succeeded,
5014/// false otherwise.
5015///
5016/// FIXME: what to do about extended qualifiers?
5017bool
5018BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5019    QualType Ty) {
5020  // Insert this type.
5021  if (!MemberPointerTypes.insert(Ty))
5022    return false;
5023
5024  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5025  assert(PointerTy && "type was not a member pointer type!");
5026
5027  QualType PointeeTy = PointerTy->getPointeeType();
5028  // Don't add qualified variants of arrays. For one, they're not allowed
5029  // (the qualifier would sink to the element type), and for another, the
5030  // only overload situation where it matters is subscript or pointer +- int,
5031  // and those shouldn't have qualifier variants anyway.
5032  if (PointeeTy->isArrayType())
5033    return true;
5034  const Type *ClassTy = PointerTy->getClass();
5035
5036  // Iterate through all strict supersets of the pointee type's CVR
5037  // qualifiers.
5038  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5039  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5040    if ((CVR | BaseCVR) != CVR) continue;
5041
5042    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
5043    MemberPointerTypes.insert(
5044      Context.getMemberPointerType(QPointeeTy, ClassTy));
5045  }
5046
5047  return true;
5048}
5049
5050/// AddTypesConvertedFrom - Add each of the types to which the type @p
5051/// Ty can be implicit converted to the given set of @p Types. We're
5052/// primarily interested in pointer types and enumeration types. We also
5053/// take member pointer types, for the conditional operator.
5054/// AllowUserConversions is true if we should look at the conversion
5055/// functions of a class type, and AllowExplicitConversions if we
5056/// should also include the explicit conversion functions of a class
5057/// type.
5058void
5059BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
5060                                               SourceLocation Loc,
5061                                               bool AllowUserConversions,
5062                                               bool AllowExplicitConversions,
5063                                               const Qualifiers &VisibleQuals) {
5064  // Only deal with canonical types.
5065  Ty = Context.getCanonicalType(Ty);
5066
5067  // Look through reference types; they aren't part of the type of an
5068  // expression for the purposes of conversions.
5069  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
5070    Ty = RefTy->getPointeeType();
5071
5072  // If we're dealing with an array type, decay to the pointer.
5073  if (Ty->isArrayType())
5074    Ty = SemaRef.Context.getArrayDecayedType(Ty);
5075
5076  // Otherwise, we don't care about qualifiers on the type.
5077  Ty = Ty.getLocalUnqualifiedType();
5078
5079  // Flag if we ever add a non-record type.
5080  const RecordType *TyRec = Ty->getAs<RecordType>();
5081  HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5082
5083  // Flag if we encounter an arithmetic type.
5084  HasArithmeticOrEnumeralTypes =
5085    HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5086
5087  if (Ty->isObjCIdType() || Ty->isObjCClassType())
5088    PointerTypes.insert(Ty);
5089  else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
5090    // Insert our type, and its more-qualified variants, into the set
5091    // of types.
5092    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
5093      return;
5094  } else if (Ty->isMemberPointerType()) {
5095    // Member pointers are far easier, since the pointee can't be converted.
5096    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5097      return;
5098  } else if (Ty->isEnumeralType()) {
5099    HasArithmeticOrEnumeralTypes = true;
5100    EnumerationTypes.insert(Ty);
5101  } else if (Ty->isVectorType()) {
5102    // We treat vector types as arithmetic types in many contexts as an
5103    // extension.
5104    HasArithmeticOrEnumeralTypes = true;
5105    VectorTypes.insert(Ty);
5106  } else if (Ty->isNullPtrType()) {
5107    HasNullPtrType = true;
5108  } else if (AllowUserConversions && TyRec) {
5109    // No conversion functions in incomplete types.
5110    if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5111      return;
5112
5113    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5114    const UnresolvedSetImpl *Conversions
5115      = ClassDecl->getVisibleConversionFunctions();
5116    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5117           E = Conversions->end(); I != E; ++I) {
5118      NamedDecl *D = I.getDecl();
5119      if (isa<UsingShadowDecl>(D))
5120        D = cast<UsingShadowDecl>(D)->getTargetDecl();
5121
5122      // Skip conversion function templates; they don't tell us anything
5123      // about which builtin types we can convert to.
5124      if (isa<FunctionTemplateDecl>(D))
5125        continue;
5126
5127      CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5128      if (AllowExplicitConversions || !Conv->isExplicit()) {
5129        AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5130                              VisibleQuals);
5131      }
5132    }
5133  }
5134}
5135
5136/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5137/// the volatile- and non-volatile-qualified assignment operators for the
5138/// given type to the candidate set.
5139static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5140                                                   QualType T,
5141                                                   Expr **Args,
5142                                                   unsigned NumArgs,
5143                                    OverloadCandidateSet &CandidateSet) {
5144  QualType ParamTypes[2];
5145
5146  // T& operator=(T&, T)
5147  ParamTypes[0] = S.Context.getLValueReferenceType(T);
5148  ParamTypes[1] = T;
5149  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5150                        /*IsAssignmentOperator=*/true);
5151
5152  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5153    // volatile T& operator=(volatile T&, T)
5154    ParamTypes[0]
5155      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
5156    ParamTypes[1] = T;
5157    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5158                          /*IsAssignmentOperator=*/true);
5159  }
5160}
5161
5162/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5163/// if any, found in visible type conversion functions found in ArgExpr's type.
5164static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5165    Qualifiers VRQuals;
5166    const RecordType *TyRec;
5167    if (const MemberPointerType *RHSMPType =
5168        ArgExpr->getType()->getAs<MemberPointerType>())
5169      TyRec = RHSMPType->getClass()->getAs<RecordType>();
5170    else
5171      TyRec = ArgExpr->getType()->getAs<RecordType>();
5172    if (!TyRec) {
5173      // Just to be safe, assume the worst case.
5174      VRQuals.addVolatile();
5175      VRQuals.addRestrict();
5176      return VRQuals;
5177    }
5178
5179    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5180    if (!ClassDecl->hasDefinition())
5181      return VRQuals;
5182
5183    const UnresolvedSetImpl *Conversions =
5184      ClassDecl->getVisibleConversionFunctions();
5185
5186    for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5187           E = Conversions->end(); I != E; ++I) {
5188      NamedDecl *D = I.getDecl();
5189      if (isa<UsingShadowDecl>(D))
5190        D = cast<UsingShadowDecl>(D)->getTargetDecl();
5191      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
5192        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5193        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5194          CanTy = ResTypeRef->getPointeeType();
5195        // Need to go down the pointer/mempointer chain and add qualifiers
5196        // as see them.
5197        bool done = false;
5198        while (!done) {
5199          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5200            CanTy = ResTypePtr->getPointeeType();
5201          else if (const MemberPointerType *ResTypeMPtr =
5202                CanTy->getAs<MemberPointerType>())
5203            CanTy = ResTypeMPtr->getPointeeType();
5204          else
5205            done = true;
5206          if (CanTy.isVolatileQualified())
5207            VRQuals.addVolatile();
5208          if (CanTy.isRestrictQualified())
5209            VRQuals.addRestrict();
5210          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5211            return VRQuals;
5212        }
5213      }
5214    }
5215    return VRQuals;
5216}
5217
5218namespace {
5219
5220/// \brief Helper class to manage the addition of builtin operator overload
5221/// candidates. It provides shared state and utility methods used throughout
5222/// the process, as well as a helper method to add each group of builtin
5223/// operator overloads from the standard to a candidate set.
5224class BuiltinOperatorOverloadBuilder {
5225  // Common instance state available to all overload candidate addition methods.
5226  Sema &S;
5227  Expr **Args;
5228  unsigned NumArgs;
5229  Qualifiers VisibleTypeConversionsQuals;
5230  bool HasArithmeticOrEnumeralCandidateType;
5231  llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
5232  OverloadCandidateSet &CandidateSet;
5233
5234  // Define some constants used to index and iterate over the arithemetic types
5235  // provided via the getArithmeticType() method below.
5236  // The "promoted arithmetic types" are the arithmetic
5237  // types are that preserved by promotion (C++ [over.built]p2).
5238  static const unsigned FirstIntegralType = 3;
5239  static const unsigned LastIntegralType = 18;
5240  static const unsigned FirstPromotedIntegralType = 3,
5241                        LastPromotedIntegralType = 9;
5242  static const unsigned FirstPromotedArithmeticType = 0,
5243                        LastPromotedArithmeticType = 9;
5244  static const unsigned NumArithmeticTypes = 18;
5245
5246  /// \brief Get the canonical type for a given arithmetic type index.
5247  CanQualType getArithmeticType(unsigned index) {
5248    assert(index < NumArithmeticTypes);
5249    static CanQualType ASTContext::* const
5250      ArithmeticTypes[NumArithmeticTypes] = {
5251      // Start of promoted types.
5252      &ASTContext::FloatTy,
5253      &ASTContext::DoubleTy,
5254      &ASTContext::LongDoubleTy,
5255
5256      // Start of integral types.
5257      &ASTContext::IntTy,
5258      &ASTContext::LongTy,
5259      &ASTContext::LongLongTy,
5260      &ASTContext::UnsignedIntTy,
5261      &ASTContext::UnsignedLongTy,
5262      &ASTContext::UnsignedLongLongTy,
5263      // End of promoted types.
5264
5265      &ASTContext::BoolTy,
5266      &ASTContext::CharTy,
5267      &ASTContext::WCharTy,
5268      &ASTContext::Char16Ty,
5269      &ASTContext::Char32Ty,
5270      &ASTContext::SignedCharTy,
5271      &ASTContext::ShortTy,
5272      &ASTContext::UnsignedCharTy,
5273      &ASTContext::UnsignedShortTy,
5274      // End of integral types.
5275      // FIXME: What about complex?
5276    };
5277    return S.Context.*ArithmeticTypes[index];
5278  }
5279
5280  /// \brief Gets the canonical type resulting from the usual arithemetic
5281  /// converions for the given arithmetic types.
5282  CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5283    // Accelerator table for performing the usual arithmetic conversions.
5284    // The rules are basically:
5285    //   - if either is floating-point, use the wider floating-point
5286    //   - if same signedness, use the higher rank
5287    //   - if same size, use unsigned of the higher rank
5288    //   - use the larger type
5289    // These rules, together with the axiom that higher ranks are
5290    // never smaller, are sufficient to precompute all of these results
5291    // *except* when dealing with signed types of higher rank.
5292    // (we could precompute SLL x UI for all known platforms, but it's
5293    // better not to make any assumptions).
5294    enum PromotedType {
5295                  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL, Dep=-1
5296    };
5297    static PromotedType ConversionsTable[LastPromotedArithmeticType]
5298                                        [LastPromotedArithmeticType] = {
5299      /* Flt*/ {  Flt,  Dbl, LDbl,  Flt,  Flt,  Flt,  Flt,  Flt,  Flt },
5300      /* Dbl*/ {  Dbl,  Dbl, LDbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl,  Dbl },
5301      /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5302      /*  SI*/ {  Flt,  Dbl, LDbl,   SI,   SL,  SLL,   UI,   UL,  ULL },
5303      /*  SL*/ {  Flt,  Dbl, LDbl,   SL,   SL,  SLL,  Dep,   UL,  ULL },
5304      /* SLL*/ {  Flt,  Dbl, LDbl,  SLL,  SLL,  SLL,  Dep,  Dep,  ULL },
5305      /*  UI*/ {  Flt,  Dbl, LDbl,   UI,  Dep,  Dep,   UI,   UL,  ULL },
5306      /*  UL*/ {  Flt,  Dbl, LDbl,   UL,   UL,  Dep,   UL,   UL,  ULL },
5307      /* ULL*/ {  Flt,  Dbl, LDbl,  ULL,  ULL,  ULL,  ULL,  ULL,  ULL },
5308    };
5309
5310    assert(L < LastPromotedArithmeticType);
5311    assert(R < LastPromotedArithmeticType);
5312    int Idx = ConversionsTable[L][R];
5313
5314    // Fast path: the table gives us a concrete answer.
5315    if (Idx != Dep) return getArithmeticType(Idx);
5316
5317    // Slow path: we need to compare widths.
5318    // An invariant is that the signed type has higher rank.
5319    CanQualType LT = getArithmeticType(L),
5320                RT = getArithmeticType(R);
5321    unsigned LW = S.Context.getIntWidth(LT),
5322             RW = S.Context.getIntWidth(RT);
5323
5324    // If they're different widths, use the signed type.
5325    if (LW > RW) return LT;
5326    else if (LW < RW) return RT;
5327
5328    // Otherwise, use the unsigned type of the signed type's rank.
5329    if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5330    assert(L == SLL || R == SLL);
5331    return S.Context.UnsignedLongLongTy;
5332  }
5333
5334  /// \brief Helper method to factor out the common pattern of adding overloads
5335  /// for '++' and '--' builtin operators.
5336  void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5337                                           bool HasVolatile) {
5338    QualType ParamTypes[2] = {
5339      S.Context.getLValueReferenceType(CandidateTy),
5340      S.Context.IntTy
5341    };
5342
5343    // Non-volatile version.
5344    if (NumArgs == 1)
5345      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5346    else
5347      S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5348
5349    // Use a heuristic to reduce number of builtin candidates in the set:
5350    // add volatile version only if there are conversions to a volatile type.
5351    if (HasVolatile) {
5352      ParamTypes[0] =
5353        S.Context.getLValueReferenceType(
5354          S.Context.getVolatileType(CandidateTy));
5355      if (NumArgs == 1)
5356        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5357      else
5358        S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5359    }
5360  }
5361
5362public:
5363  BuiltinOperatorOverloadBuilder(
5364    Sema &S, Expr **Args, unsigned NumArgs,
5365    Qualifiers VisibleTypeConversionsQuals,
5366    bool HasArithmeticOrEnumeralCandidateType,
5367    llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5368    OverloadCandidateSet &CandidateSet)
5369    : S(S), Args(Args), NumArgs(NumArgs),
5370      VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
5371      HasArithmeticOrEnumeralCandidateType(
5372        HasArithmeticOrEnumeralCandidateType),
5373      CandidateTypes(CandidateTypes),
5374      CandidateSet(CandidateSet) {
5375    // Validate some of our static helper constants in debug builds.
5376    assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
5377           "Invalid first promoted integral type");
5378    assert(getArithmeticType(LastPromotedIntegralType - 1)
5379             == S.Context.UnsignedLongLongTy &&
5380           "Invalid last promoted integral type");
5381    assert(getArithmeticType(FirstPromotedArithmeticType)
5382             == S.Context.FloatTy &&
5383           "Invalid first promoted arithmetic type");
5384    assert(getArithmeticType(LastPromotedArithmeticType - 1)
5385             == S.Context.UnsignedLongLongTy &&
5386           "Invalid last promoted arithmetic type");
5387  }
5388
5389  // C++ [over.built]p3:
5390  //
5391  //   For every pair (T, VQ), where T is an arithmetic type, and VQ
5392  //   is either volatile or empty, there exist candidate operator
5393  //   functions of the form
5394  //
5395  //       VQ T&      operator++(VQ T&);
5396  //       T          operator++(VQ T&, int);
5397  //
5398  // C++ [over.built]p4:
5399  //
5400  //   For every pair (T, VQ), where T is an arithmetic type other
5401  //   than bool, and VQ is either volatile or empty, there exist
5402  //   candidate operator functions of the form
5403  //
5404  //       VQ T&      operator--(VQ T&);
5405  //       T          operator--(VQ T&, int);
5406  void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
5407    if (!HasArithmeticOrEnumeralCandidateType)
5408      return;
5409
5410    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5411         Arith < NumArithmeticTypes; ++Arith) {
5412      addPlusPlusMinusMinusStyleOverloads(
5413        getArithmeticType(Arith),
5414        VisibleTypeConversionsQuals.hasVolatile());
5415    }
5416  }
5417
5418  // C++ [over.built]p5:
5419  //
5420  //   For every pair (T, VQ), where T is a cv-qualified or
5421  //   cv-unqualified object type, and VQ is either volatile or
5422  //   empty, there exist candidate operator functions of the form
5423  //
5424  //       T*VQ&      operator++(T*VQ&);
5425  //       T*VQ&      operator--(T*VQ&);
5426  //       T*         operator++(T*VQ&, int);
5427  //       T*         operator--(T*VQ&, int);
5428  void addPlusPlusMinusMinusPointerOverloads() {
5429    for (BuiltinCandidateTypeSet::iterator
5430              Ptr = CandidateTypes[0].pointer_begin(),
5431           PtrEnd = CandidateTypes[0].pointer_end();
5432         Ptr != PtrEnd; ++Ptr) {
5433      // Skip pointer types that aren't pointers to object types.
5434      if (!(*Ptr)->getPointeeType()->isObjectType())
5435        continue;
5436
5437      addPlusPlusMinusMinusStyleOverloads(*Ptr,
5438        (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5439         VisibleTypeConversionsQuals.hasVolatile()));
5440    }
5441  }
5442
5443  // C++ [over.built]p6:
5444  //   For every cv-qualified or cv-unqualified object type T, there
5445  //   exist candidate operator functions of the form
5446  //
5447  //       T&         operator*(T*);
5448  //
5449  // C++ [over.built]p7:
5450  //   For every function type T that does not have cv-qualifiers or a
5451  //   ref-qualifier, there exist candidate operator functions of the form
5452  //       T&         operator*(T*);
5453  void addUnaryStarPointerOverloads() {
5454    for (BuiltinCandidateTypeSet::iterator
5455              Ptr = CandidateTypes[0].pointer_begin(),
5456           PtrEnd = CandidateTypes[0].pointer_end();
5457         Ptr != PtrEnd; ++Ptr) {
5458      QualType ParamTy = *Ptr;
5459      QualType PointeeTy = ParamTy->getPointeeType();
5460      if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5461        continue;
5462
5463      if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5464        if (Proto->getTypeQuals() || Proto->getRefQualifier())
5465          continue;
5466
5467      S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5468                            &ParamTy, Args, 1, CandidateSet);
5469    }
5470  }
5471
5472  // C++ [over.built]p9:
5473  //  For every promoted arithmetic type T, there exist candidate
5474  //  operator functions of the form
5475  //
5476  //       T         operator+(T);
5477  //       T         operator-(T);
5478  void addUnaryPlusOrMinusArithmeticOverloads() {
5479    if (!HasArithmeticOrEnumeralCandidateType)
5480      return;
5481
5482    for (unsigned Arith = FirstPromotedArithmeticType;
5483         Arith < LastPromotedArithmeticType; ++Arith) {
5484      QualType ArithTy = getArithmeticType(Arith);
5485      S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5486    }
5487
5488    // Extension: We also add these operators for vector types.
5489    for (BuiltinCandidateTypeSet::iterator
5490              Vec = CandidateTypes[0].vector_begin(),
5491           VecEnd = CandidateTypes[0].vector_end();
5492         Vec != VecEnd; ++Vec) {
5493      QualType VecTy = *Vec;
5494      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5495    }
5496  }
5497
5498  // C++ [over.built]p8:
5499  //   For every type T, there exist candidate operator functions of
5500  //   the form
5501  //
5502  //       T*         operator+(T*);
5503  void addUnaryPlusPointerOverloads() {
5504    for (BuiltinCandidateTypeSet::iterator
5505              Ptr = CandidateTypes[0].pointer_begin(),
5506           PtrEnd = CandidateTypes[0].pointer_end();
5507         Ptr != PtrEnd; ++Ptr) {
5508      QualType ParamTy = *Ptr;
5509      S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5510    }
5511  }
5512
5513  // C++ [over.built]p10:
5514  //   For every promoted integral type T, there exist candidate
5515  //   operator functions of the form
5516  //
5517  //        T         operator~(T);
5518  void addUnaryTildePromotedIntegralOverloads() {
5519    if (!HasArithmeticOrEnumeralCandidateType)
5520      return;
5521
5522    for (unsigned Int = FirstPromotedIntegralType;
5523         Int < LastPromotedIntegralType; ++Int) {
5524      QualType IntTy = getArithmeticType(Int);
5525      S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5526    }
5527
5528    // Extension: We also add this operator for vector types.
5529    for (BuiltinCandidateTypeSet::iterator
5530              Vec = CandidateTypes[0].vector_begin(),
5531           VecEnd = CandidateTypes[0].vector_end();
5532         Vec != VecEnd; ++Vec) {
5533      QualType VecTy = *Vec;
5534      S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5535    }
5536  }
5537
5538  // C++ [over.match.oper]p16:
5539  //   For every pointer to member type T, there exist candidate operator
5540  //   functions of the form
5541  //
5542  //        bool operator==(T,T);
5543  //        bool operator!=(T,T);
5544  void addEqualEqualOrNotEqualMemberPointerOverloads() {
5545    /// Set of (canonical) types that we've already handled.
5546    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5547
5548    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5549      for (BuiltinCandidateTypeSet::iterator
5550                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5551             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5552           MemPtr != MemPtrEnd;
5553           ++MemPtr) {
5554        // Don't add the same builtin candidate twice.
5555        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5556          continue;
5557
5558        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5559        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5560                              CandidateSet);
5561      }
5562    }
5563  }
5564
5565  // C++ [over.built]p15:
5566  //
5567  //   For every T, where T is an enumeration type, a pointer type, or
5568  //   std::nullptr_t, there exist candidate operator functions of the form
5569  //
5570  //        bool       operator<(T, T);
5571  //        bool       operator>(T, T);
5572  //        bool       operator<=(T, T);
5573  //        bool       operator>=(T, T);
5574  //        bool       operator==(T, T);
5575  //        bool       operator!=(T, T);
5576  void addRelationalPointerOrEnumeralOverloads() {
5577    // C++ [over.built]p1:
5578    //   If there is a user-written candidate with the same name and parameter
5579    //   types as a built-in candidate operator function, the built-in operator
5580    //   function is hidden and is not included in the set of candidate
5581    //   functions.
5582    //
5583    // The text is actually in a note, but if we don't implement it then we end
5584    // up with ambiguities when the user provides an overloaded operator for
5585    // an enumeration type. Note that only enumeration types have this problem,
5586    // so we track which enumeration types we've seen operators for. Also, the
5587    // only other overloaded operator with enumeration argumenst, operator=,
5588    // cannot be overloaded for enumeration types, so this is the only place
5589    // where we must suppress candidates like this.
5590    llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5591      UserDefinedBinaryOperators;
5592
5593    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5594      if (CandidateTypes[ArgIdx].enumeration_begin() !=
5595          CandidateTypes[ArgIdx].enumeration_end()) {
5596        for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5597                                         CEnd = CandidateSet.end();
5598             C != CEnd; ++C) {
5599          if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5600            continue;
5601
5602          QualType FirstParamType =
5603            C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5604          QualType SecondParamType =
5605            C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5606
5607          // Skip if either parameter isn't of enumeral type.
5608          if (!FirstParamType->isEnumeralType() ||
5609              !SecondParamType->isEnumeralType())
5610            continue;
5611
5612          // Add this operator to the set of known user-defined operators.
5613          UserDefinedBinaryOperators.insert(
5614            std::make_pair(S.Context.getCanonicalType(FirstParamType),
5615                           S.Context.getCanonicalType(SecondParamType)));
5616        }
5617      }
5618    }
5619
5620    /// Set of (canonical) types that we've already handled.
5621    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5622
5623    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5624      for (BuiltinCandidateTypeSet::iterator
5625                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5626             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5627           Ptr != PtrEnd; ++Ptr) {
5628        // Don't add the same builtin candidate twice.
5629        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5630          continue;
5631
5632        QualType ParamTypes[2] = { *Ptr, *Ptr };
5633        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5634                              CandidateSet);
5635      }
5636      for (BuiltinCandidateTypeSet::iterator
5637                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5638             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5639           Enum != EnumEnd; ++Enum) {
5640        CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5641
5642        // Don't add the same builtin candidate twice, or if a user defined
5643        // candidate exists.
5644        if (!AddedTypes.insert(CanonType) ||
5645            UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5646                                                            CanonType)))
5647          continue;
5648
5649        QualType ParamTypes[2] = { *Enum, *Enum };
5650        S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5651                              CandidateSet);
5652      }
5653
5654      if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5655        CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5656        if (AddedTypes.insert(NullPtrTy) &&
5657            !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5658                                                             NullPtrTy))) {
5659          QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5660          S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5661                                CandidateSet);
5662        }
5663      }
5664    }
5665  }
5666
5667  // C++ [over.built]p13:
5668  //
5669  //   For every cv-qualified or cv-unqualified object type T
5670  //   there exist candidate operator functions of the form
5671  //
5672  //      T*         operator+(T*, ptrdiff_t);
5673  //      T&         operator[](T*, ptrdiff_t);    [BELOW]
5674  //      T*         operator-(T*, ptrdiff_t);
5675  //      T*         operator+(ptrdiff_t, T*);
5676  //      T&         operator[](ptrdiff_t, T*);    [BELOW]
5677  //
5678  // C++ [over.built]p14:
5679  //
5680  //   For every T, where T is a pointer to object type, there
5681  //   exist candidate operator functions of the form
5682  //
5683  //      ptrdiff_t  operator-(T, T);
5684  void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5685    /// Set of (canonical) types that we've already handled.
5686    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5687
5688    for (int Arg = 0; Arg < 2; ++Arg) {
5689      QualType AsymetricParamTypes[2] = {
5690        S.Context.getPointerDiffType(),
5691        S.Context.getPointerDiffType(),
5692      };
5693      for (BuiltinCandidateTypeSet::iterator
5694                Ptr = CandidateTypes[Arg].pointer_begin(),
5695             PtrEnd = CandidateTypes[Arg].pointer_end();
5696           Ptr != PtrEnd; ++Ptr) {
5697        QualType PointeeTy = (*Ptr)->getPointeeType();
5698        if (!PointeeTy->isObjectType())
5699          continue;
5700
5701        AsymetricParamTypes[Arg] = *Ptr;
5702        if (Arg == 0 || Op == OO_Plus) {
5703          // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5704          // T* operator+(ptrdiff_t, T*);
5705          S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5706                                CandidateSet);
5707        }
5708        if (Op == OO_Minus) {
5709          // ptrdiff_t operator-(T, T);
5710          if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5711            continue;
5712
5713          QualType ParamTypes[2] = { *Ptr, *Ptr };
5714          S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5715                                Args, 2, CandidateSet);
5716        }
5717      }
5718    }
5719  }
5720
5721  // C++ [over.built]p12:
5722  //
5723  //   For every pair of promoted arithmetic types L and R, there
5724  //   exist candidate operator functions of the form
5725  //
5726  //        LR         operator*(L, R);
5727  //        LR         operator/(L, R);
5728  //        LR         operator+(L, R);
5729  //        LR         operator-(L, R);
5730  //        bool       operator<(L, R);
5731  //        bool       operator>(L, R);
5732  //        bool       operator<=(L, R);
5733  //        bool       operator>=(L, R);
5734  //        bool       operator==(L, R);
5735  //        bool       operator!=(L, R);
5736  //
5737  //   where LR is the result of the usual arithmetic conversions
5738  //   between types L and R.
5739  //
5740  // C++ [over.built]p24:
5741  //
5742  //   For every pair of promoted arithmetic types L and R, there exist
5743  //   candidate operator functions of the form
5744  //
5745  //        LR       operator?(bool, L, R);
5746  //
5747  //   where LR is the result of the usual arithmetic conversions
5748  //   between types L and R.
5749  // Our candidates ignore the first parameter.
5750  void addGenericBinaryArithmeticOverloads(bool isComparison) {
5751    if (!HasArithmeticOrEnumeralCandidateType)
5752      return;
5753
5754    for (unsigned Left = FirstPromotedArithmeticType;
5755         Left < LastPromotedArithmeticType; ++Left) {
5756      for (unsigned Right = FirstPromotedArithmeticType;
5757           Right < LastPromotedArithmeticType; ++Right) {
5758        QualType LandR[2] = { getArithmeticType(Left),
5759                              getArithmeticType(Right) };
5760        QualType Result =
5761          isComparison ? S.Context.BoolTy
5762                       : getUsualArithmeticConversions(Left, Right);
5763        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5764      }
5765    }
5766
5767    // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5768    // conditional operator for vector types.
5769    for (BuiltinCandidateTypeSet::iterator
5770              Vec1 = CandidateTypes[0].vector_begin(),
5771           Vec1End = CandidateTypes[0].vector_end();
5772         Vec1 != Vec1End; ++Vec1) {
5773      for (BuiltinCandidateTypeSet::iterator
5774                Vec2 = CandidateTypes[1].vector_begin(),
5775             Vec2End = CandidateTypes[1].vector_end();
5776           Vec2 != Vec2End; ++Vec2) {
5777        QualType LandR[2] = { *Vec1, *Vec2 };
5778        QualType Result = S.Context.BoolTy;
5779        if (!isComparison) {
5780          if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5781            Result = *Vec1;
5782          else
5783            Result = *Vec2;
5784        }
5785
5786        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5787      }
5788    }
5789  }
5790
5791  // C++ [over.built]p17:
5792  //
5793  //   For every pair of promoted integral types L and R, there
5794  //   exist candidate operator functions of the form
5795  //
5796  //      LR         operator%(L, R);
5797  //      LR         operator&(L, R);
5798  //      LR         operator^(L, R);
5799  //      LR         operator|(L, R);
5800  //      L          operator<<(L, R);
5801  //      L          operator>>(L, R);
5802  //
5803  //   where LR is the result of the usual arithmetic conversions
5804  //   between types L and R.
5805  void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
5806    if (!HasArithmeticOrEnumeralCandidateType)
5807      return;
5808
5809    for (unsigned Left = FirstPromotedIntegralType;
5810         Left < LastPromotedIntegralType; ++Left) {
5811      for (unsigned Right = FirstPromotedIntegralType;
5812           Right < LastPromotedIntegralType; ++Right) {
5813        QualType LandR[2] = { getArithmeticType(Left),
5814                              getArithmeticType(Right) };
5815        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5816            ? LandR[0]
5817            : getUsualArithmeticConversions(Left, Right);
5818        S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5819      }
5820    }
5821  }
5822
5823  // C++ [over.built]p20:
5824  //
5825  //   For every pair (T, VQ), where T is an enumeration or
5826  //   pointer to member type and VQ is either volatile or
5827  //   empty, there exist candidate operator functions of the form
5828  //
5829  //        VQ T&      operator=(VQ T&, T);
5830  void addAssignmentMemberPointerOrEnumeralOverloads() {
5831    /// Set of (canonical) types that we've already handled.
5832    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5833
5834    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5835      for (BuiltinCandidateTypeSet::iterator
5836                Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5837             EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5838           Enum != EnumEnd; ++Enum) {
5839        if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5840          continue;
5841
5842        AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5843                                               CandidateSet);
5844      }
5845
5846      for (BuiltinCandidateTypeSet::iterator
5847                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5848             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5849           MemPtr != MemPtrEnd; ++MemPtr) {
5850        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5851          continue;
5852
5853        AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5854                                               CandidateSet);
5855      }
5856    }
5857  }
5858
5859  // C++ [over.built]p19:
5860  //
5861  //   For every pair (T, VQ), where T is any type and VQ is either
5862  //   volatile or empty, there exist candidate operator functions
5863  //   of the form
5864  //
5865  //        T*VQ&      operator=(T*VQ&, T*);
5866  //
5867  // C++ [over.built]p21:
5868  //
5869  //   For every pair (T, VQ), where T is a cv-qualified or
5870  //   cv-unqualified object type and VQ is either volatile or
5871  //   empty, there exist candidate operator functions of the form
5872  //
5873  //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
5874  //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
5875  void addAssignmentPointerOverloads(bool isEqualOp) {
5876    /// Set of (canonical) types that we've already handled.
5877    llvm::SmallPtrSet<QualType, 8> AddedTypes;
5878
5879    for (BuiltinCandidateTypeSet::iterator
5880              Ptr = CandidateTypes[0].pointer_begin(),
5881           PtrEnd = CandidateTypes[0].pointer_end();
5882         Ptr != PtrEnd; ++Ptr) {
5883      // If this is operator=, keep track of the builtin candidates we added.
5884      if (isEqualOp)
5885        AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
5886      else if (!(*Ptr)->getPointeeType()->isObjectType())
5887        continue;
5888
5889      // non-volatile version
5890      QualType ParamTypes[2] = {
5891        S.Context.getLValueReferenceType(*Ptr),
5892        isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5893      };
5894      S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5895                            /*IsAssigmentOperator=*/ isEqualOp);
5896
5897      if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5898          VisibleTypeConversionsQuals.hasVolatile()) {
5899        // volatile version
5900        ParamTypes[0] =
5901          S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5902        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5903                              /*IsAssigmentOperator=*/isEqualOp);
5904      }
5905    }
5906
5907    if (isEqualOp) {
5908      for (BuiltinCandidateTypeSet::iterator
5909                Ptr = CandidateTypes[1].pointer_begin(),
5910             PtrEnd = CandidateTypes[1].pointer_end();
5911           Ptr != PtrEnd; ++Ptr) {
5912        // Make sure we don't add the same candidate twice.
5913        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5914          continue;
5915
5916        QualType ParamTypes[2] = {
5917          S.Context.getLValueReferenceType(*Ptr),
5918          *Ptr,
5919        };
5920
5921        // non-volatile version
5922        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5923                              /*IsAssigmentOperator=*/true);
5924
5925        if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5926            VisibleTypeConversionsQuals.hasVolatile()) {
5927          // volatile version
5928          ParamTypes[0] =
5929            S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5930          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5931                                CandidateSet, /*IsAssigmentOperator=*/true);
5932        }
5933      }
5934    }
5935  }
5936
5937  // C++ [over.built]p18:
5938  //
5939  //   For every triple (L, VQ, R), where L is an arithmetic type,
5940  //   VQ is either volatile or empty, and R is a promoted
5941  //   arithmetic type, there exist candidate operator functions of
5942  //   the form
5943  //
5944  //        VQ L&      operator=(VQ L&, R);
5945  //        VQ L&      operator*=(VQ L&, R);
5946  //        VQ L&      operator/=(VQ L&, R);
5947  //        VQ L&      operator+=(VQ L&, R);
5948  //        VQ L&      operator-=(VQ L&, R);
5949  void addAssignmentArithmeticOverloads(bool isEqualOp) {
5950    if (!HasArithmeticOrEnumeralCandidateType)
5951      return;
5952
5953    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5954      for (unsigned Right = FirstPromotedArithmeticType;
5955           Right < LastPromotedArithmeticType; ++Right) {
5956        QualType ParamTypes[2];
5957        ParamTypes[1] = getArithmeticType(Right);
5958
5959        // Add this built-in operator as a candidate (VQ is empty).
5960        ParamTypes[0] =
5961          S.Context.getLValueReferenceType(getArithmeticType(Left));
5962        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5963                              /*IsAssigmentOperator=*/isEqualOp);
5964
5965        // Add this built-in operator as a candidate (VQ is 'volatile').
5966        if (VisibleTypeConversionsQuals.hasVolatile()) {
5967          ParamTypes[0] =
5968            S.Context.getVolatileType(getArithmeticType(Left));
5969          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5970          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5971                                CandidateSet,
5972                                /*IsAssigmentOperator=*/isEqualOp);
5973        }
5974      }
5975    }
5976
5977    // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5978    for (BuiltinCandidateTypeSet::iterator
5979              Vec1 = CandidateTypes[0].vector_begin(),
5980           Vec1End = CandidateTypes[0].vector_end();
5981         Vec1 != Vec1End; ++Vec1) {
5982      for (BuiltinCandidateTypeSet::iterator
5983                Vec2 = CandidateTypes[1].vector_begin(),
5984             Vec2End = CandidateTypes[1].vector_end();
5985           Vec2 != Vec2End; ++Vec2) {
5986        QualType ParamTypes[2];
5987        ParamTypes[1] = *Vec2;
5988        // Add this built-in operator as a candidate (VQ is empty).
5989        ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5990        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5991                              /*IsAssigmentOperator=*/isEqualOp);
5992
5993        // Add this built-in operator as a candidate (VQ is 'volatile').
5994        if (VisibleTypeConversionsQuals.hasVolatile()) {
5995          ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5996          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5997          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5998                                CandidateSet,
5999                                /*IsAssigmentOperator=*/isEqualOp);
6000        }
6001      }
6002    }
6003  }
6004
6005  // C++ [over.built]p22:
6006  //
6007  //   For every triple (L, VQ, R), where L is an integral type, VQ
6008  //   is either volatile or empty, and R is a promoted integral
6009  //   type, there exist candidate operator functions of the form
6010  //
6011  //        VQ L&       operator%=(VQ L&, R);
6012  //        VQ L&       operator<<=(VQ L&, R);
6013  //        VQ L&       operator>>=(VQ L&, R);
6014  //        VQ L&       operator&=(VQ L&, R);
6015  //        VQ L&       operator^=(VQ L&, R);
6016  //        VQ L&       operator|=(VQ L&, R);
6017  void addAssignmentIntegralOverloads() {
6018    if (!HasArithmeticOrEnumeralCandidateType)
6019      return;
6020
6021    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6022      for (unsigned Right = FirstPromotedIntegralType;
6023           Right < LastPromotedIntegralType; ++Right) {
6024        QualType ParamTypes[2];
6025        ParamTypes[1] = getArithmeticType(Right);
6026
6027        // Add this built-in operator as a candidate (VQ is empty).
6028        ParamTypes[0] =
6029          S.Context.getLValueReferenceType(getArithmeticType(Left));
6030        S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6031        if (VisibleTypeConversionsQuals.hasVolatile()) {
6032          // Add this built-in operator as a candidate (VQ is 'volatile').
6033          ParamTypes[0] = getArithmeticType(Left);
6034          ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6035          ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6036          S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6037                                CandidateSet);
6038        }
6039      }
6040    }
6041  }
6042
6043  // C++ [over.operator]p23:
6044  //
6045  //   There also exist candidate operator functions of the form
6046  //
6047  //        bool        operator!(bool);
6048  //        bool        operator&&(bool, bool);
6049  //        bool        operator||(bool, bool);
6050  void addExclaimOverload() {
6051    QualType ParamTy = S.Context.BoolTy;
6052    S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6053                          /*IsAssignmentOperator=*/false,
6054                          /*NumContextualBoolArguments=*/1);
6055  }
6056  void addAmpAmpOrPipePipeOverload() {
6057    QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6058    S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6059                          /*IsAssignmentOperator=*/false,
6060                          /*NumContextualBoolArguments=*/2);
6061  }
6062
6063  // C++ [over.built]p13:
6064  //
6065  //   For every cv-qualified or cv-unqualified object type T there
6066  //   exist candidate operator functions of the form
6067  //
6068  //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
6069  //        T&         operator[](T*, ptrdiff_t);
6070  //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
6071  //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
6072  //        T&         operator[](ptrdiff_t, T*);
6073  void addSubscriptOverloads() {
6074    for (BuiltinCandidateTypeSet::iterator
6075              Ptr = CandidateTypes[0].pointer_begin(),
6076           PtrEnd = CandidateTypes[0].pointer_end();
6077         Ptr != PtrEnd; ++Ptr) {
6078      QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6079      QualType PointeeType = (*Ptr)->getPointeeType();
6080      if (!PointeeType->isObjectType())
6081        continue;
6082
6083      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6084
6085      // T& operator[](T*, ptrdiff_t)
6086      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6087    }
6088
6089    for (BuiltinCandidateTypeSet::iterator
6090              Ptr = CandidateTypes[1].pointer_begin(),
6091           PtrEnd = CandidateTypes[1].pointer_end();
6092         Ptr != PtrEnd; ++Ptr) {
6093      QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6094      QualType PointeeType = (*Ptr)->getPointeeType();
6095      if (!PointeeType->isObjectType())
6096        continue;
6097
6098      QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6099
6100      // T& operator[](ptrdiff_t, T*)
6101      S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6102    }
6103  }
6104
6105  // C++ [over.built]p11:
6106  //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6107  //    C1 is the same type as C2 or is a derived class of C2, T is an object
6108  //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6109  //    there exist candidate operator functions of the form
6110  //
6111  //      CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6112  //
6113  //    where CV12 is the union of CV1 and CV2.
6114  void addArrowStarOverloads() {
6115    for (BuiltinCandidateTypeSet::iterator
6116             Ptr = CandidateTypes[0].pointer_begin(),
6117           PtrEnd = CandidateTypes[0].pointer_end();
6118         Ptr != PtrEnd; ++Ptr) {
6119      QualType C1Ty = (*Ptr);
6120      QualType C1;
6121      QualifierCollector Q1;
6122      C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6123      if (!isa<RecordType>(C1))
6124        continue;
6125      // heuristic to reduce number of builtin candidates in the set.
6126      // Add volatile/restrict version only if there are conversions to a
6127      // volatile/restrict type.
6128      if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6129        continue;
6130      if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6131        continue;
6132      for (BuiltinCandidateTypeSet::iterator
6133                MemPtr = CandidateTypes[1].member_pointer_begin(),
6134             MemPtrEnd = CandidateTypes[1].member_pointer_end();
6135           MemPtr != MemPtrEnd; ++MemPtr) {
6136        const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6137        QualType C2 = QualType(mptr->getClass(), 0);
6138        C2 = C2.getUnqualifiedType();
6139        if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6140          break;
6141        QualType ParamTypes[2] = { *Ptr, *MemPtr };
6142        // build CV12 T&
6143        QualType T = mptr->getPointeeType();
6144        if (!VisibleTypeConversionsQuals.hasVolatile() &&
6145            T.isVolatileQualified())
6146          continue;
6147        if (!VisibleTypeConversionsQuals.hasRestrict() &&
6148            T.isRestrictQualified())
6149          continue;
6150        T = Q1.apply(S.Context, T);
6151        QualType ResultTy = S.Context.getLValueReferenceType(T);
6152        S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6153      }
6154    }
6155  }
6156
6157  // Note that we don't consider the first argument, since it has been
6158  // contextually converted to bool long ago. The candidates below are
6159  // therefore added as binary.
6160  //
6161  // C++ [over.built]p25:
6162  //   For every type T, where T is a pointer, pointer-to-member, or scoped
6163  //   enumeration type, there exist candidate operator functions of the form
6164  //
6165  //        T        operator?(bool, T, T);
6166  //
6167  void addConditionalOperatorOverloads() {
6168    /// Set of (canonical) types that we've already handled.
6169    llvm::SmallPtrSet<QualType, 8> AddedTypes;
6170
6171    for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6172      for (BuiltinCandidateTypeSet::iterator
6173                Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6174             PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6175           Ptr != PtrEnd; ++Ptr) {
6176        if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6177          continue;
6178
6179        QualType ParamTypes[2] = { *Ptr, *Ptr };
6180        S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6181      }
6182
6183      for (BuiltinCandidateTypeSet::iterator
6184                MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6185             MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6186           MemPtr != MemPtrEnd; ++MemPtr) {
6187        if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6188          continue;
6189
6190        QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6191        S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6192      }
6193
6194      if (S.getLangOptions().CPlusPlus0x) {
6195        for (BuiltinCandidateTypeSet::iterator
6196                  Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6197               EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6198             Enum != EnumEnd; ++Enum) {
6199          if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6200            continue;
6201
6202          if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6203            continue;
6204
6205          QualType ParamTypes[2] = { *Enum, *Enum };
6206          S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6207        }
6208      }
6209    }
6210  }
6211};
6212
6213} // end anonymous namespace
6214
6215/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6216/// operator overloads to the candidate set (C++ [over.built]), based
6217/// on the operator @p Op and the arguments given. For example, if the
6218/// operator is a binary '+', this routine might add "int
6219/// operator+(int, int)" to cover integer addition.
6220void
6221Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6222                                   SourceLocation OpLoc,
6223                                   Expr **Args, unsigned NumArgs,
6224                                   OverloadCandidateSet& CandidateSet) {
6225  // Find all of the types that the arguments can convert to, but only
6226  // if the operator we're looking at has built-in operator candidates
6227  // that make use of these types. Also record whether we encounter non-record
6228  // candidate types or either arithmetic or enumeral candidate types.
6229  Qualifiers VisibleTypeConversionsQuals;
6230  VisibleTypeConversionsQuals.addConst();
6231  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6232    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
6233
6234  bool HasNonRecordCandidateType = false;
6235  bool HasArithmeticOrEnumeralCandidateType = false;
6236  llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
6237  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6238    CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6239    CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6240                                                 OpLoc,
6241                                                 true,
6242                                                 (Op == OO_Exclaim ||
6243                                                  Op == OO_AmpAmp ||
6244                                                  Op == OO_PipePipe),
6245                                                 VisibleTypeConversionsQuals);
6246    HasNonRecordCandidateType = HasNonRecordCandidateType ||
6247        CandidateTypes[ArgIdx].hasNonRecordTypes();
6248    HasArithmeticOrEnumeralCandidateType =
6249        HasArithmeticOrEnumeralCandidateType ||
6250        CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
6251  }
6252
6253  // Exit early when no non-record types have been added to the candidate set
6254  // for any of the arguments to the operator.
6255  if (!HasNonRecordCandidateType)
6256    return;
6257
6258  // Setup an object to manage the common state for building overloads.
6259  BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6260                                           VisibleTypeConversionsQuals,
6261                                           HasArithmeticOrEnumeralCandidateType,
6262                                           CandidateTypes, CandidateSet);
6263
6264  // Dispatch over the operation to add in only those overloads which apply.
6265  switch (Op) {
6266  case OO_None:
6267  case NUM_OVERLOADED_OPERATORS:
6268    assert(false && "Expected an overloaded operator");
6269    break;
6270
6271  case OO_New:
6272  case OO_Delete:
6273  case OO_Array_New:
6274  case OO_Array_Delete:
6275  case OO_Call:
6276    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6277    break;
6278
6279  case OO_Comma:
6280  case OO_Arrow:
6281    // C++ [over.match.oper]p3:
6282    //   -- For the operator ',', the unary operator '&', or the
6283    //      operator '->', the built-in candidates set is empty.
6284    break;
6285
6286  case OO_Plus: // '+' is either unary or binary
6287    if (NumArgs == 1)
6288      OpBuilder.addUnaryPlusPointerOverloads();
6289    // Fall through.
6290
6291  case OO_Minus: // '-' is either unary or binary
6292    if (NumArgs == 1) {
6293      OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
6294    } else {
6295      OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6296      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6297    }
6298    break;
6299
6300  case OO_Star: // '*' is either unary or binary
6301    if (NumArgs == 1)
6302      OpBuilder.addUnaryStarPointerOverloads();
6303    else
6304      OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6305    break;
6306
6307  case OO_Slash:
6308    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6309    break;
6310
6311  case OO_PlusPlus:
6312  case OO_MinusMinus:
6313    OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6314    OpBuilder.addPlusPlusMinusMinusPointerOverloads();
6315    break;
6316
6317  case OO_EqualEqual:
6318  case OO_ExclaimEqual:
6319    OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
6320    // Fall through.
6321
6322  case OO_Less:
6323  case OO_Greater:
6324  case OO_LessEqual:
6325  case OO_GreaterEqual:
6326    OpBuilder.addRelationalPointerOrEnumeralOverloads();
6327    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6328    break;
6329
6330  case OO_Percent:
6331  case OO_Caret:
6332  case OO_Pipe:
6333  case OO_LessLess:
6334  case OO_GreaterGreater:
6335    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6336    break;
6337
6338  case OO_Amp: // '&' is either unary or binary
6339    if (NumArgs == 1)
6340      // C++ [over.match.oper]p3:
6341      //   -- For the operator ',', the unary operator '&', or the
6342      //      operator '->', the built-in candidates set is empty.
6343      break;
6344
6345    OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6346    break;
6347
6348  case OO_Tilde:
6349    OpBuilder.addUnaryTildePromotedIntegralOverloads();
6350    break;
6351
6352  case OO_Equal:
6353    OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
6354    // Fall through.
6355
6356  case OO_PlusEqual:
6357  case OO_MinusEqual:
6358    OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
6359    // Fall through.
6360
6361  case OO_StarEqual:
6362  case OO_SlashEqual:
6363    OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
6364    break;
6365
6366  case OO_PercentEqual:
6367  case OO_LessLessEqual:
6368  case OO_GreaterGreaterEqual:
6369  case OO_AmpEqual:
6370  case OO_CaretEqual:
6371  case OO_PipeEqual:
6372    OpBuilder.addAssignmentIntegralOverloads();
6373    break;
6374
6375  case OO_Exclaim:
6376    OpBuilder.addExclaimOverload();
6377    break;
6378
6379  case OO_AmpAmp:
6380  case OO_PipePipe:
6381    OpBuilder.addAmpAmpOrPipePipeOverload();
6382    break;
6383
6384  case OO_Subscript:
6385    OpBuilder.addSubscriptOverloads();
6386    break;
6387
6388  case OO_ArrowStar:
6389    OpBuilder.addArrowStarOverloads();
6390    break;
6391
6392  case OO_Conditional:
6393    OpBuilder.addConditionalOperatorOverloads();
6394    OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6395    break;
6396  }
6397}
6398
6399/// \brief Add function candidates found via argument-dependent lookup
6400/// to the set of overloading candidates.
6401///
6402/// This routine performs argument-dependent name lookup based on the
6403/// given function name (which may also be an operator name) and adds
6404/// all of the overload candidates found by ADL to the overload
6405/// candidate set (C++ [basic.lookup.argdep]).
6406void
6407Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
6408                                           bool Operator,
6409                                           Expr **Args, unsigned NumArgs,
6410                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
6411                                           OverloadCandidateSet& CandidateSet,
6412                                           bool PartialOverloading,
6413                                           bool StdNamespaceIsAssociated) {
6414  ADLResult Fns;
6415
6416  // FIXME: This approach for uniquing ADL results (and removing
6417  // redundant candidates from the set) relies on pointer-equality,
6418  // which means we need to key off the canonical decl.  However,
6419  // always going back to the canonical decl might not get us the
6420  // right set of default arguments.  What default arguments are
6421  // we supposed to consider on ADL candidates, anyway?
6422
6423  // FIXME: Pass in the explicit template arguments?
6424  ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6425                          StdNamespaceIsAssociated);
6426
6427  // Erase all of the candidates we already knew about.
6428  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6429                                   CandEnd = CandidateSet.end();
6430       Cand != CandEnd; ++Cand)
6431    if (Cand->Function) {
6432      Fns.erase(Cand->Function);
6433      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
6434        Fns.erase(FunTmpl);
6435    }
6436
6437  // For each of the ADL candidates we found, add it to the overload
6438  // set.
6439  for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
6440    DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
6441    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
6442      if (ExplicitTemplateArgs)
6443        continue;
6444
6445      AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
6446                           false, PartialOverloading);
6447    } else
6448      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
6449                                   FoundDecl, ExplicitTemplateArgs,
6450                                   Args, NumArgs, CandidateSet);
6451  }
6452}
6453
6454/// isBetterOverloadCandidate - Determines whether the first overload
6455/// candidate is a better candidate than the second (C++ 13.3.3p1).
6456bool
6457isBetterOverloadCandidate(Sema &S,
6458                          const OverloadCandidate &Cand1,
6459                          const OverloadCandidate &Cand2,
6460                          SourceLocation Loc,
6461                          bool UserDefinedConversion) {
6462  // Define viable functions to be better candidates than non-viable
6463  // functions.
6464  if (!Cand2.Viable)
6465    return Cand1.Viable;
6466  else if (!Cand1.Viable)
6467    return false;
6468
6469  // C++ [over.match.best]p1:
6470  //
6471  //   -- if F is a static member function, ICS1(F) is defined such
6472  //      that ICS1(F) is neither better nor worse than ICS1(G) for
6473  //      any function G, and, symmetrically, ICS1(G) is neither
6474  //      better nor worse than ICS1(F).
6475  unsigned StartArg = 0;
6476  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6477    StartArg = 1;
6478
6479  // C++ [over.match.best]p1:
6480  //   A viable function F1 is defined to be a better function than another
6481  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
6482  //   conversion sequence than ICSi(F2), and then...
6483  unsigned NumArgs = Cand1.Conversions.size();
6484  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6485  bool HasBetterConversion = false;
6486  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
6487    switch (CompareImplicitConversionSequences(S,
6488                                               Cand1.Conversions[ArgIdx],
6489                                               Cand2.Conversions[ArgIdx])) {
6490    case ImplicitConversionSequence::Better:
6491      // Cand1 has a better conversion sequence.
6492      HasBetterConversion = true;
6493      break;
6494
6495    case ImplicitConversionSequence::Worse:
6496      // Cand1 can't be better than Cand2.
6497      return false;
6498
6499    case ImplicitConversionSequence::Indistinguishable:
6500      // Do nothing.
6501      break;
6502    }
6503  }
6504
6505  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
6506  //       ICSj(F2), or, if not that,
6507  if (HasBetterConversion)
6508    return true;
6509
6510  //     - F1 is a non-template function and F2 is a function template
6511  //       specialization, or, if not that,
6512  if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
6513      Cand2.Function && Cand2.Function->getPrimaryTemplate())
6514    return true;
6515
6516  //   -- F1 and F2 are function template specializations, and the function
6517  //      template for F1 is more specialized than the template for F2
6518  //      according to the partial ordering rules described in 14.5.5.2, or,
6519  //      if not that,
6520  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
6521      Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
6522    if (FunctionTemplateDecl *BetterTemplate
6523          = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6524                                         Cand2.Function->getPrimaryTemplate(),
6525                                         Loc,
6526                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
6527                                                             : TPOC_Call,
6528                                         Cand1.ExplicitCallArguments))
6529      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
6530  }
6531
6532  //   -- the context is an initialization by user-defined conversion
6533  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
6534  //      from the return type of F1 to the destination type (i.e.,
6535  //      the type of the entity being initialized) is a better
6536  //      conversion sequence than the standard conversion sequence
6537  //      from the return type of F2 to the destination type.
6538  if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
6539      isa<CXXConversionDecl>(Cand1.Function) &&
6540      isa<CXXConversionDecl>(Cand2.Function)) {
6541    switch (CompareStandardConversionSequences(S,
6542                                               Cand1.FinalConversion,
6543                                               Cand2.FinalConversion)) {
6544    case ImplicitConversionSequence::Better:
6545      // Cand1 has a better conversion sequence.
6546      return true;
6547
6548    case ImplicitConversionSequence::Worse:
6549      // Cand1 can't be better than Cand2.
6550      return false;
6551
6552    case ImplicitConversionSequence::Indistinguishable:
6553      // Do nothing
6554      break;
6555    }
6556  }
6557
6558  return false;
6559}
6560
6561/// \brief Computes the best viable function (C++ 13.3.3)
6562/// within an overload candidate set.
6563///
6564/// \param CandidateSet the set of candidate functions.
6565///
6566/// \param Loc the location of the function name (or operator symbol) for
6567/// which overload resolution occurs.
6568///
6569/// \param Best f overload resolution was successful or found a deleted
6570/// function, Best points to the candidate function found.
6571///
6572/// \returns The result of overload resolution.
6573OverloadingResult
6574OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
6575                                         iterator &Best,
6576                                         bool UserDefinedConversion) {
6577  // Find the best viable function.
6578  Best = end();
6579  for (iterator Cand = begin(); Cand != end(); ++Cand) {
6580    if (Cand->Viable)
6581      if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6582                                                     UserDefinedConversion))
6583        Best = Cand;
6584  }
6585
6586  // If we didn't find any viable functions, abort.
6587  if (Best == end())
6588    return OR_No_Viable_Function;
6589
6590  // Make sure that this function is better than every other viable
6591  // function. If not, we have an ambiguity.
6592  for (iterator Cand = begin(); Cand != end(); ++Cand) {
6593    if (Cand->Viable &&
6594        Cand != Best &&
6595        !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6596                                   UserDefinedConversion)) {
6597      Best = end();
6598      return OR_Ambiguous;
6599    }
6600  }
6601
6602  // Best is the best viable function.
6603  if (Best->Function &&
6604      (Best->Function->isDeleted() ||
6605       S.isFunctionConsideredUnavailable(Best->Function)))
6606    return OR_Deleted;
6607
6608  return OR_Success;
6609}
6610
6611namespace {
6612
6613enum OverloadCandidateKind {
6614  oc_function,
6615  oc_method,
6616  oc_constructor,
6617  oc_function_template,
6618  oc_method_template,
6619  oc_constructor_template,
6620  oc_implicit_default_constructor,
6621  oc_implicit_copy_constructor,
6622  oc_implicit_move_constructor,
6623  oc_implicit_copy_assignment,
6624  oc_implicit_move_assignment,
6625  oc_implicit_inherited_constructor
6626};
6627
6628OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6629                                                FunctionDecl *Fn,
6630                                                std::string &Description) {
6631  bool isTemplate = false;
6632
6633  if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6634    isTemplate = true;
6635    Description = S.getTemplateArgumentBindingsText(
6636      FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6637  }
6638
6639  if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
6640    if (!Ctor->isImplicit())
6641      return isTemplate ? oc_constructor_template : oc_constructor;
6642
6643    if (Ctor->getInheritedConstructor())
6644      return oc_implicit_inherited_constructor;
6645
6646    if (Ctor->isDefaultConstructor())
6647      return oc_implicit_default_constructor;
6648
6649    if (Ctor->isMoveConstructor())
6650      return oc_implicit_move_constructor;
6651
6652    assert(Ctor->isCopyConstructor() &&
6653           "unexpected sort of implicit constructor");
6654    return oc_implicit_copy_constructor;
6655  }
6656
6657  if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6658    // This actually gets spelled 'candidate function' for now, but
6659    // it doesn't hurt to split it out.
6660    if (!Meth->isImplicit())
6661      return isTemplate ? oc_method_template : oc_method;
6662
6663    if (Meth->isMoveAssignmentOperator())
6664      return oc_implicit_move_assignment;
6665
6666    assert(Meth->isCopyAssignmentOperator()
6667           && "implicit method is not copy assignment operator?");
6668    return oc_implicit_copy_assignment;
6669  }
6670
6671  return isTemplate ? oc_function_template : oc_function;
6672}
6673
6674void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6675  const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6676  if (!Ctor) return;
6677
6678  Ctor = Ctor->getInheritedConstructor();
6679  if (!Ctor) return;
6680
6681  S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6682}
6683
6684} // end anonymous namespace
6685
6686// Notes the location of an overload candidate.
6687void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
6688  std::string FnDesc;
6689  OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6690  Diag(Fn->getLocation(), diag::note_ovl_candidate)
6691    << (unsigned) K << FnDesc;
6692  MaybeEmitInheritedConstructorNote(*this, Fn);
6693}
6694
6695//Notes the location of all overload candidates designated through
6696// OverloadedExpr
6697void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6698  assert(OverloadedExpr->getType() == Context.OverloadTy);
6699
6700  OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6701  OverloadExpr *OvlExpr = Ovl.Expression;
6702
6703  for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6704                            IEnd = OvlExpr->decls_end();
6705       I != IEnd; ++I) {
6706    if (FunctionTemplateDecl *FunTmpl =
6707                dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6708      NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6709    } else if (FunctionDecl *Fun
6710                      = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6711      NoteOverloadCandidate(Fun);
6712    }
6713  }
6714}
6715
6716/// Diagnoses an ambiguous conversion.  The partial diagnostic is the
6717/// "lead" diagnostic; it will be given two arguments, the source and
6718/// target types of the conversion.
6719void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6720                                 Sema &S,
6721                                 SourceLocation CaretLoc,
6722                                 const PartialDiagnostic &PDiag) const {
6723  S.Diag(CaretLoc, PDiag)
6724    << Ambiguous.getFromType() << Ambiguous.getToType();
6725  for (AmbiguousConversionSequence::const_iterator
6726         I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6727    S.NoteOverloadCandidate(*I);
6728  }
6729}
6730
6731namespace {
6732
6733void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6734  const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6735  assert(Conv.isBad());
6736  assert(Cand->Function && "for now, candidate must be a function");
6737  FunctionDecl *Fn = Cand->Function;
6738
6739  // There's a conversion slot for the object argument if this is a
6740  // non-constructor method.  Note that 'I' corresponds the
6741  // conversion-slot index.
6742  bool isObjectArgument = false;
6743  if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
6744    if (I == 0)
6745      isObjectArgument = true;
6746    else
6747      I--;
6748  }
6749
6750  std::string FnDesc;
6751  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6752
6753  Expr *FromExpr = Conv.Bad.FromExpr;
6754  QualType FromTy = Conv.Bad.getFromType();
6755  QualType ToTy = Conv.Bad.getToType();
6756
6757  if (FromTy == S.Context.OverloadTy) {
6758    assert(FromExpr && "overload set argument came from implicit argument?");
6759    Expr *E = FromExpr->IgnoreParens();
6760    if (isa<UnaryOperator>(E))
6761      E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
6762    DeclarationName Name = cast<OverloadExpr>(E)->getName();
6763
6764    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6765      << (unsigned) FnKind << FnDesc
6766      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6767      << ToTy << Name << I+1;
6768    MaybeEmitInheritedConstructorNote(S, Fn);
6769    return;
6770  }
6771
6772  // Do some hand-waving analysis to see if the non-viability is due
6773  // to a qualifier mismatch.
6774  CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6775  CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6776  if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6777    CToTy = RT->getPointeeType();
6778  else {
6779    // TODO: detect and diagnose the full richness of const mismatches.
6780    if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6781      if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6782        CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6783  }
6784
6785  if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6786      !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6787    // It is dumb that we have to do this here.
6788    while (isa<ArrayType>(CFromTy))
6789      CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6790    while (isa<ArrayType>(CToTy))
6791      CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6792
6793    Qualifiers FromQs = CFromTy.getQualifiers();
6794    Qualifiers ToQs = CToTy.getQualifiers();
6795
6796    if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6797      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6798        << (unsigned) FnKind << FnDesc
6799        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6800        << FromTy
6801        << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6802        << (unsigned) isObjectArgument << I+1;
6803      MaybeEmitInheritedConstructorNote(S, Fn);
6804      return;
6805    }
6806
6807    if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
6808      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
6809        << (unsigned) FnKind << FnDesc
6810        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6811        << FromTy
6812        << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6813        << (unsigned) isObjectArgument << I+1;
6814      MaybeEmitInheritedConstructorNote(S, Fn);
6815      return;
6816    }
6817
6818    if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6819      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6820      << (unsigned) FnKind << FnDesc
6821      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6822      << FromTy
6823      << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6824      << (unsigned) isObjectArgument << I+1;
6825      MaybeEmitInheritedConstructorNote(S, Fn);
6826      return;
6827    }
6828
6829    unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6830    assert(CVR && "unexpected qualifiers mismatch");
6831
6832    if (isObjectArgument) {
6833      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6834        << (unsigned) FnKind << FnDesc
6835        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6836        << FromTy << (CVR - 1);
6837    } else {
6838      S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6839        << (unsigned) FnKind << FnDesc
6840        << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6841        << FromTy << (CVR - 1) << I+1;
6842    }
6843    MaybeEmitInheritedConstructorNote(S, Fn);
6844    return;
6845  }
6846
6847  // Diagnose references or pointers to incomplete types differently,
6848  // since it's far from impossible that the incompleteness triggered
6849  // the failure.
6850  QualType TempFromTy = FromTy.getNonReferenceType();
6851  if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6852    TempFromTy = PTy->getPointeeType();
6853  if (TempFromTy->isIncompleteType()) {
6854    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6855      << (unsigned) FnKind << FnDesc
6856      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6857      << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6858    MaybeEmitInheritedConstructorNote(S, Fn);
6859    return;
6860  }
6861
6862  // Diagnose base -> derived pointer conversions.
6863  unsigned BaseToDerivedConversion = 0;
6864  if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6865    if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6866      if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6867                                               FromPtrTy->getPointeeType()) &&
6868          !FromPtrTy->getPointeeType()->isIncompleteType() &&
6869          !ToPtrTy->getPointeeType()->isIncompleteType() &&
6870          S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6871                          FromPtrTy->getPointeeType()))
6872        BaseToDerivedConversion = 1;
6873    }
6874  } else if (const ObjCObjectPointerType *FromPtrTy
6875                                    = FromTy->getAs<ObjCObjectPointerType>()) {
6876    if (const ObjCObjectPointerType *ToPtrTy
6877                                        = ToTy->getAs<ObjCObjectPointerType>())
6878      if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6879        if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6880          if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6881                                                FromPtrTy->getPointeeType()) &&
6882              FromIface->isSuperClassOf(ToIface))
6883            BaseToDerivedConversion = 2;
6884  } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6885      if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6886          !FromTy->isIncompleteType() &&
6887          !ToRefTy->getPointeeType()->isIncompleteType() &&
6888          S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6889        BaseToDerivedConversion = 3;
6890    }
6891
6892  if (BaseToDerivedConversion) {
6893    S.Diag(Fn->getLocation(),
6894           diag::note_ovl_candidate_bad_base_to_derived_conv)
6895      << (unsigned) FnKind << FnDesc
6896      << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6897      << (BaseToDerivedConversion - 1)
6898      << FromTy << ToTy << I+1;
6899    MaybeEmitInheritedConstructorNote(S, Fn);
6900    return;
6901  }
6902
6903  // TODO: specialize more based on the kind of mismatch
6904  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6905    << (unsigned) FnKind << FnDesc
6906    << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6907    << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6908  MaybeEmitInheritedConstructorNote(S, Fn);
6909}
6910
6911void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6912                           unsigned NumFormalArgs) {
6913  // TODO: treat calls to a missing default constructor as a special case
6914
6915  FunctionDecl *Fn = Cand->Function;
6916  const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6917
6918  unsigned MinParams = Fn->getMinRequiredArguments();
6919
6920  // With invalid overloaded operators, it's possible that we think we
6921  // have an arity mismatch when it fact it looks like we have the
6922  // right number of arguments, because only overloaded operators have
6923  // the weird behavior of overloading member and non-member functions.
6924  // Just don't report anything.
6925  if (Fn->isInvalidDecl() &&
6926      Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6927    return;
6928
6929  // at least / at most / exactly
6930  unsigned mode, modeCount;
6931  if (NumFormalArgs < MinParams) {
6932    assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6933           (Cand->FailureKind == ovl_fail_bad_deduction &&
6934            Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
6935    if (MinParams != FnTy->getNumArgs() ||
6936        FnTy->isVariadic() || FnTy->isTemplateVariadic())
6937      mode = 0; // "at least"
6938    else
6939      mode = 2; // "exactly"
6940    modeCount = MinParams;
6941  } else {
6942    assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6943           (Cand->FailureKind == ovl_fail_bad_deduction &&
6944            Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
6945    if (MinParams != FnTy->getNumArgs())
6946      mode = 1; // "at most"
6947    else
6948      mode = 2; // "exactly"
6949    modeCount = FnTy->getNumArgs();
6950  }
6951
6952  std::string Description;
6953  OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6954
6955  S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
6956    << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6957    << modeCount << NumFormalArgs;
6958  MaybeEmitInheritedConstructorNote(S, Fn);
6959}
6960
6961/// Diagnose a failed template-argument deduction.
6962void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6963                          Expr **Args, unsigned NumArgs) {
6964  FunctionDecl *Fn = Cand->Function; // pattern
6965
6966  TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
6967  NamedDecl *ParamD;
6968  (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6969  (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6970  (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
6971  switch (Cand->DeductionFailure.Result) {
6972  case Sema::TDK_Success:
6973    llvm_unreachable("TDK_success while diagnosing bad deduction");
6974
6975  case Sema::TDK_Incomplete: {
6976    assert(ParamD && "no parameter found for incomplete deduction result");
6977    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6978      << ParamD->getDeclName();
6979    MaybeEmitInheritedConstructorNote(S, Fn);
6980    return;
6981  }
6982
6983  case Sema::TDK_Underqualified: {
6984    assert(ParamD && "no parameter found for bad qualifiers deduction result");
6985    TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6986
6987    QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6988
6989    // Param will have been canonicalized, but it should just be a
6990    // qualified version of ParamD, so move the qualifiers to that.
6991    QualifierCollector Qs;
6992    Qs.strip(Param);
6993    QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
6994    assert(S.Context.hasSameType(Param, NonCanonParam));
6995
6996    // Arg has also been canonicalized, but there's nothing we can do
6997    // about that.  It also doesn't matter as much, because it won't
6998    // have any template parameters in it (because deduction isn't
6999    // done on dependent types).
7000    QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7001
7002    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7003      << ParamD->getDeclName() << Arg << NonCanonParam;
7004    MaybeEmitInheritedConstructorNote(S, Fn);
7005    return;
7006  }
7007
7008  case Sema::TDK_Inconsistent: {
7009    assert(ParamD && "no parameter found for inconsistent deduction result");
7010    int which = 0;
7011    if (isa<TemplateTypeParmDecl>(ParamD))
7012      which = 0;
7013    else if (isa<NonTypeTemplateParmDecl>(ParamD))
7014      which = 1;
7015    else {
7016      which = 2;
7017    }
7018
7019    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
7020      << which << ParamD->getDeclName()
7021      << *Cand->DeductionFailure.getFirstArg()
7022      << *Cand->DeductionFailure.getSecondArg();
7023    MaybeEmitInheritedConstructorNote(S, Fn);
7024    return;
7025  }
7026
7027  case Sema::TDK_InvalidExplicitArguments:
7028    assert(ParamD && "no parameter found for invalid explicit arguments");
7029    if (ParamD->getDeclName())
7030      S.Diag(Fn->getLocation(),
7031             diag::note_ovl_candidate_explicit_arg_mismatch_named)
7032        << ParamD->getDeclName();
7033    else {
7034      int index = 0;
7035      if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7036        index = TTP->getIndex();
7037      else if (NonTypeTemplateParmDecl *NTTP
7038                                  = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7039        index = NTTP->getIndex();
7040      else
7041        index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
7042      S.Diag(Fn->getLocation(),
7043             diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7044        << (index + 1);
7045    }
7046    MaybeEmitInheritedConstructorNote(S, Fn);
7047    return;
7048
7049  case Sema::TDK_TooManyArguments:
7050  case Sema::TDK_TooFewArguments:
7051    DiagnoseArityMismatch(S, Cand, NumArgs);
7052    return;
7053
7054  case Sema::TDK_InstantiationDepth:
7055    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
7056    MaybeEmitInheritedConstructorNote(S, Fn);
7057    return;
7058
7059  case Sema::TDK_SubstitutionFailure: {
7060    std::string ArgString;
7061    if (TemplateArgumentList *Args
7062                            = Cand->DeductionFailure.getTemplateArgumentList())
7063      ArgString = S.getTemplateArgumentBindingsText(
7064                    Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7065                                                    *Args);
7066    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7067      << ArgString;
7068    MaybeEmitInheritedConstructorNote(S, Fn);
7069    return;
7070  }
7071
7072  // TODO: diagnose these individually, then kill off
7073  // note_ovl_candidate_bad_deduction, which is uselessly vague.
7074  case Sema::TDK_NonDeducedMismatch:
7075  case Sema::TDK_FailedOverloadResolution:
7076    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
7077    MaybeEmitInheritedConstructorNote(S, Fn);
7078    return;
7079  }
7080}
7081
7082/// Generates a 'note' diagnostic for an overload candidate.  We've
7083/// already generated a primary error at the call site.
7084///
7085/// It really does need to be a single diagnostic with its caret
7086/// pointed at the candidate declaration.  Yes, this creates some
7087/// major challenges of technical writing.  Yes, this makes pointing
7088/// out problems with specific arguments quite awkward.  It's still
7089/// better than generating twenty screens of text for every failed
7090/// overload.
7091///
7092/// It would be great to be able to express per-candidate problems
7093/// more richly for those diagnostic clients that cared, but we'd
7094/// still have to be just as careful with the default diagnostics.
7095void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7096                           Expr **Args, unsigned NumArgs) {
7097  FunctionDecl *Fn = Cand->Function;
7098
7099  // Note deleted candidates, but only if they're viable.
7100  if (Cand->Viable && (Fn->isDeleted() ||
7101      S.isFunctionConsideredUnavailable(Fn))) {
7102    std::string FnDesc;
7103    OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7104
7105    S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
7106      << FnKind << FnDesc << Fn->isDeleted();
7107    MaybeEmitInheritedConstructorNote(S, Fn);
7108    return;
7109  }
7110
7111  // We don't really have anything else to say about viable candidates.
7112  if (Cand->Viable) {
7113    S.NoteOverloadCandidate(Fn);
7114    return;
7115  }
7116
7117  switch (Cand->FailureKind) {
7118  case ovl_fail_too_many_arguments:
7119  case ovl_fail_too_few_arguments:
7120    return DiagnoseArityMismatch(S, Cand, NumArgs);
7121
7122  case ovl_fail_bad_deduction:
7123    return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7124
7125  case ovl_fail_trivial_conversion:
7126  case ovl_fail_bad_final_conversion:
7127  case ovl_fail_final_conversion_not_exact:
7128    return S.NoteOverloadCandidate(Fn);
7129
7130  case ovl_fail_bad_conversion: {
7131    unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7132    for (unsigned N = Cand->Conversions.size(); I != N; ++I)
7133      if (Cand->Conversions[I].isBad())
7134        return DiagnoseBadConversion(S, Cand, I);
7135
7136    // FIXME: this currently happens when we're called from SemaInit
7137    // when user-conversion overload fails.  Figure out how to handle
7138    // those conditions and diagnose them well.
7139    return S.NoteOverloadCandidate(Fn);
7140  }
7141  }
7142}
7143
7144void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7145  // Desugar the type of the surrogate down to a function type,
7146  // retaining as many typedefs as possible while still showing
7147  // the function type (and, therefore, its parameter types).
7148  QualType FnType = Cand->Surrogate->getConversionType();
7149  bool isLValueReference = false;
7150  bool isRValueReference = false;
7151  bool isPointer = false;
7152  if (const LValueReferenceType *FnTypeRef =
7153        FnType->getAs<LValueReferenceType>()) {
7154    FnType = FnTypeRef->getPointeeType();
7155    isLValueReference = true;
7156  } else if (const RValueReferenceType *FnTypeRef =
7157               FnType->getAs<RValueReferenceType>()) {
7158    FnType = FnTypeRef->getPointeeType();
7159    isRValueReference = true;
7160  }
7161  if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7162    FnType = FnTypePtr->getPointeeType();
7163    isPointer = true;
7164  }
7165  // Desugar down to a function type.
7166  FnType = QualType(FnType->getAs<FunctionType>(), 0);
7167  // Reconstruct the pointer/reference as appropriate.
7168  if (isPointer) FnType = S.Context.getPointerType(FnType);
7169  if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7170  if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7171
7172  S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7173    << FnType;
7174  MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
7175}
7176
7177void NoteBuiltinOperatorCandidate(Sema &S,
7178                                  const char *Opc,
7179                                  SourceLocation OpLoc,
7180                                  OverloadCandidate *Cand) {
7181  assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7182  std::string TypeStr("operator");
7183  TypeStr += Opc;
7184  TypeStr += "(";
7185  TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7186  if (Cand->Conversions.size() == 1) {
7187    TypeStr += ")";
7188    S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7189  } else {
7190    TypeStr += ", ";
7191    TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7192    TypeStr += ")";
7193    S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7194  }
7195}
7196
7197void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7198                                  OverloadCandidate *Cand) {
7199  unsigned NoOperands = Cand->Conversions.size();
7200  for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7201    const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
7202    if (ICS.isBad()) break; // all meaningless after first invalid
7203    if (!ICS.isAmbiguous()) continue;
7204
7205    ICS.DiagnoseAmbiguousConversion(S, OpLoc,
7206                              S.PDiag(diag::note_ambiguous_type_conversion));
7207  }
7208}
7209
7210SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7211  if (Cand->Function)
7212    return Cand->Function->getLocation();
7213  if (Cand->IsSurrogate)
7214    return Cand->Surrogate->getLocation();
7215  return SourceLocation();
7216}
7217
7218struct CompareOverloadCandidatesForDisplay {
7219  Sema &S;
7220  CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
7221
7222  bool operator()(const OverloadCandidate *L,
7223                  const OverloadCandidate *R) {
7224    // Fast-path this check.
7225    if (L == R) return false;
7226
7227    // Order first by viability.
7228    if (L->Viable) {
7229      if (!R->Viable) return true;
7230
7231      // TODO: introduce a tri-valued comparison for overload
7232      // candidates.  Would be more worthwhile if we had a sort
7233      // that could exploit it.
7234      if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7235      if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
7236    } else if (R->Viable)
7237      return false;
7238
7239    assert(L->Viable == R->Viable);
7240
7241    // Criteria by which we can sort non-viable candidates:
7242    if (!L->Viable) {
7243      // 1. Arity mismatches come after other candidates.
7244      if (L->FailureKind == ovl_fail_too_many_arguments ||
7245          L->FailureKind == ovl_fail_too_few_arguments)
7246        return false;
7247      if (R->FailureKind == ovl_fail_too_many_arguments ||
7248          R->FailureKind == ovl_fail_too_few_arguments)
7249        return true;
7250
7251      // 2. Bad conversions come first and are ordered by the number
7252      // of bad conversions and quality of good conversions.
7253      if (L->FailureKind == ovl_fail_bad_conversion) {
7254        if (R->FailureKind != ovl_fail_bad_conversion)
7255          return true;
7256
7257        // If there's any ordering between the defined conversions...
7258        // FIXME: this might not be transitive.
7259        assert(L->Conversions.size() == R->Conversions.size());
7260
7261        int leftBetter = 0;
7262        unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7263        for (unsigned E = L->Conversions.size(); I != E; ++I) {
7264          switch (CompareImplicitConversionSequences(S,
7265                                                     L->Conversions[I],
7266                                                     R->Conversions[I])) {
7267          case ImplicitConversionSequence::Better:
7268            leftBetter++;
7269            break;
7270
7271          case ImplicitConversionSequence::Worse:
7272            leftBetter--;
7273            break;
7274
7275          case ImplicitConversionSequence::Indistinguishable:
7276            break;
7277          }
7278        }
7279        if (leftBetter > 0) return true;
7280        if (leftBetter < 0) return false;
7281
7282      } else if (R->FailureKind == ovl_fail_bad_conversion)
7283        return false;
7284
7285      // TODO: others?
7286    }
7287
7288    // Sort everything else by location.
7289    SourceLocation LLoc = GetLocationForCandidate(L);
7290    SourceLocation RLoc = GetLocationForCandidate(R);
7291
7292    // Put candidates without locations (e.g. builtins) at the end.
7293    if (LLoc.isInvalid()) return false;
7294    if (RLoc.isInvalid()) return true;
7295
7296    return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
7297  }
7298};
7299
7300/// CompleteNonViableCandidate - Normally, overload resolution only
7301/// computes up to the first
7302void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7303                                Expr **Args, unsigned NumArgs) {
7304  assert(!Cand->Viable);
7305
7306  // Don't do anything on failures other than bad conversion.
7307  if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7308
7309  // Skip forward to the first bad conversion.
7310  unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
7311  unsigned ConvCount = Cand->Conversions.size();
7312  while (true) {
7313    assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7314    ConvIdx++;
7315    if (Cand->Conversions[ConvIdx - 1].isBad())
7316      break;
7317  }
7318
7319  if (ConvIdx == ConvCount)
7320    return;
7321
7322  assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7323         "remaining conversion is initialized?");
7324
7325  // FIXME: this should probably be preserved from the overload
7326  // operation somehow.
7327  bool SuppressUserConversions = false;
7328
7329  const FunctionProtoType* Proto;
7330  unsigned ArgIdx = ConvIdx;
7331
7332  if (Cand->IsSurrogate) {
7333    QualType ConvType
7334      = Cand->Surrogate->getConversionType().getNonReferenceType();
7335    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7336      ConvType = ConvPtrType->getPointeeType();
7337    Proto = ConvType->getAs<FunctionProtoType>();
7338    ArgIdx--;
7339  } else if (Cand->Function) {
7340    Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7341    if (isa<CXXMethodDecl>(Cand->Function) &&
7342        !isa<CXXConstructorDecl>(Cand->Function))
7343      ArgIdx--;
7344  } else {
7345    // Builtin binary operator with a bad first conversion.
7346    assert(ConvCount <= 3);
7347    for (; ConvIdx != ConvCount; ++ConvIdx)
7348      Cand->Conversions[ConvIdx]
7349        = TryCopyInitialization(S, Args[ConvIdx],
7350                                Cand->BuiltinTypes.ParamTypes[ConvIdx],
7351                                SuppressUserConversions,
7352                                /*InOverloadResolution*/ true,
7353                                /*AllowObjCWritebackConversion=*/
7354                                  S.getLangOptions().ObjCAutoRefCount);
7355    return;
7356  }
7357
7358  // Fill in the rest of the conversions.
7359  unsigned NumArgsInProto = Proto->getNumArgs();
7360  for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7361    if (ArgIdx < NumArgsInProto)
7362      Cand->Conversions[ConvIdx]
7363        = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
7364                                SuppressUserConversions,
7365                                /*InOverloadResolution=*/true,
7366                                /*AllowObjCWritebackConversion=*/
7367                                  S.getLangOptions().ObjCAutoRefCount);
7368    else
7369      Cand->Conversions[ConvIdx].setEllipsis();
7370  }
7371}
7372
7373} // end anonymous namespace
7374
7375/// PrintOverloadCandidates - When overload resolution fails, prints
7376/// diagnostic messages containing the candidates in the candidate
7377/// set.
7378void OverloadCandidateSet::NoteCandidates(Sema &S,
7379                                          OverloadCandidateDisplayKind OCD,
7380                                          Expr **Args, unsigned NumArgs,
7381                                          const char *Opc,
7382                                          SourceLocation OpLoc) {
7383  // Sort the candidates by viability and position.  Sorting directly would
7384  // be prohibitive, so we make a set of pointers and sort those.
7385  llvm::SmallVector<OverloadCandidate*, 32> Cands;
7386  if (OCD == OCD_AllCandidates) Cands.reserve(size());
7387  for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
7388    if (Cand->Viable)
7389      Cands.push_back(Cand);
7390    else if (OCD == OCD_AllCandidates) {
7391      CompleteNonViableCandidate(S, Cand, Args, NumArgs);
7392      if (Cand->Function || Cand->IsSurrogate)
7393        Cands.push_back(Cand);
7394      // Otherwise, this a non-viable builtin candidate.  We do not, in general,
7395      // want to list every possible builtin candidate.
7396    }
7397  }
7398
7399  std::sort(Cands.begin(), Cands.end(),
7400            CompareOverloadCandidatesForDisplay(S));
7401
7402  bool ReportedAmbiguousConversions = false;
7403
7404  llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
7405  const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
7406  unsigned CandsShown = 0;
7407  for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7408    OverloadCandidate *Cand = *I;
7409
7410    // Set an arbitrary limit on the number of candidate functions we'll spam
7411    // the user with.  FIXME: This limit should depend on details of the
7412    // candidate list.
7413    if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7414      break;
7415    }
7416    ++CandsShown;
7417
7418    if (Cand->Function)
7419      NoteFunctionCandidate(S, Cand, Args, NumArgs);
7420    else if (Cand->IsSurrogate)
7421      NoteSurrogateCandidate(S, Cand);
7422    else {
7423      assert(Cand->Viable &&
7424             "Non-viable built-in candidates are not added to Cands.");
7425      // Generally we only see ambiguities including viable builtin
7426      // operators if overload resolution got screwed up by an
7427      // ambiguous user-defined conversion.
7428      //
7429      // FIXME: It's quite possible for different conversions to see
7430      // different ambiguities, though.
7431      if (!ReportedAmbiguousConversions) {
7432        NoteAmbiguousUserConversions(S, OpLoc, Cand);
7433        ReportedAmbiguousConversions = true;
7434      }
7435
7436      // If this is a viable builtin, print it.
7437      NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
7438    }
7439  }
7440
7441  if (I != E)
7442    S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
7443}
7444
7445// [PossiblyAFunctionType]  -->   [Return]
7446// NonFunctionType --> NonFunctionType
7447// R (A) --> R(A)
7448// R (*)(A) --> R (A)
7449// R (&)(A) --> R (A)
7450// R (S::*)(A) --> R (A)
7451QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7452  QualType Ret = PossiblyAFunctionType;
7453  if (const PointerType *ToTypePtr =
7454    PossiblyAFunctionType->getAs<PointerType>())
7455    Ret = ToTypePtr->getPointeeType();
7456  else if (const ReferenceType *ToTypeRef =
7457    PossiblyAFunctionType->getAs<ReferenceType>())
7458    Ret = ToTypeRef->getPointeeType();
7459  else if (const MemberPointerType *MemTypePtr =
7460    PossiblyAFunctionType->getAs<MemberPointerType>())
7461    Ret = MemTypePtr->getPointeeType();
7462  Ret =
7463    Context.getCanonicalType(Ret).getUnqualifiedType();
7464  return Ret;
7465}
7466
7467// A helper class to help with address of function resolution
7468// - allows us to avoid passing around all those ugly parameters
7469class AddressOfFunctionResolver
7470{
7471  Sema& S;
7472  Expr* SourceExpr;
7473  const QualType& TargetType;
7474  QualType TargetFunctionType; // Extracted function type from target type
7475
7476  bool Complain;
7477  //DeclAccessPair& ResultFunctionAccessPair;
7478  ASTContext& Context;
7479
7480  bool TargetTypeIsNonStaticMemberFunction;
7481  bool FoundNonTemplateFunction;
7482
7483  OverloadExpr::FindResult OvlExprInfo;
7484  OverloadExpr *OvlExpr;
7485  TemplateArgumentListInfo OvlExplicitTemplateArgs;
7486  llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
7487
7488public:
7489  AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7490                            const QualType& TargetType, bool Complain)
7491    : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7492      Complain(Complain), Context(S.getASTContext()),
7493      TargetTypeIsNonStaticMemberFunction(
7494                                    !!TargetType->getAs<MemberPointerType>()),
7495      FoundNonTemplateFunction(false),
7496      OvlExprInfo(OverloadExpr::find(SourceExpr)),
7497      OvlExpr(OvlExprInfo.Expression)
7498  {
7499    ExtractUnqualifiedFunctionTypeFromTargetType();
7500
7501    if (!TargetFunctionType->isFunctionType()) {
7502      if (OvlExpr->hasExplicitTemplateArgs()) {
7503        DeclAccessPair dap;
7504        if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7505                                            OvlExpr, false, &dap) ) {
7506
7507          if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7508            if (!Method->isStatic()) {
7509              // If the target type is a non-function type and the function
7510              // found is a non-static member function, pretend as if that was
7511              // the target, it's the only possible type to end up with.
7512              TargetTypeIsNonStaticMemberFunction = true;
7513
7514              // And skip adding the function if its not in the proper form.
7515              // We'll diagnose this due to an empty set of functions.
7516              if (!OvlExprInfo.HasFormOfMemberPointer)
7517                return;
7518            }
7519          }
7520
7521          Matches.push_back(std::make_pair(dap,Fn));
7522        }
7523      }
7524      return;
7525    }
7526
7527    if (OvlExpr->hasExplicitTemplateArgs())
7528      OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
7529
7530    if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7531      // C++ [over.over]p4:
7532      //   If more than one function is selected, [...]
7533      if (Matches.size() > 1) {
7534        if (FoundNonTemplateFunction)
7535          EliminateAllTemplateMatches();
7536        else
7537          EliminateAllExceptMostSpecializedTemplate();
7538      }
7539    }
7540  }
7541
7542private:
7543  bool isTargetTypeAFunction() const {
7544    return TargetFunctionType->isFunctionType();
7545  }
7546
7547  // [ToType]     [Return]
7548
7549  // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7550  // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7551  // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7552  void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7553    TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7554  }
7555
7556  // return true if any matching specializations were found
7557  bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7558                                   const DeclAccessPair& CurAccessFunPair) {
7559    if (CXXMethodDecl *Method
7560              = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7561      // Skip non-static function templates when converting to pointer, and
7562      // static when converting to member pointer.
7563      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7564        return false;
7565    }
7566    else if (TargetTypeIsNonStaticMemberFunction)
7567      return false;
7568
7569    // C++ [over.over]p2:
7570    //   If the name is a function template, template argument deduction is
7571    //   done (14.8.2.2), and if the argument deduction succeeds, the
7572    //   resulting template argument list is used to generate a single
7573    //   function template specialization, which is added to the set of
7574    //   overloaded functions considered.
7575    FunctionDecl *Specialization = 0;
7576    TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7577    if (Sema::TemplateDeductionResult Result
7578          = S.DeduceTemplateArguments(FunctionTemplate,
7579                                      &OvlExplicitTemplateArgs,
7580                                      TargetFunctionType, Specialization,
7581                                      Info)) {
7582      // FIXME: make a note of the failed deduction for diagnostics.
7583      (void)Result;
7584      return false;
7585    }
7586
7587    // Template argument deduction ensures that we have an exact match.
7588    // This function template specicalization works.
7589    Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7590    assert(TargetFunctionType
7591                      == Context.getCanonicalType(Specialization->getType()));
7592    Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7593    return true;
7594  }
7595
7596  bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7597                                      const DeclAccessPair& CurAccessFunPair) {
7598    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7599      // Skip non-static functions when converting to pointer, and static
7600      // when converting to member pointer.
7601      if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7602        return false;
7603    }
7604    else if (TargetTypeIsNonStaticMemberFunction)
7605      return false;
7606
7607    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
7608      QualType ResultTy;
7609      if (Context.hasSameUnqualifiedType(TargetFunctionType,
7610                                         FunDecl->getType()) ||
7611          S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7612                                 ResultTy)) {
7613        Matches.push_back(std::make_pair(CurAccessFunPair,
7614          cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
7615        FoundNonTemplateFunction = true;
7616        return true;
7617      }
7618    }
7619
7620    return false;
7621  }
7622
7623  bool FindAllFunctionsThatMatchTargetTypeExactly() {
7624    bool Ret = false;
7625
7626    // If the overload expression doesn't have the form of a pointer to
7627    // member, don't try to convert it to a pointer-to-member type.
7628    if (IsInvalidFormOfPointerToMemberFunction())
7629      return false;
7630
7631    for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7632                               E = OvlExpr->decls_end();
7633         I != E; ++I) {
7634      // Look through any using declarations to find the underlying function.
7635      NamedDecl *Fn = (*I)->getUnderlyingDecl();
7636
7637      // C++ [over.over]p3:
7638      //   Non-member functions and static member functions match
7639      //   targets of type "pointer-to-function" or "reference-to-function."
7640      //   Nonstatic member functions match targets of
7641      //   type "pointer-to-member-function."
7642      // Note that according to DR 247, the containing class does not matter.
7643      if (FunctionTemplateDecl *FunctionTemplate
7644                                        = dyn_cast<FunctionTemplateDecl>(Fn)) {
7645        if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7646          Ret = true;
7647      }
7648      // If we have explicit template arguments supplied, skip non-templates.
7649      else if (!OvlExpr->hasExplicitTemplateArgs() &&
7650               AddMatchingNonTemplateFunction(Fn, I.getPair()))
7651        Ret = true;
7652    }
7653    assert(Ret || Matches.empty());
7654    return Ret;
7655  }
7656
7657  void EliminateAllExceptMostSpecializedTemplate() {
7658    //   [...] and any given function template specialization F1 is
7659    //   eliminated if the set contains a second function template
7660    //   specialization whose function template is more specialized
7661    //   than the function template of F1 according to the partial
7662    //   ordering rules of 14.5.5.2.
7663
7664    // The algorithm specified above is quadratic. We instead use a
7665    // two-pass algorithm (similar to the one used to identify the
7666    // best viable function in an overload set) that identifies the
7667    // best function template (if it exists).
7668
7669    UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7670    for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7671      MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
7672
7673    UnresolvedSetIterator Result =
7674      S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7675                           TPOC_Other, 0, SourceExpr->getLocStart(),
7676                           S.PDiag(),
7677                           S.PDiag(diag::err_addr_ovl_ambiguous)
7678                             << Matches[0].second->getDeclName(),
7679                           S.PDiag(diag::note_ovl_candidate)
7680                             << (unsigned) oc_function_template,
7681                           Complain);
7682
7683    if (Result != MatchesCopy.end()) {
7684      // Make it the first and only element
7685      Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7686      Matches[0].second = cast<FunctionDecl>(*Result);
7687      Matches.resize(1);
7688    }
7689  }
7690
7691  void EliminateAllTemplateMatches() {
7692    //   [...] any function template specializations in the set are
7693    //   eliminated if the set also contains a non-template function, [...]
7694    for (unsigned I = 0, N = Matches.size(); I != N; ) {
7695      if (Matches[I].second->getPrimaryTemplate() == 0)
7696        ++I;
7697      else {
7698        Matches[I] = Matches[--N];
7699        Matches.set_size(N);
7700      }
7701    }
7702  }
7703
7704public:
7705  void ComplainNoMatchesFound() const {
7706    assert(Matches.empty());
7707    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7708        << OvlExpr->getName() << TargetFunctionType
7709        << OvlExpr->getSourceRange();
7710    S.NoteAllOverloadCandidates(OvlExpr);
7711  }
7712
7713  bool IsInvalidFormOfPointerToMemberFunction() const {
7714    return TargetTypeIsNonStaticMemberFunction &&
7715      !OvlExprInfo.HasFormOfMemberPointer;
7716  }
7717
7718  void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7719      // TODO: Should we condition this on whether any functions might
7720      // have matched, or is it more appropriate to do that in callers?
7721      // TODO: a fixit wouldn't hurt.
7722      S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7723        << TargetType << OvlExpr->getSourceRange();
7724  }
7725
7726  void ComplainOfInvalidConversion() const {
7727    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7728      << OvlExpr->getName() << TargetType;
7729  }
7730
7731  void ComplainMultipleMatchesFound() const {
7732    assert(Matches.size() > 1);
7733    S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7734      << OvlExpr->getName()
7735      << OvlExpr->getSourceRange();
7736    S.NoteAllOverloadCandidates(OvlExpr);
7737  }
7738
7739  int getNumMatches() const { return Matches.size(); }
7740
7741  FunctionDecl* getMatchingFunctionDecl() const {
7742    if (Matches.size() != 1) return 0;
7743    return Matches[0].second;
7744  }
7745
7746  const DeclAccessPair* getMatchingFunctionAccessPair() const {
7747    if (Matches.size() != 1) return 0;
7748    return &Matches[0].first;
7749  }
7750};
7751
7752/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7753/// an overloaded function (C++ [over.over]), where @p From is an
7754/// expression with overloaded function type and @p ToType is the type
7755/// we're trying to resolve to. For example:
7756///
7757/// @code
7758/// int f(double);
7759/// int f(int);
7760///
7761/// int (*pfd)(double) = f; // selects f(double)
7762/// @endcode
7763///
7764/// This routine returns the resulting FunctionDecl if it could be
7765/// resolved, and NULL otherwise. When @p Complain is true, this
7766/// routine will emit diagnostics if there is an error.
7767FunctionDecl *
7768Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7769                                    bool Complain,
7770                                    DeclAccessPair &FoundResult) {
7771
7772  assert(AddressOfExpr->getType() == Context.OverloadTy);
7773
7774  AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7775  int NumMatches = Resolver.getNumMatches();
7776  FunctionDecl* Fn = 0;
7777  if ( NumMatches == 0 && Complain) {
7778    if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7779      Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7780    else
7781      Resolver.ComplainNoMatchesFound();
7782  }
7783  else if (NumMatches > 1 && Complain)
7784    Resolver.ComplainMultipleMatchesFound();
7785  else if (NumMatches == 1) {
7786    Fn = Resolver.getMatchingFunctionDecl();
7787    assert(Fn);
7788    FoundResult = *Resolver.getMatchingFunctionAccessPair();
7789    MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
7790    if (Complain)
7791      CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
7792  }
7793
7794  return Fn;
7795}
7796
7797/// \brief Given an expression that refers to an overloaded function, try to
7798/// resolve that overloaded function expression down to a single function.
7799///
7800/// This routine can only resolve template-ids that refer to a single function
7801/// template, where that template-id refers to a single template whose template
7802/// arguments are either provided by the template-id or have defaults,
7803/// as described in C++0x [temp.arg.explicit]p3.
7804FunctionDecl *
7805Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7806                                                  bool Complain,
7807                                                  DeclAccessPair *FoundResult) {
7808  // C++ [over.over]p1:
7809  //   [...] [Note: any redundant set of parentheses surrounding the
7810  //   overloaded function name is ignored (5.1). ]
7811  // C++ [over.over]p1:
7812  //   [...] The overloaded function name can be preceded by the &
7813  //   operator.
7814
7815  // If we didn't actually find any template-ids, we're done.
7816  if (!ovl->hasExplicitTemplateArgs())
7817    return 0;
7818
7819  TemplateArgumentListInfo ExplicitTemplateArgs;
7820  ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
7821
7822  // Look through all of the overloaded functions, searching for one
7823  // whose type matches exactly.
7824  FunctionDecl *Matched = 0;
7825  for (UnresolvedSetIterator I = ovl->decls_begin(),
7826         E = ovl->decls_end(); I != E; ++I) {
7827    // C++0x [temp.arg.explicit]p3:
7828    //   [...] In contexts where deduction is done and fails, or in contexts
7829    //   where deduction is not done, if a template argument list is
7830    //   specified and it, along with any default template arguments,
7831    //   identifies a single function template specialization, then the
7832    //   template-id is an lvalue for the function template specialization.
7833    FunctionTemplateDecl *FunctionTemplate
7834      = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
7835
7836    // C++ [over.over]p2:
7837    //   If the name is a function template, template argument deduction is
7838    //   done (14.8.2.2), and if the argument deduction succeeds, the
7839    //   resulting template argument list is used to generate a single
7840    //   function template specialization, which is added to the set of
7841    //   overloaded functions considered.
7842    FunctionDecl *Specialization = 0;
7843    TemplateDeductionInfo Info(Context, ovl->getNameLoc());
7844    if (TemplateDeductionResult Result
7845          = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7846                                    Specialization, Info)) {
7847      // FIXME: make a note of the failed deduction for diagnostics.
7848      (void)Result;
7849      continue;
7850    }
7851
7852    assert(Specialization && "no specialization and no error?");
7853
7854    // Multiple matches; we can't resolve to a single declaration.
7855    if (Matched) {
7856      if (Complain) {
7857        Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7858          << ovl->getName();
7859        NoteAllOverloadCandidates(ovl);
7860      }
7861      return 0;
7862    }
7863
7864    Matched = Specialization;
7865    if (FoundResult) *FoundResult = I.getPair();
7866  }
7867
7868  return Matched;
7869}
7870
7871
7872
7873
7874// Resolve and fix an overloaded expression that
7875// can be resolved because it identifies a single function
7876// template specialization
7877// Last three arguments should only be supplied if Complain = true
7878ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
7879             Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
7880                                  const SourceRange& OpRangeForComplaining,
7881                                           QualType DestTypeForComplaining,
7882                                            unsigned DiagIDForComplaining) {
7883  assert(SrcExpr->getType() == Context.OverloadTy);
7884
7885  OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
7886
7887  DeclAccessPair found;
7888  ExprResult SingleFunctionExpression;
7889  if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7890                           ovl.Expression, /*complain*/ false, &found)) {
7891    if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7892      return ExprError();
7893
7894    // It is only correct to resolve to an instance method if we're
7895    // resolving a form that's permitted to be a pointer to member.
7896    // Otherwise we'll end up making a bound member expression, which
7897    // is illegal in all the contexts we resolve like this.
7898    if (!ovl.HasFormOfMemberPointer &&
7899        isa<CXXMethodDecl>(fn) &&
7900        cast<CXXMethodDecl>(fn)->isInstance()) {
7901      if (complain) {
7902        Diag(ovl.Expression->getExprLoc(),
7903             diag::err_invalid_use_of_bound_member_func)
7904          << ovl.Expression->getSourceRange();
7905        // TODO: I believe we only end up here if there's a mix of
7906        // static and non-static candidates (otherwise the expression
7907        // would have 'bound member' type, not 'overload' type).
7908        // Ideally we would note which candidate was chosen and why
7909        // the static candidates were rejected.
7910      }
7911
7912      return ExprError();
7913    }
7914
7915    // Fix the expresion to refer to 'fn'.
7916    SingleFunctionExpression =
7917      Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7918
7919    // If desired, do function-to-pointer decay.
7920    if (doFunctionPointerConverion)
7921      SingleFunctionExpression =
7922        DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7923  }
7924
7925  if (!SingleFunctionExpression.isUsable()) {
7926    if (complain) {
7927      Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7928        << ovl.Expression->getName()
7929        << DestTypeForComplaining
7930        << OpRangeForComplaining
7931        << ovl.Expression->getQualifierLoc().getSourceRange();
7932      NoteAllOverloadCandidates(SrcExpr);
7933    }
7934    return ExprError();
7935  }
7936
7937  return SingleFunctionExpression;
7938}
7939
7940/// \brief Add a single candidate to the overload set.
7941static void AddOverloadedCallCandidate(Sema &S,
7942                                       DeclAccessPair FoundDecl,
7943                                 TemplateArgumentListInfo *ExplicitTemplateArgs,
7944                                       Expr **Args, unsigned NumArgs,
7945                                       OverloadCandidateSet &CandidateSet,
7946                                       bool PartialOverloading) {
7947  NamedDecl *Callee = FoundDecl.getDecl();
7948  if (isa<UsingShadowDecl>(Callee))
7949    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7950
7951  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
7952    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
7953    S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
7954                           false, PartialOverloading);
7955    return;
7956  }
7957
7958  if (FunctionTemplateDecl *FuncTemplate
7959      = dyn_cast<FunctionTemplateDecl>(Callee)) {
7960    S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7961                                   ExplicitTemplateArgs,
7962                                   Args, NumArgs, CandidateSet);
7963    return;
7964  }
7965
7966  assert(false && "unhandled case in overloaded call candidate");
7967
7968  // do nothing?
7969}
7970
7971/// \brief Add the overload candidates named by callee and/or found by argument
7972/// dependent lookup to the given overload set.
7973void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
7974                                       Expr **Args, unsigned NumArgs,
7975                                       OverloadCandidateSet &CandidateSet,
7976                                       bool PartialOverloading) {
7977
7978#ifndef NDEBUG
7979  // Verify that ArgumentDependentLookup is consistent with the rules
7980  // in C++0x [basic.lookup.argdep]p3:
7981  //
7982  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
7983  //   and let Y be the lookup set produced by argument dependent
7984  //   lookup (defined as follows). If X contains
7985  //
7986  //     -- a declaration of a class member, or
7987  //
7988  //     -- a block-scope function declaration that is not a
7989  //        using-declaration, or
7990  //
7991  //     -- a declaration that is neither a function or a function
7992  //        template
7993  //
7994  //   then Y is empty.
7995
7996  if (ULE->requiresADL()) {
7997    for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7998           E = ULE->decls_end(); I != E; ++I) {
7999      assert(!(*I)->getDeclContext()->isRecord());
8000      assert(isa<UsingShadowDecl>(*I) ||
8001             !(*I)->getDeclContext()->isFunctionOrMethod());
8002      assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
8003    }
8004  }
8005#endif
8006
8007  // It would be nice to avoid this copy.
8008  TemplateArgumentListInfo TABuffer;
8009  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
8010  if (ULE->hasExplicitTemplateArgs()) {
8011    ULE->copyTemplateArgumentsInto(TABuffer);
8012    ExplicitTemplateArgs = &TABuffer;
8013  }
8014
8015  for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8016         E = ULE->decls_end(); I != E; ++I)
8017    AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
8018                               Args, NumArgs, CandidateSet,
8019                               PartialOverloading);
8020
8021  if (ULE->requiresADL())
8022    AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8023                                         Args, NumArgs,
8024                                         ExplicitTemplateArgs,
8025                                         CandidateSet,
8026                                         PartialOverloading,
8027                                         ULE->isStdAssociatedNamespace());
8028}
8029
8030/// Attempt to recover from an ill-formed use of a non-dependent name in a
8031/// template, where the non-dependent name was declared after the template
8032/// was defined. This is common in code written for a compilers which do not
8033/// correctly implement two-stage name lookup.
8034///
8035/// Returns true if a viable candidate was found and a diagnostic was issued.
8036static bool
8037DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8038                       const CXXScopeSpec &SS, LookupResult &R,
8039                       TemplateArgumentListInfo *ExplicitTemplateArgs,
8040                       Expr **Args, unsigned NumArgs) {
8041  if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8042    return false;
8043
8044  for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8045    SemaRef.LookupQualifiedName(R, DC);
8046
8047    if (!R.empty()) {
8048      R.suppressDiagnostics();
8049
8050      if (isa<CXXRecordDecl>(DC)) {
8051        // Don't diagnose names we find in classes; we get much better
8052        // diagnostics for these from DiagnoseEmptyLookup.
8053        R.clear();
8054        return false;
8055      }
8056
8057      OverloadCandidateSet Candidates(FnLoc);
8058      for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8059        AddOverloadedCallCandidate(SemaRef, I.getPair(),
8060                                   ExplicitTemplateArgs, Args, NumArgs,
8061                                   Candidates, false);
8062
8063      OverloadCandidateSet::iterator Best;
8064      if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success)
8065        // No viable functions. Don't bother the user with notes for functions
8066        // which don't work and shouldn't be found anyway.
8067        return false;
8068
8069      // Find the namespaces where ADL would have looked, and suggest
8070      // declaring the function there instead.
8071      Sema::AssociatedNamespaceSet AssociatedNamespaces;
8072      Sema::AssociatedClassSet AssociatedClasses;
8073      SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8074                                                 AssociatedNamespaces,
8075                                                 AssociatedClasses);
8076      // Never suggest declaring a function within namespace 'std'.
8077      Sema::AssociatedNamespaceSet SuggestedNamespaces;
8078      if (DeclContext *Std = SemaRef.getStdNamespace()) {
8079        for (Sema::AssociatedNamespaceSet::iterator
8080               it = AssociatedNamespaces.begin(),
8081               end = AssociatedNamespaces.end(); it != end; ++it) {
8082          if (!Std->Encloses(*it))
8083            SuggestedNamespaces.insert(*it);
8084        }
8085      } else {
8086        // Lacking the 'std::' namespace, use all of the associated namespaces.
8087        SuggestedNamespaces = AssociatedNamespaces;
8088      }
8089
8090      SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8091        << R.getLookupName();
8092      if (SuggestedNamespaces.empty()) {
8093        SemaRef.Diag(Best->Function->getLocation(),
8094                     diag::note_not_found_by_two_phase_lookup)
8095          << R.getLookupName() << 0;
8096      } else if (SuggestedNamespaces.size() == 1) {
8097        SemaRef.Diag(Best->Function->getLocation(),
8098                     diag::note_not_found_by_two_phase_lookup)
8099          << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
8100      } else {
8101        // FIXME: It would be useful to list the associated namespaces here,
8102        // but the diagnostics infrastructure doesn't provide a way to produce
8103        // a localized representation of a list of items.
8104        SemaRef.Diag(Best->Function->getLocation(),
8105                     diag::note_not_found_by_two_phase_lookup)
8106          << R.getLookupName() << 2;
8107      }
8108
8109      // Try to recover by calling this function.
8110      return true;
8111    }
8112
8113    R.clear();
8114  }
8115
8116  return false;
8117}
8118
8119/// Attempt to recover from ill-formed use of a non-dependent operator in a
8120/// template, where the non-dependent operator was declared after the template
8121/// was defined.
8122///
8123/// Returns true if a viable candidate was found and a diagnostic was issued.
8124static bool
8125DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8126                               SourceLocation OpLoc,
8127                               Expr **Args, unsigned NumArgs) {
8128  DeclarationName OpName =
8129    SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8130  LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8131  return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8132                                /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8133}
8134
8135/// Attempts to recover from a call where no functions were found.
8136///
8137/// Returns true if new candidates were found.
8138static ExprResult
8139BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
8140                      UnresolvedLookupExpr *ULE,
8141                      SourceLocation LParenLoc,
8142                      Expr **Args, unsigned NumArgs,
8143                      SourceLocation RParenLoc,
8144                      bool EmptyLookup) {
8145
8146  CXXScopeSpec SS;
8147  SS.Adopt(ULE->getQualifierLoc());
8148
8149  TemplateArgumentListInfo TABuffer;
8150  TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
8151  if (ULE->hasExplicitTemplateArgs()) {
8152    ULE->copyTemplateArgumentsInto(TABuffer);
8153    ExplicitTemplateArgs = &TABuffer;
8154  }
8155
8156  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8157                 Sema::LookupOrdinaryName);
8158  if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8159                              ExplicitTemplateArgs, Args, NumArgs) &&
8160      (!EmptyLookup ||
8161       SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression)))
8162    return ExprError();
8163
8164  assert(!R.empty() && "lookup results empty despite recovery");
8165
8166  // Build an implicit member call if appropriate.  Just drop the
8167  // casts and such from the call, we don't really care.
8168  ExprResult NewFn = ExprError();
8169  if ((*R.begin())->isCXXClassMember())
8170    NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8171                                                    ExplicitTemplateArgs);
8172  else if (ExplicitTemplateArgs)
8173    NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8174  else
8175    NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8176
8177  if (NewFn.isInvalid())
8178    return ExprError();
8179
8180  // This shouldn't cause an infinite loop because we're giving it
8181  // an expression with viable lookup results, which should never
8182  // end up here.
8183  return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
8184                               MultiExprArg(Args, NumArgs), RParenLoc);
8185}
8186
8187/// ResolveOverloadedCallFn - Given the call expression that calls Fn
8188/// (which eventually refers to the declaration Func) and the call
8189/// arguments Args/NumArgs, attempt to resolve the function call down
8190/// to a specific function. If overload resolution succeeds, returns
8191/// the function declaration produced by overload
8192/// resolution. Otherwise, emits diagnostics, deletes all of the
8193/// arguments and Fn, and returns NULL.
8194ExprResult
8195Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
8196                              SourceLocation LParenLoc,
8197                              Expr **Args, unsigned NumArgs,
8198                              SourceLocation RParenLoc,
8199                              Expr *ExecConfig) {
8200#ifndef NDEBUG
8201  if (ULE->requiresADL()) {
8202    // To do ADL, we must have found an unqualified name.
8203    assert(!ULE->getQualifier() && "qualified name with ADL");
8204
8205    // We don't perform ADL for implicit declarations of builtins.
8206    // Verify that this was correctly set up.
8207    FunctionDecl *F;
8208    if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8209        (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8210        F->getBuiltinID() && F->isImplicit())
8211      assert(0 && "performing ADL for builtin");
8212
8213    // We don't perform ADL in C.
8214    assert(getLangOptions().CPlusPlus && "ADL enabled in C");
8215  } else
8216    assert(!ULE->isStdAssociatedNamespace() &&
8217           "std is associated namespace but not doing ADL");
8218#endif
8219
8220  OverloadCandidateSet CandidateSet(Fn->getExprLoc());
8221
8222  // Add the functions denoted by the callee to the set of candidate
8223  // functions, including those from argument-dependent lookup.
8224  AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
8225
8226  // If we found nothing, try to recover.
8227  // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8228  // out if it fails.
8229  if (CandidateSet.empty())
8230    return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
8231                                 RParenLoc, /*EmptyLookup=*/true);
8232
8233  OverloadCandidateSet::iterator Best;
8234  switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
8235  case OR_Success: {
8236    FunctionDecl *FDecl = Best->Function;
8237    MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
8238    CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
8239    DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8240                      ULE->getNameLoc());
8241    Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8242    return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8243                                 ExecConfig);
8244  }
8245
8246  case OR_No_Viable_Function: {
8247    // Try to recover by looking for viable functions which the user might
8248    // have meant to call.
8249    ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8250                                                Args, NumArgs, RParenLoc,
8251                                                /*EmptyLookup=*/false);
8252    if (!Recovery.isInvalid())
8253      return Recovery;
8254
8255    Diag(Fn->getSourceRange().getBegin(),
8256         diag::err_ovl_no_viable_function_in_call)
8257      << ULE->getName() << Fn->getSourceRange();
8258    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8259    break;
8260  }
8261
8262  case OR_Ambiguous:
8263    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
8264      << ULE->getName() << Fn->getSourceRange();
8265    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
8266    break;
8267
8268  case OR_Deleted:
8269    {
8270      Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8271        << Best->Function->isDeleted()
8272        << ULE->getName()
8273        << getDeletedOrUnavailableSuffix(Best->Function)
8274        << Fn->getSourceRange();
8275      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8276    }
8277    break;
8278  }
8279
8280  // Overload resolution failed.
8281  return ExprError();
8282}
8283
8284static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
8285  return Functions.size() > 1 ||
8286    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8287}
8288
8289/// \brief Create a unary operation that may resolve to an overloaded
8290/// operator.
8291///
8292/// \param OpLoc The location of the operator itself (e.g., '*').
8293///
8294/// \param OpcIn The UnaryOperator::Opcode that describes this
8295/// operator.
8296///
8297/// \param Functions The set of non-member functions that will be
8298/// considered by overload resolution. The caller needs to build this
8299/// set based on the context using, e.g.,
8300/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8301/// set should not contain any member functions; those will be added
8302/// by CreateOverloadedUnaryOp().
8303///
8304/// \param input The input argument.
8305ExprResult
8306Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8307                              const UnresolvedSetImpl &Fns,
8308                              Expr *Input) {
8309  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
8310
8311  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8312  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8313  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8314  // TODO: provide better source location info.
8315  DeclarationNameInfo OpNameInfo(OpName, OpLoc);
8316
8317  if (Input->getObjectKind() == OK_ObjCProperty) {
8318    ExprResult Result = ConvertPropertyForRValue(Input);
8319    if (Result.isInvalid())
8320      return ExprError();
8321    Input = Result.take();
8322  }
8323
8324  Expr *Args[2] = { Input, 0 };
8325  unsigned NumArgs = 1;
8326
8327  // For post-increment and post-decrement, add the implicit '0' as
8328  // the second argument, so that we know this is a post-increment or
8329  // post-decrement.
8330  if (Opc == UO_PostInc || Opc == UO_PostDec) {
8331    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
8332    Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8333                                     SourceLocation());
8334    NumArgs = 2;
8335  }
8336
8337  if (Input->isTypeDependent()) {
8338    if (Fns.empty())
8339      return Owned(new (Context) UnaryOperator(Input,
8340                                               Opc,
8341                                               Context.DependentTy,
8342                                               VK_RValue, OK_Ordinary,
8343                                               OpLoc));
8344
8345    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8346    UnresolvedLookupExpr *Fn
8347      = UnresolvedLookupExpr::Create(Context, NamingClass,
8348                                     NestedNameSpecifierLoc(), OpNameInfo,
8349                                     /*ADL*/ true, IsOverloaded(Fns),
8350                                     Fns.begin(), Fns.end());
8351    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
8352                                                  &Args[0], NumArgs,
8353                                                   Context.DependentTy,
8354                                                   VK_RValue,
8355                                                   OpLoc));
8356  }
8357
8358  // Build an empty overload set.
8359  OverloadCandidateSet CandidateSet(OpLoc);
8360
8361  // Add the candidates from the given function set.
8362  AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
8363
8364  // Add operator candidates that are member functions.
8365  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8366
8367  // Add candidates from ADL.
8368  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8369                                       Args, NumArgs,
8370                                       /*ExplicitTemplateArgs*/ 0,
8371                                       CandidateSet);
8372
8373  // Add builtin operator candidates.
8374  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8375
8376  // Perform overload resolution.
8377  OverloadCandidateSet::iterator Best;
8378  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
8379  case OR_Success: {
8380    // We found a built-in operator or an overloaded operator.
8381    FunctionDecl *FnDecl = Best->Function;
8382
8383    if (FnDecl) {
8384      // We matched an overloaded operator. Build a call to that
8385      // operator.
8386
8387      MarkDeclarationReferenced(OpLoc, FnDecl);
8388
8389      // Convert the arguments.
8390      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
8391        CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
8392
8393        ExprResult InputRes =
8394          PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8395                                              Best->FoundDecl, Method);
8396        if (InputRes.isInvalid())
8397          return ExprError();
8398        Input = InputRes.take();
8399      } else {
8400        // Convert the arguments.
8401        ExprResult InputInit
8402          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
8403                                                      Context,
8404                                                      FnDecl->getParamDecl(0)),
8405                                      SourceLocation(),
8406                                      Input);
8407        if (InputInit.isInvalid())
8408          return ExprError();
8409        Input = InputInit.take();
8410      }
8411
8412      DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8413
8414      // Determine the result type.
8415      QualType ResultTy = FnDecl->getResultType();
8416      ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8417      ResultTy = ResultTy.getNonLValueExprType(Context);
8418
8419      // Build the actual expression node.
8420      ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8421      if (FnExpr.isInvalid())
8422        return ExprError();
8423
8424      Args[0] = Input;
8425      CallExpr *TheCall =
8426        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
8427                                          Args, NumArgs, ResultTy, VK, OpLoc);
8428
8429      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
8430                              FnDecl))
8431        return ExprError();
8432
8433      return MaybeBindToTemporary(TheCall);
8434    } else {
8435      // We matched a built-in operator. Convert the arguments, then
8436      // break out so that we will build the appropriate built-in
8437      // operator node.
8438      ExprResult InputRes =
8439        PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8440                                  Best->Conversions[0], AA_Passing);
8441      if (InputRes.isInvalid())
8442        return ExprError();
8443      Input = InputRes.take();
8444      break;
8445    }
8446  }
8447
8448  case OR_No_Viable_Function:
8449    // This is an erroneous use of an operator which can be overloaded by
8450    // a non-member function. Check for non-member operators which were
8451    // defined too late to be candidates.
8452    if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8453      // FIXME: Recover by calling the found function.
8454      return ExprError();
8455
8456    // No viable function; fall through to handling this as a
8457    // built-in operator, which will produce an error message for us.
8458    break;
8459
8460  case OR_Ambiguous:
8461    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
8462        << UnaryOperator::getOpcodeStr(Opc)
8463        << Input->getType()
8464        << Input->getSourceRange();
8465    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8466                                Args, NumArgs,
8467                                UnaryOperator::getOpcodeStr(Opc), OpLoc);
8468    return ExprError();
8469
8470  case OR_Deleted:
8471    Diag(OpLoc, diag::err_ovl_deleted_oper)
8472      << Best->Function->isDeleted()
8473      << UnaryOperator::getOpcodeStr(Opc)
8474      << getDeletedOrUnavailableSuffix(Best->Function)
8475      << Input->getSourceRange();
8476    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8477    return ExprError();
8478  }
8479
8480  // Either we found no viable overloaded operator or we matched a
8481  // built-in operator. In either case, fall through to trying to
8482  // build a built-in operation.
8483  return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8484}
8485
8486/// \brief Create a binary operation that may resolve to an overloaded
8487/// operator.
8488///
8489/// \param OpLoc The location of the operator itself (e.g., '+').
8490///
8491/// \param OpcIn The BinaryOperator::Opcode that describes this
8492/// operator.
8493///
8494/// \param Functions The set of non-member functions that will be
8495/// considered by overload resolution. The caller needs to build this
8496/// set based on the context using, e.g.,
8497/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8498/// set should not contain any member functions; those will be added
8499/// by CreateOverloadedBinOp().
8500///
8501/// \param LHS Left-hand argument.
8502/// \param RHS Right-hand argument.
8503ExprResult
8504Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
8505                            unsigned OpcIn,
8506                            const UnresolvedSetImpl &Fns,
8507                            Expr *LHS, Expr *RHS) {
8508  Expr *Args[2] = { LHS, RHS };
8509  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
8510
8511  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8512  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8513  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8514
8515  // If either side is type-dependent, create an appropriate dependent
8516  // expression.
8517  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8518    if (Fns.empty()) {
8519      // If there are no functions to store, just build a dependent
8520      // BinaryOperator or CompoundAssignment.
8521      if (Opc <= BO_Assign || Opc > BO_OrAssign)
8522        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
8523                                                  Context.DependentTy,
8524                                                  VK_RValue, OK_Ordinary,
8525                                                  OpLoc));
8526
8527      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8528                                                        Context.DependentTy,
8529                                                        VK_LValue,
8530                                                        OK_Ordinary,
8531                                                        Context.DependentTy,
8532                                                        Context.DependentTy,
8533                                                        OpLoc));
8534    }
8535
8536    // FIXME: save results of ADL from here?
8537    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8538    // TODO: provide better source location info in DNLoc component.
8539    DeclarationNameInfo OpNameInfo(OpName, OpLoc);
8540    UnresolvedLookupExpr *Fn
8541      = UnresolvedLookupExpr::Create(Context, NamingClass,
8542                                     NestedNameSpecifierLoc(), OpNameInfo,
8543                                     /*ADL*/ true, IsOverloaded(Fns),
8544                                     Fns.begin(), Fns.end());
8545    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
8546                                                   Args, 2,
8547                                                   Context.DependentTy,
8548                                                   VK_RValue,
8549                                                   OpLoc));
8550  }
8551
8552  // Always do property rvalue conversions on the RHS.
8553  if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8554    ExprResult Result = ConvertPropertyForRValue(Args[1]);
8555    if (Result.isInvalid())
8556      return ExprError();
8557    Args[1] = Result.take();
8558  }
8559
8560  // The LHS is more complicated.
8561  if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8562
8563    // There's a tension for assignment operators between primitive
8564    // property assignment and the overloaded operators.
8565    if (BinaryOperator::isAssignmentOp(Opc)) {
8566      const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8567
8568      // Is the property "logically" settable?
8569      bool Settable = (PRE->isExplicitProperty() ||
8570                       PRE->getImplicitPropertySetter());
8571
8572      // To avoid gratuitously inventing semantics, use the primitive
8573      // unless it isn't.  Thoughts in case we ever really care:
8574      // - If the property isn't logically settable, we have to
8575      //   load and hope.
8576      // - If the property is settable and this is simple assignment,
8577      //   we really should use the primitive.
8578      // - If the property is settable, then we could try overloading
8579      //   on a generic lvalue of the appropriate type;  if it works
8580      //   out to a builtin candidate, we would do that same operation
8581      //   on the property, and otherwise just error.
8582      if (Settable)
8583        return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8584    }
8585
8586    ExprResult Result = ConvertPropertyForRValue(Args[0]);
8587    if (Result.isInvalid())
8588      return ExprError();
8589    Args[0] = Result.take();
8590  }
8591
8592  // If this is the assignment operator, we only perform overload resolution
8593  // if the left-hand side is a class or enumeration type. This is actually
8594  // a hack. The standard requires that we do overload resolution between the
8595  // various built-in candidates, but as DR507 points out, this can lead to
8596  // problems. So we do it this way, which pretty much follows what GCC does.
8597  // Note that we go the traditional code path for compound assignment forms.
8598  if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
8599    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8600
8601  // If this is the .* operator, which is not overloadable, just
8602  // create a built-in binary operator.
8603  if (Opc == BO_PtrMemD)
8604    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8605
8606  // Build an empty overload set.
8607  OverloadCandidateSet CandidateSet(OpLoc);
8608
8609  // Add the candidates from the given function set.
8610  AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
8611
8612  // Add operator candidates that are member functions.
8613  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8614
8615  // Add candidates from ADL.
8616  AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8617                                       Args, 2,
8618                                       /*ExplicitTemplateArgs*/ 0,
8619                                       CandidateSet);
8620
8621  // Add builtin operator candidates.
8622  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8623
8624  // Perform overload resolution.
8625  OverloadCandidateSet::iterator Best;
8626  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
8627    case OR_Success: {
8628      // We found a built-in operator or an overloaded operator.
8629      FunctionDecl *FnDecl = Best->Function;
8630
8631      if (FnDecl) {
8632        // We matched an overloaded operator. Build a call to that
8633        // operator.
8634
8635        MarkDeclarationReferenced(OpLoc, FnDecl);
8636
8637        // Convert the arguments.
8638        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
8639          // Best->Access is only meaningful for class members.
8640          CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
8641
8642          ExprResult Arg1 =
8643            PerformCopyInitialization(
8644              InitializedEntity::InitializeParameter(Context,
8645                                                     FnDecl->getParamDecl(0)),
8646              SourceLocation(), Owned(Args[1]));
8647          if (Arg1.isInvalid())
8648            return ExprError();
8649
8650          ExprResult Arg0 =
8651            PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8652                                                Best->FoundDecl, Method);
8653          if (Arg0.isInvalid())
8654            return ExprError();
8655          Args[0] = Arg0.takeAs<Expr>();
8656          Args[1] = RHS = Arg1.takeAs<Expr>();
8657        } else {
8658          // Convert the arguments.
8659          ExprResult Arg0 = PerformCopyInitialization(
8660            InitializedEntity::InitializeParameter(Context,
8661                                                   FnDecl->getParamDecl(0)),
8662            SourceLocation(), Owned(Args[0]));
8663          if (Arg0.isInvalid())
8664            return ExprError();
8665
8666          ExprResult Arg1 =
8667            PerformCopyInitialization(
8668              InitializedEntity::InitializeParameter(Context,
8669                                                     FnDecl->getParamDecl(1)),
8670              SourceLocation(), Owned(Args[1]));
8671          if (Arg1.isInvalid())
8672            return ExprError();
8673          Args[0] = LHS = Arg0.takeAs<Expr>();
8674          Args[1] = RHS = Arg1.takeAs<Expr>();
8675        }
8676
8677        DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8678
8679        // Determine the result type.
8680        QualType ResultTy = FnDecl->getResultType();
8681        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8682        ResultTy = ResultTy.getNonLValueExprType(Context);
8683
8684        // Build the actual expression node.
8685        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8686        if (FnExpr.isInvalid())
8687          return ExprError();
8688
8689        CXXOperatorCallExpr *TheCall =
8690          new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
8691                                            Args, 2, ResultTy, VK, OpLoc);
8692
8693        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
8694                                FnDecl))
8695          return ExprError();
8696
8697        return MaybeBindToTemporary(TheCall);
8698      } else {
8699        // We matched a built-in operator. Convert the arguments, then
8700        // break out so that we will build the appropriate built-in
8701        // operator node.
8702        ExprResult ArgsRes0 =
8703          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8704                                    Best->Conversions[0], AA_Passing);
8705        if (ArgsRes0.isInvalid())
8706          return ExprError();
8707        Args[0] = ArgsRes0.take();
8708
8709        ExprResult ArgsRes1 =
8710          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8711                                    Best->Conversions[1], AA_Passing);
8712        if (ArgsRes1.isInvalid())
8713          return ExprError();
8714        Args[1] = ArgsRes1.take();
8715        break;
8716      }
8717    }
8718
8719    case OR_No_Viable_Function: {
8720      // C++ [over.match.oper]p9:
8721      //   If the operator is the operator , [...] and there are no
8722      //   viable functions, then the operator is assumed to be the
8723      //   built-in operator and interpreted according to clause 5.
8724      if (Opc == BO_Comma)
8725        break;
8726
8727      // For class as left operand for assignment or compound assigment
8728      // operator do not fall through to handling in built-in, but report that
8729      // no overloaded assignment operator found
8730      ExprResult Result = ExprError();
8731      if (Args[0]->getType()->isRecordType() &&
8732          Opc >= BO_Assign && Opc <= BO_OrAssign) {
8733        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
8734             << BinaryOperator::getOpcodeStr(Opc)
8735             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8736      } else {
8737        // This is an erroneous use of an operator which can be overloaded by
8738        // a non-member function. Check for non-member operators which were
8739        // defined too late to be candidates.
8740        if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8741          // FIXME: Recover by calling the found function.
8742          return ExprError();
8743
8744        // No viable function; try to create a built-in operation, which will
8745        // produce an error. Then, show the non-viable candidates.
8746        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8747      }
8748      assert(Result.isInvalid() &&
8749             "C++ binary operator overloading is missing candidates!");
8750      if (Result.isInvalid())
8751        CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8752                                    BinaryOperator::getOpcodeStr(Opc), OpLoc);
8753      return move(Result);
8754    }
8755
8756    case OR_Ambiguous:
8757      Diag(OpLoc,  diag::err_ovl_ambiguous_oper_binary)
8758          << BinaryOperator::getOpcodeStr(Opc)
8759          << Args[0]->getType() << Args[1]->getType()
8760          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8761      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8762                                  BinaryOperator::getOpcodeStr(Opc), OpLoc);
8763      return ExprError();
8764
8765    case OR_Deleted:
8766      Diag(OpLoc, diag::err_ovl_deleted_oper)
8767        << Best->Function->isDeleted()
8768        << BinaryOperator::getOpcodeStr(Opc)
8769        << getDeletedOrUnavailableSuffix(Best->Function)
8770        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8771      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
8772      return ExprError();
8773  }
8774
8775  // We matched a built-in operator; build it.
8776  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8777}
8778
8779ExprResult
8780Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8781                                         SourceLocation RLoc,
8782                                         Expr *Base, Expr *Idx) {
8783  Expr *Args[2] = { Base, Idx };
8784  DeclarationName OpName =
8785      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8786
8787  // If either side is type-dependent, create an appropriate dependent
8788  // expression.
8789  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8790
8791    CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8792    // CHECKME: no 'operator' keyword?
8793    DeclarationNameInfo OpNameInfo(OpName, LLoc);
8794    OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
8795    UnresolvedLookupExpr *Fn
8796      = UnresolvedLookupExpr::Create(Context, NamingClass,
8797                                     NestedNameSpecifierLoc(), OpNameInfo,
8798                                     /*ADL*/ true, /*Overloaded*/ false,
8799                                     UnresolvedSetIterator(),
8800                                     UnresolvedSetIterator());
8801    // Can't add any actual overloads yet
8802
8803    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8804                                                   Args, 2,
8805                                                   Context.DependentTy,
8806                                                   VK_RValue,
8807                                                   RLoc));
8808  }
8809
8810  if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8811    ExprResult Result = ConvertPropertyForRValue(Args[0]);
8812    if (Result.isInvalid())
8813      return ExprError();
8814    Args[0] = Result.take();
8815  }
8816  if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8817    ExprResult Result = ConvertPropertyForRValue(Args[1]);
8818    if (Result.isInvalid())
8819      return ExprError();
8820    Args[1] = Result.take();
8821  }
8822
8823  // Build an empty overload set.
8824  OverloadCandidateSet CandidateSet(LLoc);
8825
8826  // Subscript can only be overloaded as a member function.
8827
8828  // Add operator candidates that are member functions.
8829  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8830
8831  // Add builtin operator candidates.
8832  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8833
8834  // Perform overload resolution.
8835  OverloadCandidateSet::iterator Best;
8836  switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
8837    case OR_Success: {
8838      // We found a built-in operator or an overloaded operator.
8839      FunctionDecl *FnDecl = Best->Function;
8840
8841      if (FnDecl) {
8842        // We matched an overloaded operator. Build a call to that
8843        // operator.
8844
8845        MarkDeclarationReferenced(LLoc, FnDecl);
8846
8847        CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
8848        DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
8849
8850        // Convert the arguments.
8851        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
8852        ExprResult Arg0 =
8853          PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8854                                              Best->FoundDecl, Method);
8855        if (Arg0.isInvalid())
8856          return ExprError();
8857        Args[0] = Arg0.take();
8858
8859        // Convert the arguments.
8860        ExprResult InputInit
8861          = PerformCopyInitialization(InitializedEntity::InitializeParameter(
8862                                                      Context,
8863                                                      FnDecl->getParamDecl(0)),
8864                                      SourceLocation(),
8865                                      Owned(Args[1]));
8866        if (InputInit.isInvalid())
8867          return ExprError();
8868
8869        Args[1] = InputInit.takeAs<Expr>();
8870
8871        // Determine the result type
8872        QualType ResultTy = FnDecl->getResultType();
8873        ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8874        ResultTy = ResultTy.getNonLValueExprType(Context);
8875
8876        // Build the actual expression node.
8877        ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8878        if (FnExpr.isInvalid())
8879          return ExprError();
8880
8881        CXXOperatorCallExpr *TheCall =
8882          new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
8883                                            FnExpr.take(), Args, 2,
8884                                            ResultTy, VK, RLoc);
8885
8886        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
8887                                FnDecl))
8888          return ExprError();
8889
8890        return MaybeBindToTemporary(TheCall);
8891      } else {
8892        // We matched a built-in operator. Convert the arguments, then
8893        // break out so that we will build the appropriate built-in
8894        // operator node.
8895        ExprResult ArgsRes0 =
8896          PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8897                                    Best->Conversions[0], AA_Passing);
8898        if (ArgsRes0.isInvalid())
8899          return ExprError();
8900        Args[0] = ArgsRes0.take();
8901
8902        ExprResult ArgsRes1 =
8903          PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8904                                    Best->Conversions[1], AA_Passing);
8905        if (ArgsRes1.isInvalid())
8906          return ExprError();
8907        Args[1] = ArgsRes1.take();
8908
8909        break;
8910      }
8911    }
8912
8913    case OR_No_Viable_Function: {
8914      if (CandidateSet.empty())
8915        Diag(LLoc, diag::err_ovl_no_oper)
8916          << Args[0]->getType() << /*subscript*/ 0
8917          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8918      else
8919        Diag(LLoc, diag::err_ovl_no_viable_subscript)
8920          << Args[0]->getType()
8921          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8922      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8923                                  "[]", LLoc);
8924      return ExprError();
8925    }
8926
8927    case OR_Ambiguous:
8928      Diag(LLoc,  diag::err_ovl_ambiguous_oper_binary)
8929          << "[]"
8930          << Args[0]->getType() << Args[1]->getType()
8931          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8932      CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8933                                  "[]", LLoc);
8934      return ExprError();
8935
8936    case OR_Deleted:
8937      Diag(LLoc, diag::err_ovl_deleted_oper)
8938        << Best->Function->isDeleted() << "[]"
8939        << getDeletedOrUnavailableSuffix(Best->Function)
8940        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8941      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8942                                  "[]", LLoc);
8943      return ExprError();
8944    }
8945
8946  // We matched a built-in operator; build it.
8947  return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
8948}
8949
8950/// BuildCallToMemberFunction - Build a call to a member
8951/// function. MemExpr is the expression that refers to the member
8952/// function (and includes the object parameter), Args/NumArgs are the
8953/// arguments to the function call (not including the object
8954/// parameter). The caller needs to validate that the member
8955/// expression refers to a non-static member function or an overloaded
8956/// member function.
8957ExprResult
8958Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8959                                SourceLocation LParenLoc, Expr **Args,
8960                                unsigned NumArgs, SourceLocation RParenLoc) {
8961  assert(MemExprE->getType() == Context.BoundMemberTy ||
8962         MemExprE->getType() == Context.OverloadTy);
8963
8964  // Dig out the member expression. This holds both the object
8965  // argument and the member function we're referring to.
8966  Expr *NakedMemExpr = MemExprE->IgnoreParens();
8967
8968  // Determine whether this is a call to a pointer-to-member function.
8969  if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
8970    assert(op->getType() == Context.BoundMemberTy);
8971    assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
8972
8973    QualType fnType =
8974      op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
8975
8976    const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
8977    QualType resultType = proto->getCallResultType(Context);
8978    ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
8979
8980    // Check that the object type isn't more qualified than the
8981    // member function we're calling.
8982    Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
8983
8984    QualType objectType = op->getLHS()->getType();
8985    if (op->getOpcode() == BO_PtrMemI)
8986      objectType = objectType->castAs<PointerType>()->getPointeeType();
8987    Qualifiers objectQuals = objectType.getQualifiers();
8988
8989    Qualifiers difference = objectQuals - funcQuals;
8990    difference.removeObjCGCAttr();
8991    difference.removeAddressSpace();
8992    if (difference) {
8993      std::string qualsString = difference.getAsString();
8994      Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
8995        << fnType.getUnqualifiedType()
8996        << qualsString
8997        << (qualsString.find(' ') == std::string::npos ? 1 : 2);
8998    }
8999
9000    CXXMemberCallExpr *call
9001      = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9002                                        resultType, valueKind, RParenLoc);
9003
9004    if (CheckCallReturnType(proto->getResultType(),
9005                            op->getRHS()->getSourceRange().getBegin(),
9006                            call, 0))
9007      return ExprError();
9008
9009    if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9010      return ExprError();
9011
9012    return MaybeBindToTemporary(call);
9013  }
9014
9015  MemberExpr *MemExpr;
9016  CXXMethodDecl *Method = 0;
9017  DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
9018  NestedNameSpecifier *Qualifier = 0;
9019  if (isa<MemberExpr>(NakedMemExpr)) {
9020    MemExpr = cast<MemberExpr>(NakedMemExpr);
9021    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
9022    FoundDecl = MemExpr->getFoundDecl();
9023    Qualifier = MemExpr->getQualifier();
9024  } else {
9025    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
9026    Qualifier = UnresExpr->getQualifier();
9027
9028    QualType ObjectType = UnresExpr->getBaseType();
9029    Expr::Classification ObjectClassification
9030      = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9031                            : UnresExpr->getBase()->Classify(Context);
9032
9033    // Add overload candidates
9034    OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
9035
9036    // FIXME: avoid copy.
9037    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9038    if (UnresExpr->hasExplicitTemplateArgs()) {
9039      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9040      TemplateArgs = &TemplateArgsBuffer;
9041    }
9042
9043    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9044           E = UnresExpr->decls_end(); I != E; ++I) {
9045
9046      NamedDecl *Func = *I;
9047      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9048      if (isa<UsingShadowDecl>(Func))
9049        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9050
9051
9052      // Microsoft supports direct constructor calls.
9053      if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
9054        AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9055                             CandidateSet);
9056      } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
9057        // If explicit template arguments were provided, we can't call a
9058        // non-template member function.
9059        if (TemplateArgs)
9060          continue;
9061
9062        AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
9063                           ObjectClassification,
9064                           Args, NumArgs, CandidateSet,
9065                           /*SuppressUserConversions=*/false);
9066      } else {
9067        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
9068                                   I.getPair(), ActingDC, TemplateArgs,
9069                                   ObjectType,  ObjectClassification,
9070                                   Args, NumArgs, CandidateSet,
9071                                   /*SuppressUsedConversions=*/false);
9072      }
9073    }
9074
9075    DeclarationName DeclName = UnresExpr->getMemberName();
9076
9077    OverloadCandidateSet::iterator Best;
9078    switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
9079                                            Best)) {
9080    case OR_Success:
9081      Method = cast<CXXMethodDecl>(Best->Function);
9082      MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
9083      FoundDecl = Best->FoundDecl;
9084      CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
9085      DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
9086      break;
9087
9088    case OR_No_Viable_Function:
9089      Diag(UnresExpr->getMemberLoc(),
9090           diag::err_ovl_no_viable_member_function_in_call)
9091        << DeclName << MemExprE->getSourceRange();
9092      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9093      // FIXME: Leaking incoming expressions!
9094      return ExprError();
9095
9096    case OR_Ambiguous:
9097      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
9098        << DeclName << MemExprE->getSourceRange();
9099      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9100      // FIXME: Leaking incoming expressions!
9101      return ExprError();
9102
9103    case OR_Deleted:
9104      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
9105        << Best->Function->isDeleted()
9106        << DeclName
9107        << getDeletedOrUnavailableSuffix(Best->Function)
9108        << MemExprE->getSourceRange();
9109      CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9110      // FIXME: Leaking incoming expressions!
9111      return ExprError();
9112    }
9113
9114    MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
9115
9116    // If overload resolution picked a static member, build a
9117    // non-member call based on that function.
9118    if (Method->isStatic()) {
9119      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9120                                   Args, NumArgs, RParenLoc);
9121    }
9122
9123    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
9124  }
9125
9126  QualType ResultType = Method->getResultType();
9127  ExprValueKind VK = Expr::getValueKindForType(ResultType);
9128  ResultType = ResultType.getNonLValueExprType(Context);
9129
9130  assert(Method && "Member call to something that isn't a method?");
9131  CXXMemberCallExpr *TheCall =
9132    new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9133                                    ResultType, VK, RParenLoc);
9134
9135  // Check for a valid return type.
9136  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
9137                          TheCall, Method))
9138    return ExprError();
9139
9140  // Convert the object argument (for a non-static member function call).
9141  // We only need to do this if there was actually an overload; otherwise
9142  // it was done at lookup.
9143  if (!Method->isStatic()) {
9144    ExprResult ObjectArg =
9145      PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9146                                          FoundDecl, Method);
9147    if (ObjectArg.isInvalid())
9148      return ExprError();
9149    MemExpr->setBase(ObjectArg.take());
9150  }
9151
9152  // Convert the rest of the arguments
9153  const FunctionProtoType *Proto =
9154    Method->getType()->getAs<FunctionProtoType>();
9155  if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
9156                              RParenLoc))
9157    return ExprError();
9158
9159  if (CheckFunctionCall(Method, TheCall))
9160    return ExprError();
9161
9162  if ((isa<CXXConstructorDecl>(CurContext) ||
9163       isa<CXXDestructorDecl>(CurContext)) &&
9164      TheCall->getMethodDecl()->isPure()) {
9165    const CXXMethodDecl *MD = TheCall->getMethodDecl();
9166
9167    if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()))
9168      Diag(MemExpr->getLocStart(),
9169           diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9170        << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9171        << MD->getParent()->getDeclName();
9172
9173      Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
9174  }
9175  return MaybeBindToTemporary(TheCall);
9176}
9177
9178/// BuildCallToObjectOfClassType - Build a call to an object of class
9179/// type (C++ [over.call.object]), which can end up invoking an
9180/// overloaded function call operator (@c operator()) or performing a
9181/// user-defined conversion on the object argument.
9182ExprResult
9183Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
9184                                   SourceLocation LParenLoc,
9185                                   Expr **Args, unsigned NumArgs,
9186                                   SourceLocation RParenLoc) {
9187  ExprResult Object = Owned(Obj);
9188  if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9189    Object = ConvertPropertyForRValue(Object.take());
9190    if (Object.isInvalid())
9191      return ExprError();
9192  }
9193
9194  assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9195  const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
9196
9197  // C++ [over.call.object]p1:
9198  //  If the primary-expression E in the function call syntax
9199  //  evaluates to a class object of type "cv T", then the set of
9200  //  candidate functions includes at least the function call
9201  //  operators of T. The function call operators of T are obtained by
9202  //  ordinary lookup of the name operator() in the context of
9203  //  (E).operator().
9204  OverloadCandidateSet CandidateSet(LParenLoc);
9205  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
9206
9207  if (RequireCompleteType(LParenLoc, Object.get()->getType(),
9208                          PDiag(diag::err_incomplete_object_call)
9209                          << Object.get()->getSourceRange()))
9210    return true;
9211
9212  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9213  LookupQualifiedName(R, Record->getDecl());
9214  R.suppressDiagnostics();
9215
9216  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
9217       Oper != OperEnd; ++Oper) {
9218    AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9219                       Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
9220                       /*SuppressUserConversions=*/ false);
9221  }
9222
9223  // C++ [over.call.object]p2:
9224  //   In addition, for each conversion function declared in T of the
9225  //   form
9226  //
9227  //        operator conversion-type-id () cv-qualifier;
9228  //
9229  //   where cv-qualifier is the same cv-qualification as, or a
9230  //   greater cv-qualification than, cv, and where conversion-type-id
9231  //   denotes the type "pointer to function of (P1,...,Pn) returning
9232  //   R", or the type "reference to pointer to function of
9233  //   (P1,...,Pn) returning R", or the type "reference to function
9234  //   of (P1,...,Pn) returning R", a surrogate call function [...]
9235  //   is also considered as a candidate function. Similarly,
9236  //   surrogate call functions are added to the set of candidate
9237  //   functions for each conversion function declared in an
9238  //   accessible base class provided the function is not hidden
9239  //   within T by another intervening declaration.
9240  const UnresolvedSetImpl *Conversions
9241    = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
9242  for (UnresolvedSetImpl::iterator I = Conversions->begin(),
9243         E = Conversions->end(); I != E; ++I) {
9244    NamedDecl *D = *I;
9245    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9246    if (isa<UsingShadowDecl>(D))
9247      D = cast<UsingShadowDecl>(D)->getTargetDecl();
9248
9249    // Skip over templated conversion functions; they aren't
9250    // surrogates.
9251    if (isa<FunctionTemplateDecl>(D))
9252      continue;
9253
9254    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9255
9256    // Strip the reference type (if any) and then the pointer type (if
9257    // any) to get down to what might be a function type.
9258    QualType ConvType = Conv->getConversionType().getNonReferenceType();
9259    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9260      ConvType = ConvPtrType->getPointeeType();
9261
9262    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9263      AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9264                            Object.get(), Args, NumArgs, CandidateSet);
9265  }
9266
9267  // Perform overload resolution.
9268  OverloadCandidateSet::iterator Best;
9269  switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
9270                             Best)) {
9271  case OR_Success:
9272    // Overload resolution succeeded; we'll build the appropriate call
9273    // below.
9274    break;
9275
9276  case OR_No_Viable_Function:
9277    if (CandidateSet.empty())
9278      Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9279        << Object.get()->getType() << /*call*/ 1
9280        << Object.get()->getSourceRange();
9281    else
9282      Diag(Object.get()->getSourceRange().getBegin(),
9283           diag::err_ovl_no_viable_object_call)
9284        << Object.get()->getType() << Object.get()->getSourceRange();
9285    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9286    break;
9287
9288  case OR_Ambiguous:
9289    Diag(Object.get()->getSourceRange().getBegin(),
9290         diag::err_ovl_ambiguous_object_call)
9291      << Object.get()->getType() << Object.get()->getSourceRange();
9292    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
9293    break;
9294
9295  case OR_Deleted:
9296    Diag(Object.get()->getSourceRange().getBegin(),
9297         diag::err_ovl_deleted_object_call)
9298      << Best->Function->isDeleted()
9299      << Object.get()->getType()
9300      << getDeletedOrUnavailableSuffix(Best->Function)
9301      << Object.get()->getSourceRange();
9302    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9303    break;
9304  }
9305
9306  if (Best == CandidateSet.end())
9307    return true;
9308
9309  if (Best->Function == 0) {
9310    // Since there is no function declaration, this is one of the
9311    // surrogate candidates. Dig out the conversion function.
9312    CXXConversionDecl *Conv
9313      = cast<CXXConversionDecl>(
9314                         Best->Conversions[0].UserDefined.ConversionFunction);
9315
9316    CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
9317    DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
9318
9319    // We selected one of the surrogate functions that converts the
9320    // object parameter to a function pointer. Perform the conversion
9321    // on the object argument, then let ActOnCallExpr finish the job.
9322
9323    // Create an implicit member expr to refer to the conversion operator.
9324    // and then call it.
9325    ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
9326    if (Call.isInvalid())
9327      return ExprError();
9328
9329    return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
9330                         RParenLoc);
9331  }
9332
9333  MarkDeclarationReferenced(LParenLoc, Best->Function);
9334  CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
9335  DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
9336
9337  // We found an overloaded operator(). Build a CXXOperatorCallExpr
9338  // that calls this method, using Object for the implicit object
9339  // parameter and passing along the remaining arguments.
9340  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
9341  const FunctionProtoType *Proto =
9342    Method->getType()->getAs<FunctionProtoType>();
9343
9344  unsigned NumArgsInProto = Proto->getNumArgs();
9345  unsigned NumArgsToCheck = NumArgs;
9346
9347  // Build the full argument list for the method call (the
9348  // implicit object parameter is placed at the beginning of the
9349  // list).
9350  Expr **MethodArgs;
9351  if (NumArgs < NumArgsInProto) {
9352    NumArgsToCheck = NumArgsInProto;
9353    MethodArgs = new Expr*[NumArgsInProto + 1];
9354  } else {
9355    MethodArgs = new Expr*[NumArgs + 1];
9356  }
9357  MethodArgs[0] = Object.get();
9358  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9359    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
9360
9361  ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9362  if (NewFn.isInvalid())
9363    return true;
9364
9365  // Once we've built TheCall, all of the expressions are properly
9366  // owned.
9367  QualType ResultTy = Method->getResultType();
9368  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9369  ResultTy = ResultTy.getNonLValueExprType(Context);
9370
9371  CXXOperatorCallExpr *TheCall =
9372    new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
9373                                      MethodArgs, NumArgs + 1,
9374                                      ResultTy, VK, RParenLoc);
9375  delete [] MethodArgs;
9376
9377  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
9378                          Method))
9379    return true;
9380
9381  // We may have default arguments. If so, we need to allocate more
9382  // slots in the call for them.
9383  if (NumArgs < NumArgsInProto)
9384    TheCall->setNumArgs(Context, NumArgsInProto + 1);
9385  else if (NumArgs > NumArgsInProto)
9386    NumArgsToCheck = NumArgsInProto;
9387
9388  bool IsError = false;
9389
9390  // Initialize the implicit object parameter.
9391  ExprResult ObjRes =
9392    PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9393                                        Best->FoundDecl, Method);
9394  if (ObjRes.isInvalid())
9395    IsError = true;
9396  else
9397    Object = move(ObjRes);
9398  TheCall->setArg(0, Object.take());
9399
9400  // Check the argument types.
9401  for (unsigned i = 0; i != NumArgsToCheck; i++) {
9402    Expr *Arg;
9403    if (i < NumArgs) {
9404      Arg = Args[i];
9405
9406      // Pass the argument.
9407
9408      ExprResult InputInit
9409        = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9410                                                    Context,
9411                                                    Method->getParamDecl(i)),
9412                                    SourceLocation(), Arg);
9413
9414      IsError |= InputInit.isInvalid();
9415      Arg = InputInit.takeAs<Expr>();
9416    } else {
9417      ExprResult DefArg
9418        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9419      if (DefArg.isInvalid()) {
9420        IsError = true;
9421        break;
9422      }
9423
9424      Arg = DefArg.takeAs<Expr>();
9425    }
9426
9427    TheCall->setArg(i + 1, Arg);
9428  }
9429
9430  // If this is a variadic call, handle args passed through "...".
9431  if (Proto->isVariadic()) {
9432    // Promote the arguments (C99 6.5.2.2p7).
9433    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
9434      ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9435      IsError |= Arg.isInvalid();
9436      TheCall->setArg(i + 1, Arg.take());
9437    }
9438  }
9439
9440  if (IsError) return true;
9441
9442  if (CheckFunctionCall(Method, TheCall))
9443    return true;
9444
9445  return MaybeBindToTemporary(TheCall);
9446}
9447
9448/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
9449///  (if one exists), where @c Base is an expression of class type and
9450/// @c Member is the name of the member we're trying to find.
9451ExprResult
9452Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
9453  assert(Base->getType()->isRecordType() &&
9454         "left-hand side must have class type");
9455
9456  if (Base->getObjectKind() == OK_ObjCProperty) {
9457    ExprResult Result = ConvertPropertyForRValue(Base);
9458    if (Result.isInvalid())
9459      return ExprError();
9460    Base = Result.take();
9461  }
9462
9463  SourceLocation Loc = Base->getExprLoc();
9464
9465  // C++ [over.ref]p1:
9466  //
9467  //   [...] An expression x->m is interpreted as (x.operator->())->m
9468  //   for a class object x of type T if T::operator->() exists and if
9469  //   the operator is selected as the best match function by the
9470  //   overload resolution mechanism (13.3).
9471  DeclarationName OpName =
9472    Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
9473  OverloadCandidateSet CandidateSet(Loc);
9474  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
9475
9476  if (RequireCompleteType(Loc, Base->getType(),
9477                          PDiag(diag::err_typecheck_incomplete_tag)
9478                            << Base->getSourceRange()))
9479    return ExprError();
9480
9481  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9482  LookupQualifiedName(R, BaseRecord->getDecl());
9483  R.suppressDiagnostics();
9484
9485  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
9486       Oper != OperEnd; ++Oper) {
9487    AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9488                       0, 0, CandidateSet, /*SuppressUserConversions=*/false);
9489  }
9490
9491  // Perform overload resolution.
9492  OverloadCandidateSet::iterator Best;
9493  switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9494  case OR_Success:
9495    // Overload resolution succeeded; we'll build the call below.
9496    break;
9497
9498  case OR_No_Viable_Function:
9499    if (CandidateSet.empty())
9500      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
9501        << Base->getType() << Base->getSourceRange();
9502    else
9503      Diag(OpLoc, diag::err_ovl_no_viable_oper)
9504        << "operator->" << Base->getSourceRange();
9505    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
9506    return ExprError();
9507
9508  case OR_Ambiguous:
9509    Diag(OpLoc,  diag::err_ovl_ambiguous_oper_unary)
9510      << "->" << Base->getType() << Base->getSourceRange();
9511    CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
9512    return ExprError();
9513
9514  case OR_Deleted:
9515    Diag(OpLoc,  diag::err_ovl_deleted_oper)
9516      << Best->Function->isDeleted()
9517      << "->"
9518      << getDeletedOrUnavailableSuffix(Best->Function)
9519      << Base->getSourceRange();
9520    CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
9521    return ExprError();
9522  }
9523
9524  MarkDeclarationReferenced(OpLoc, Best->Function);
9525  CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
9526  DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9527
9528  // Convert the object parameter.
9529  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
9530  ExprResult BaseResult =
9531    PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9532                                        Best->FoundDecl, Method);
9533  if (BaseResult.isInvalid())
9534    return ExprError();
9535  Base = BaseResult.take();
9536
9537  // Build the operator call.
9538  ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9539  if (FnExpr.isInvalid())
9540    return ExprError();
9541
9542  QualType ResultTy = Method->getResultType();
9543  ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9544  ResultTy = ResultTy.getNonLValueExprType(Context);
9545  CXXOperatorCallExpr *TheCall =
9546    new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
9547                                      &Base, 1, ResultTy, VK, OpLoc);
9548
9549  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
9550                          Method))
9551          return ExprError();
9552
9553  return MaybeBindToTemporary(TheCall);
9554}
9555
9556/// FixOverloadedFunctionReference - E is an expression that refers to
9557/// a C++ overloaded function (possibly with some parentheses and
9558/// perhaps a '&' around it). We have resolved the overloaded function
9559/// to the function declaration Fn, so patch up the expression E to
9560/// refer (possibly indirectly) to Fn. Returns the new expr.
9561Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
9562                                           FunctionDecl *Fn) {
9563  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
9564    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9565                                                   Found, Fn);
9566    if (SubExpr == PE->getSubExpr())
9567      return PE;
9568
9569    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
9570  }
9571
9572  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9573    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9574                                                   Found, Fn);
9575    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
9576                               SubExpr->getType()) &&
9577           "Implicit cast type cannot be determined from overload");
9578    assert(ICE->path_empty() && "fixing up hierarchy conversion?");
9579    if (SubExpr == ICE->getSubExpr())
9580      return ICE;
9581
9582    return ImplicitCastExpr::Create(Context, ICE->getType(),
9583                                    ICE->getCastKind(),
9584                                    SubExpr, 0,
9585                                    ICE->getValueKind());
9586  }
9587
9588  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
9589    assert(UnOp->getOpcode() == UO_AddrOf &&
9590           "Can only take the address of an overloaded function");
9591    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9592      if (Method->isStatic()) {
9593        // Do nothing: static member functions aren't any different
9594        // from non-member functions.
9595      } else {
9596        // Fix the sub expression, which really has to be an
9597        // UnresolvedLookupExpr holding an overloaded member function
9598        // or template.
9599        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9600                                                       Found, Fn);
9601        if (SubExpr == UnOp->getSubExpr())
9602          return UnOp;
9603
9604        assert(isa<DeclRefExpr>(SubExpr)
9605               && "fixed to something other than a decl ref");
9606        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9607               && "fixed to a member ref with no nested name qualifier");
9608
9609        // We have taken the address of a pointer to member
9610        // function. Perform the computation here so that we get the
9611        // appropriate pointer to member type.
9612        QualType ClassType
9613          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9614        QualType MemPtrType
9615          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9616
9617        return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9618                                           VK_RValue, OK_Ordinary,
9619                                           UnOp->getOperatorLoc());
9620      }
9621    }
9622    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9623                                                   Found, Fn);
9624    if (SubExpr == UnOp->getSubExpr())
9625      return UnOp;
9626
9627    return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
9628                                     Context.getPointerType(SubExpr->getType()),
9629                                       VK_RValue, OK_Ordinary,
9630                                       UnOp->getOperatorLoc());
9631  }
9632
9633  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9634    // FIXME: avoid copy.
9635    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9636    if (ULE->hasExplicitTemplateArgs()) {
9637      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9638      TemplateArgs = &TemplateArgsBuffer;
9639    }
9640
9641    return DeclRefExpr::Create(Context,
9642                               ULE->getQualifierLoc(),
9643                               Fn,
9644                               ULE->getNameLoc(),
9645                               Fn->getType(),
9646                               VK_LValue,
9647                               Found.getDecl(),
9648                               TemplateArgs);
9649  }
9650
9651  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
9652    // FIXME: avoid copy.
9653    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9654    if (MemExpr->hasExplicitTemplateArgs()) {
9655      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9656      TemplateArgs = &TemplateArgsBuffer;
9657    }
9658
9659    Expr *Base;
9660
9661    // If we're filling in a static method where we used to have an
9662    // implicit member access, rewrite to a simple decl ref.
9663    if (MemExpr->isImplicitAccess()) {
9664      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9665        return DeclRefExpr::Create(Context,
9666                                   MemExpr->getQualifierLoc(),
9667                                   Fn,
9668                                   MemExpr->getMemberLoc(),
9669                                   Fn->getType(),
9670                                   VK_LValue,
9671                                   Found.getDecl(),
9672                                   TemplateArgs);
9673      } else {
9674        SourceLocation Loc = MemExpr->getMemberLoc();
9675        if (MemExpr->getQualifier())
9676          Loc = MemExpr->getQualifierLoc().getBeginLoc();
9677        Base = new (Context) CXXThisExpr(Loc,
9678                                         MemExpr->getBaseType(),
9679                                         /*isImplicit=*/true);
9680      }
9681    } else
9682      Base = MemExpr->getBase();
9683
9684    ExprValueKind valueKind;
9685    QualType type;
9686    if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9687      valueKind = VK_LValue;
9688      type = Fn->getType();
9689    } else {
9690      valueKind = VK_RValue;
9691      type = Context.BoundMemberTy;
9692    }
9693
9694    return MemberExpr::Create(Context, Base,
9695                              MemExpr->isArrow(),
9696                              MemExpr->getQualifierLoc(),
9697                              Fn,
9698                              Found,
9699                              MemExpr->getMemberNameInfo(),
9700                              TemplateArgs,
9701                              type, valueKind, OK_Ordinary);
9702  }
9703
9704  llvm_unreachable("Invalid reference to overloaded function");
9705  return E;
9706}
9707
9708ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
9709                                                DeclAccessPair Found,
9710                                                FunctionDecl *Fn) {
9711  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
9712}
9713
9714} // end namespace clang
9715