SemaOverload.cpp revision 578b69b186d9cba0a6ae1dd7f4c04cd6a49f0aac
1//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "Lookup.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/TypeOrdering.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/STLExtras.h"
26#include <algorithm>
27#include <cstdio>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
33ImplicitConversionCategory
34GetConversionCategory(ImplicitConversionKind Kind) {
35  static const ImplicitConversionCategory
36    Category[(int)ICK_Num_Conversion_Kinds] = {
37    ICC_Identity,
38    ICC_Lvalue_Transformation,
39    ICC_Lvalue_Transformation,
40    ICC_Lvalue_Transformation,
41    ICC_Identity,
42    ICC_Qualification_Adjustment,
43    ICC_Promotion,
44    ICC_Promotion,
45    ICC_Promotion,
46    ICC_Conversion,
47    ICC_Conversion,
48    ICC_Conversion,
49    ICC_Conversion,
50    ICC_Conversion,
51    ICC_Conversion,
52    ICC_Conversion,
53    ICC_Conversion,
54    ICC_Conversion,
55    ICC_Conversion
56  };
57  return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63  static const ImplicitConversionRank
64    Rank[(int)ICK_Num_Conversion_Kinds] = {
65    ICR_Exact_Match,
66    ICR_Exact_Match,
67    ICR_Exact_Match,
68    ICR_Exact_Match,
69    ICR_Exact_Match,
70    ICR_Exact_Match,
71    ICR_Promotion,
72    ICR_Promotion,
73    ICR_Promotion,
74    ICR_Conversion,
75    ICR_Conversion,
76    ICR_Conversion,
77    ICR_Conversion,
78    ICR_Conversion,
79    ICR_Conversion,
80    ICR_Conversion,
81    ICR_Conversion,
82    ICR_Conversion,
83    ICR_Conversion
84  };
85  return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
91  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
92    "No conversion",
93    "Lvalue-to-rvalue",
94    "Array-to-pointer",
95    "Function-to-pointer",
96    "Noreturn adjustment",
97    "Qualification",
98    "Integral promotion",
99    "Floating point promotion",
100    "Complex promotion",
101    "Integral conversion",
102    "Floating conversion",
103    "Complex conversion",
104    "Floating-integral conversion",
105    "Complex-real conversion",
106    "Pointer conversion",
107    "Pointer-to-member conversion",
108    "Boolean conversion",
109    "Compatible-types conversion",
110    "Derived-to-base conversion"
111  };
112  return Name[Kind];
113}
114
115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118  First = ICK_Identity;
119  Second = ICK_Identity;
120  Third = ICK_Identity;
121  Deprecated = false;
122  ReferenceBinding = false;
123  DirectBinding = false;
124  RRefBinding = false;
125  CopyConstructor = 0;
126}
127
128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132  ImplicitConversionRank Rank = ICR_Exact_Match;
133  if  (GetConversionRank(First) > Rank)
134    Rank = GetConversionRank(First);
135  if  (GetConversionRank(Second) > Rank)
136    Rank = GetConversionRank(Second);
137  if  (GetConversionRank(Third) > Rank)
138    Rank = GetConversionRank(Third);
139  return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
144/// used as part of the ranking of standard conversion sequences
145/// (C++ 13.3.3.2p4).
146bool StandardConversionSequence::isPointerConversionToBool() const {
147  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
148  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
149
150  // Note that FromType has not necessarily been transformed by the
151  // array-to-pointer or function-to-pointer implicit conversions, so
152  // check for their presence as well as checking whether FromType is
153  // a pointer.
154  if (ToType->isBooleanType() &&
155      (FromType->isPointerType() || FromType->isBlockPointerType() ||
156       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
157    return true;
158
159  return false;
160}
161
162/// isPointerConversionToVoidPointer - Determines whether this
163/// conversion is a conversion of a pointer to a void pointer. This is
164/// used as part of the ranking of standard conversion sequences (C++
165/// 13.3.3.2p4).
166bool
167StandardConversionSequence::
168isPointerConversionToVoidPointer(ASTContext& Context) const {
169  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
170  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
171
172  // Note that FromType has not necessarily been transformed by the
173  // array-to-pointer implicit conversion, so check for its presence
174  // and redo the conversion to get a pointer.
175  if (First == ICK_Array_To_Pointer)
176    FromType = Context.getArrayDecayedType(FromType);
177
178  if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
179    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
180      return ToPtrType->getPointeeType()->isVoidType();
181
182  return false;
183}
184
185/// DebugPrint - Print this standard conversion sequence to standard
186/// error. Useful for debugging overloading issues.
187void StandardConversionSequence::DebugPrint() const {
188  bool PrintedSomething = false;
189  if (First != ICK_Identity) {
190    fprintf(stderr, "%s", GetImplicitConversionName(First));
191    PrintedSomething = true;
192  }
193
194  if (Second != ICK_Identity) {
195    if (PrintedSomething) {
196      fprintf(stderr, " -> ");
197    }
198    fprintf(stderr, "%s", GetImplicitConversionName(Second));
199
200    if (CopyConstructor) {
201      fprintf(stderr, " (by copy constructor)");
202    } else if (DirectBinding) {
203      fprintf(stderr, " (direct reference binding)");
204    } else if (ReferenceBinding) {
205      fprintf(stderr, " (reference binding)");
206    }
207    PrintedSomething = true;
208  }
209
210  if (Third != ICK_Identity) {
211    if (PrintedSomething) {
212      fprintf(stderr, " -> ");
213    }
214    fprintf(stderr, "%s", GetImplicitConversionName(Third));
215    PrintedSomething = true;
216  }
217
218  if (!PrintedSomething) {
219    fprintf(stderr, "No conversions required");
220  }
221}
222
223/// DebugPrint - Print this user-defined conversion sequence to standard
224/// error. Useful for debugging overloading issues.
225void UserDefinedConversionSequence::DebugPrint() const {
226  if (Before.First || Before.Second || Before.Third) {
227    Before.DebugPrint();
228    fprintf(stderr, " -> ");
229  }
230  fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
231  if (After.First || After.Second || After.Third) {
232    fprintf(stderr, " -> ");
233    After.DebugPrint();
234  }
235}
236
237/// DebugPrint - Print this implicit conversion sequence to standard
238/// error. Useful for debugging overloading issues.
239void ImplicitConversionSequence::DebugPrint() const {
240  switch (ConversionKind) {
241  case StandardConversion:
242    fprintf(stderr, "Standard conversion: ");
243    Standard.DebugPrint();
244    break;
245  case UserDefinedConversion:
246    fprintf(stderr, "User-defined conversion: ");
247    UserDefined.DebugPrint();
248    break;
249  case EllipsisConversion:
250    fprintf(stderr, "Ellipsis conversion");
251    break;
252  case BadConversion:
253    fprintf(stderr, "Bad conversion");
254    break;
255  }
256
257  fprintf(stderr, "\n");
258}
259
260// IsOverload - Determine whether the given New declaration is an
261// overload of the declarations in Old. This routine returns false if
262// New and Old cannot be overloaded, e.g., if New has the same
263// signature as some function in Old (C++ 1.3.10) or if the Old
264// declarations aren't functions (or function templates) at all. When
265// it does return false, MatchedDecl will point to the decl that New
266// cannot be overloaded with.  This decl may be a UsingShadowDecl on
267// top of the underlying declaration.
268//
269// Example: Given the following input:
270//
271//   void f(int, float); // #1
272//   void f(int, int); // #2
273//   int f(int, int); // #3
274//
275// When we process #1, there is no previous declaration of "f",
276// so IsOverload will not be used.
277//
278// When we process #2, Old contains only the FunctionDecl for #1.  By
279// comparing the parameter types, we see that #1 and #2 are overloaded
280// (since they have different signatures), so this routine returns
281// false; MatchedDecl is unchanged.
282//
283// When we process #3, Old is an overload set containing #1 and #2. We
284// compare the signatures of #3 to #1 (they're overloaded, so we do
285// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
286// identical (return types of functions are not part of the
287// signature), IsOverload returns false and MatchedDecl will be set to
288// point to the FunctionDecl for #2.
289Sema::OverloadKind
290Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
291                    NamedDecl *&Match) {
292  for (LookupResult::iterator I = Old.begin(), E = Old.end();
293         I != E; ++I) {
294    NamedDecl *OldD = (*I)->getUnderlyingDecl();
295    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
296      if (!IsOverload(New, OldT->getTemplatedDecl())) {
297        Match = *I;
298        return Ovl_Match;
299      }
300    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
301      if (!IsOverload(New, OldF)) {
302        Match = *I;
303        return Ovl_Match;
304      }
305    } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
306      // We can overload with these, which can show up when doing
307      // redeclaration checks for UsingDecls.
308      assert(Old.getLookupKind() == LookupUsingDeclName);
309    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
310      // Optimistically assume that an unresolved using decl will
311      // overload; if it doesn't, we'll have to diagnose during
312      // template instantiation.
313    } else {
314      // (C++ 13p1):
315      //   Only function declarations can be overloaded; object and type
316      //   declarations cannot be overloaded.
317      Match = *I;
318      return Ovl_NonFunction;
319    }
320  }
321
322  return Ovl_Overload;
323}
324
325bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
326  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
327  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
328
329  // C++ [temp.fct]p2:
330  //   A function template can be overloaded with other function templates
331  //   and with normal (non-template) functions.
332  if ((OldTemplate == 0) != (NewTemplate == 0))
333    return true;
334
335  // Is the function New an overload of the function Old?
336  QualType OldQType = Context.getCanonicalType(Old->getType());
337  QualType NewQType = Context.getCanonicalType(New->getType());
338
339  // Compare the signatures (C++ 1.3.10) of the two functions to
340  // determine whether they are overloads. If we find any mismatch
341  // in the signature, they are overloads.
342
343  // If either of these functions is a K&R-style function (no
344  // prototype), then we consider them to have matching signatures.
345  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
346      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
347    return false;
348
349  FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
350  FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
351
352  // The signature of a function includes the types of its
353  // parameters (C++ 1.3.10), which includes the presence or absence
354  // of the ellipsis; see C++ DR 357).
355  if (OldQType != NewQType &&
356      (OldType->getNumArgs() != NewType->getNumArgs() ||
357       OldType->isVariadic() != NewType->isVariadic() ||
358       !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
359                   NewType->arg_type_begin())))
360    return true;
361
362  // C++ [temp.over.link]p4:
363  //   The signature of a function template consists of its function
364  //   signature, its return type and its template parameter list. The names
365  //   of the template parameters are significant only for establishing the
366  //   relationship between the template parameters and the rest of the
367  //   signature.
368  //
369  // We check the return type and template parameter lists for function
370  // templates first; the remaining checks follow.
371  if (NewTemplate &&
372      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
373                                       OldTemplate->getTemplateParameters(),
374                                       false, TPL_TemplateMatch) ||
375       OldType->getResultType() != NewType->getResultType()))
376    return true;
377
378  // If the function is a class member, its signature includes the
379  // cv-qualifiers (if any) on the function itself.
380  //
381  // As part of this, also check whether one of the member functions
382  // is static, in which case they are not overloads (C++
383  // 13.1p2). While not part of the definition of the signature,
384  // this check is important to determine whether these functions
385  // can be overloaded.
386  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
387  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
388  if (OldMethod && NewMethod &&
389      !OldMethod->isStatic() && !NewMethod->isStatic() &&
390      OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
391    return true;
392
393  // The signatures match; this is not an overload.
394  return false;
395}
396
397/// TryImplicitConversion - Attempt to perform an implicit conversion
398/// from the given expression (Expr) to the given type (ToType). This
399/// function returns an implicit conversion sequence that can be used
400/// to perform the initialization. Given
401///
402///   void f(float f);
403///   void g(int i) { f(i); }
404///
405/// this routine would produce an implicit conversion sequence to
406/// describe the initialization of f from i, which will be a standard
407/// conversion sequence containing an lvalue-to-rvalue conversion (C++
408/// 4.1) followed by a floating-integral conversion (C++ 4.9).
409//
410/// Note that this routine only determines how the conversion can be
411/// performed; it does not actually perform the conversion. As such,
412/// it will not produce any diagnostics if no conversion is available,
413/// but will instead return an implicit conversion sequence of kind
414/// "BadConversion".
415///
416/// If @p SuppressUserConversions, then user-defined conversions are
417/// not permitted.
418/// If @p AllowExplicit, then explicit user-defined conversions are
419/// permitted.
420/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
421/// no matter its actual lvalueness.
422/// If @p UserCast, the implicit conversion is being done for a user-specified
423/// cast.
424ImplicitConversionSequence
425Sema::TryImplicitConversion(Expr* From, QualType ToType,
426                            bool SuppressUserConversions,
427                            bool AllowExplicit, bool ForceRValue,
428                            bool InOverloadResolution,
429                            bool UserCast) {
430  ImplicitConversionSequence ICS;
431  OverloadCandidateSet Conversions;
432  OverloadingResult UserDefResult = OR_Success;
433  if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
434    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
435  else if (getLangOptions().CPlusPlus &&
436           (UserDefResult = IsUserDefinedConversion(From, ToType,
437                                   ICS.UserDefined,
438                                   Conversions,
439                                   !SuppressUserConversions, AllowExplicit,
440				   ForceRValue, UserCast)) == OR_Success) {
441    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
442    // C++ [over.ics.user]p4:
443    //   A conversion of an expression of class type to the same class
444    //   type is given Exact Match rank, and a conversion of an
445    //   expression of class type to a base class of that type is
446    //   given Conversion rank, in spite of the fact that a copy
447    //   constructor (i.e., a user-defined conversion function) is
448    //   called for those cases.
449    if (CXXConstructorDecl *Constructor
450          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
451      QualType FromCanon
452        = Context.getCanonicalType(From->getType().getUnqualifiedType());
453      QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
454      if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
455        // Turn this into a "standard" conversion sequence, so that it
456        // gets ranked with standard conversion sequences.
457        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
458        ICS.Standard.setAsIdentityConversion();
459        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
460        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
461        ICS.Standard.CopyConstructor = Constructor;
462        if (ToCanon != FromCanon)
463          ICS.Standard.Second = ICK_Derived_To_Base;
464      }
465    }
466
467    // C++ [over.best.ics]p4:
468    //   However, when considering the argument of a user-defined
469    //   conversion function that is a candidate by 13.3.1.3 when
470    //   invoked for the copying of the temporary in the second step
471    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
472    //   13.3.1.6 in all cases, only standard conversion sequences and
473    //   ellipsis conversion sequences are allowed.
474    if (SuppressUserConversions &&
475        ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
476      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
477  } else {
478    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
479    if (UserDefResult == OR_Ambiguous) {
480      for (OverloadCandidateSet::iterator Cand = Conversions.begin();
481           Cand != Conversions.end(); ++Cand)
482        if (Cand->Viable)
483          ICS.ConversionFunctionSet.push_back(Cand->Function);
484    }
485  }
486
487  return ICS;
488}
489
490/// \brief Determine whether the conversion from FromType to ToType is a valid
491/// conversion that strips "noreturn" off the nested function type.
492static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
493                                 QualType ToType, QualType &ResultTy) {
494  if (Context.hasSameUnqualifiedType(FromType, ToType))
495    return false;
496
497  // Strip the noreturn off the type we're converting from; noreturn can
498  // safely be removed.
499  FromType = Context.getNoReturnType(FromType, false);
500  if (!Context.hasSameUnqualifiedType(FromType, ToType))
501    return false;
502
503  ResultTy = FromType;
504  return true;
505}
506
507/// IsStandardConversion - Determines whether there is a standard
508/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
509/// expression From to the type ToType. Standard conversion sequences
510/// only consider non-class types; for conversions that involve class
511/// types, use TryImplicitConversion. If a conversion exists, SCS will
512/// contain the standard conversion sequence required to perform this
513/// conversion and this routine will return true. Otherwise, this
514/// routine will return false and the value of SCS is unspecified.
515bool
516Sema::IsStandardConversion(Expr* From, QualType ToType,
517                           bool InOverloadResolution,
518                           StandardConversionSequence &SCS) {
519  QualType FromType = From->getType();
520
521  // Standard conversions (C++ [conv])
522  SCS.setAsIdentityConversion();
523  SCS.Deprecated = false;
524  SCS.IncompatibleObjC = false;
525  SCS.FromTypePtr = FromType.getAsOpaquePtr();
526  SCS.CopyConstructor = 0;
527
528  // There are no standard conversions for class types in C++, so
529  // abort early. When overloading in C, however, we do permit
530  if (FromType->isRecordType() || ToType->isRecordType()) {
531    if (getLangOptions().CPlusPlus)
532      return false;
533
534    // When we're overloading in C, we allow, as standard conversions,
535  }
536
537  // The first conversion can be an lvalue-to-rvalue conversion,
538  // array-to-pointer conversion, or function-to-pointer conversion
539  // (C++ 4p1).
540
541  // Lvalue-to-rvalue conversion (C++ 4.1):
542  //   An lvalue (3.10) of a non-function, non-array type T can be
543  //   converted to an rvalue.
544  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
545  if (argIsLvalue == Expr::LV_Valid &&
546      !FromType->isFunctionType() && !FromType->isArrayType() &&
547      Context.getCanonicalType(FromType) != Context.OverloadTy) {
548    SCS.First = ICK_Lvalue_To_Rvalue;
549
550    // If T is a non-class type, the type of the rvalue is the
551    // cv-unqualified version of T. Otherwise, the type of the rvalue
552    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
553    // just strip the qualifiers because they don't matter.
554    FromType = FromType.getUnqualifiedType();
555  } else if (FromType->isArrayType()) {
556    // Array-to-pointer conversion (C++ 4.2)
557    SCS.First = ICK_Array_To_Pointer;
558
559    // An lvalue or rvalue of type "array of N T" or "array of unknown
560    // bound of T" can be converted to an rvalue of type "pointer to
561    // T" (C++ 4.2p1).
562    FromType = Context.getArrayDecayedType(FromType);
563
564    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
565      // This conversion is deprecated. (C++ D.4).
566      SCS.Deprecated = true;
567
568      // For the purpose of ranking in overload resolution
569      // (13.3.3.1.1), this conversion is considered an
570      // array-to-pointer conversion followed by a qualification
571      // conversion (4.4). (C++ 4.2p2)
572      SCS.Second = ICK_Identity;
573      SCS.Third = ICK_Qualification;
574      SCS.ToTypePtr = ToType.getAsOpaquePtr();
575      return true;
576    }
577  } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
578    // Function-to-pointer conversion (C++ 4.3).
579    SCS.First = ICK_Function_To_Pointer;
580
581    // An lvalue of function type T can be converted to an rvalue of
582    // type "pointer to T." The result is a pointer to the
583    // function. (C++ 4.3p1).
584    FromType = Context.getPointerType(FromType);
585  } else if (FunctionDecl *Fn
586               = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
587    // Address of overloaded function (C++ [over.over]).
588    SCS.First = ICK_Function_To_Pointer;
589
590    // We were able to resolve the address of the overloaded function,
591    // so we can convert to the type of that function.
592    FromType = Fn->getType();
593    if (ToType->isLValueReferenceType())
594      FromType = Context.getLValueReferenceType(FromType);
595    else if (ToType->isRValueReferenceType())
596      FromType = Context.getRValueReferenceType(FromType);
597    else if (ToType->isMemberPointerType()) {
598      // Resolve address only succeeds if both sides are member pointers,
599      // but it doesn't have to be the same class. See DR 247.
600      // Note that this means that the type of &Derived::fn can be
601      // Ret (Base::*)(Args) if the fn overload actually found is from the
602      // base class, even if it was brought into the derived class via a
603      // using declaration. The standard isn't clear on this issue at all.
604      CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
605      FromType = Context.getMemberPointerType(FromType,
606                    Context.getTypeDeclType(M->getParent()).getTypePtr());
607    } else
608      FromType = Context.getPointerType(FromType);
609  } else {
610    // We don't require any conversions for the first step.
611    SCS.First = ICK_Identity;
612  }
613
614  // The second conversion can be an integral promotion, floating
615  // point promotion, integral conversion, floating point conversion,
616  // floating-integral conversion, pointer conversion,
617  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
618  // For overloading in C, this can also be a "compatible-type"
619  // conversion.
620  bool IncompatibleObjC = false;
621  if (Context.hasSameUnqualifiedType(FromType, ToType)) {
622    // The unqualified versions of the types are the same: there's no
623    // conversion to do.
624    SCS.Second = ICK_Identity;
625  } else if (IsIntegralPromotion(From, FromType, ToType)) {
626    // Integral promotion (C++ 4.5).
627    SCS.Second = ICK_Integral_Promotion;
628    FromType = ToType.getUnqualifiedType();
629  } else if (IsFloatingPointPromotion(FromType, ToType)) {
630    // Floating point promotion (C++ 4.6).
631    SCS.Second = ICK_Floating_Promotion;
632    FromType = ToType.getUnqualifiedType();
633  } else if (IsComplexPromotion(FromType, ToType)) {
634    // Complex promotion (Clang extension)
635    SCS.Second = ICK_Complex_Promotion;
636    FromType = ToType.getUnqualifiedType();
637  } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
638           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
639    // Integral conversions (C++ 4.7).
640    // FIXME: isIntegralType shouldn't be true for enums in C++.
641    SCS.Second = ICK_Integral_Conversion;
642    FromType = ToType.getUnqualifiedType();
643  } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
644    // Floating point conversions (C++ 4.8).
645    SCS.Second = ICK_Floating_Conversion;
646    FromType = ToType.getUnqualifiedType();
647  } else if (FromType->isComplexType() && ToType->isComplexType()) {
648    // Complex conversions (C99 6.3.1.6)
649    SCS.Second = ICK_Complex_Conversion;
650    FromType = ToType.getUnqualifiedType();
651  } else if ((FromType->isFloatingType() &&
652              ToType->isIntegralType() && (!ToType->isBooleanType() &&
653                                           !ToType->isEnumeralType())) ||
654             ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
655              ToType->isFloatingType())) {
656    // Floating-integral conversions (C++ 4.9).
657    // FIXME: isIntegralType shouldn't be true for enums in C++.
658    SCS.Second = ICK_Floating_Integral;
659    FromType = ToType.getUnqualifiedType();
660  } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
661             (ToType->isComplexType() && FromType->isArithmeticType())) {
662    // Complex-real conversions (C99 6.3.1.7)
663    SCS.Second = ICK_Complex_Real;
664    FromType = ToType.getUnqualifiedType();
665  } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
666                                 FromType, IncompatibleObjC)) {
667    // Pointer conversions (C++ 4.10).
668    SCS.Second = ICK_Pointer_Conversion;
669    SCS.IncompatibleObjC = IncompatibleObjC;
670  } else if (IsMemberPointerConversion(From, FromType, ToType,
671                                       InOverloadResolution, FromType)) {
672    // Pointer to member conversions (4.11).
673    SCS.Second = ICK_Pointer_Member;
674  } else if (ToType->isBooleanType() &&
675             (FromType->isArithmeticType() ||
676              FromType->isEnumeralType() ||
677              FromType->isAnyPointerType() ||
678              FromType->isBlockPointerType() ||
679              FromType->isMemberPointerType() ||
680              FromType->isNullPtrType())) {
681    // Boolean conversions (C++ 4.12).
682    SCS.Second = ICK_Boolean_Conversion;
683    FromType = Context.BoolTy;
684  } else if (!getLangOptions().CPlusPlus &&
685             Context.typesAreCompatible(ToType, FromType)) {
686    // Compatible conversions (Clang extension for C function overloading)
687    SCS.Second = ICK_Compatible_Conversion;
688  } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
689    // Treat a conversion that strips "noreturn" as an identity conversion.
690    SCS.Second = ICK_NoReturn_Adjustment;
691  } else {
692    // No second conversion required.
693    SCS.Second = ICK_Identity;
694  }
695
696  QualType CanonFrom;
697  QualType CanonTo;
698  // The third conversion can be a qualification conversion (C++ 4p1).
699  if (IsQualificationConversion(FromType, ToType)) {
700    SCS.Third = ICK_Qualification;
701    FromType = ToType;
702    CanonFrom = Context.getCanonicalType(FromType);
703    CanonTo = Context.getCanonicalType(ToType);
704  } else {
705    // No conversion required
706    SCS.Third = ICK_Identity;
707
708    // C++ [over.best.ics]p6:
709    //   [...] Any difference in top-level cv-qualification is
710    //   subsumed by the initialization itself and does not constitute
711    //   a conversion. [...]
712    CanonFrom = Context.getCanonicalType(FromType);
713    CanonTo = Context.getCanonicalType(ToType);
714    if (CanonFrom.getLocalUnqualifiedType()
715                                       == CanonTo.getLocalUnqualifiedType() &&
716        CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
717      FromType = ToType;
718      CanonFrom = CanonTo;
719    }
720  }
721
722  // If we have not converted the argument type to the parameter type,
723  // this is a bad conversion sequence.
724  if (CanonFrom != CanonTo)
725    return false;
726
727  SCS.ToTypePtr = FromType.getAsOpaquePtr();
728  return true;
729}
730
731/// IsIntegralPromotion - Determines whether the conversion from the
732/// expression From (whose potentially-adjusted type is FromType) to
733/// ToType is an integral promotion (C++ 4.5). If so, returns true and
734/// sets PromotedType to the promoted type.
735bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
736  const BuiltinType *To = ToType->getAs<BuiltinType>();
737  // All integers are built-in.
738  if (!To) {
739    return false;
740  }
741
742  // An rvalue of type char, signed char, unsigned char, short int, or
743  // unsigned short int can be converted to an rvalue of type int if
744  // int can represent all the values of the source type; otherwise,
745  // the source rvalue can be converted to an rvalue of type unsigned
746  // int (C++ 4.5p1).
747  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
748    if (// We can promote any signed, promotable integer type to an int
749        (FromType->isSignedIntegerType() ||
750         // We can promote any unsigned integer type whose size is
751         // less than int to an int.
752         (!FromType->isSignedIntegerType() &&
753          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
754      return To->getKind() == BuiltinType::Int;
755    }
756
757    return To->getKind() == BuiltinType::UInt;
758  }
759
760  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
761  // can be converted to an rvalue of the first of the following types
762  // that can represent all the values of its underlying type: int,
763  // unsigned int, long, or unsigned long (C++ 4.5p2).
764
765  // We pre-calculate the promotion type for enum types.
766  if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
767    if (ToType->isIntegerType())
768      return Context.hasSameUnqualifiedType(ToType,
769                                FromEnumType->getDecl()->getPromotionType());
770
771  if (FromType->isWideCharType() && ToType->isIntegerType()) {
772    // Determine whether the type we're converting from is signed or
773    // unsigned.
774    bool FromIsSigned;
775    uint64_t FromSize = Context.getTypeSize(FromType);
776
777    // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
778    FromIsSigned = true;
779
780    // The types we'll try to promote to, in the appropriate
781    // order. Try each of these types.
782    QualType PromoteTypes[6] = {
783      Context.IntTy, Context.UnsignedIntTy,
784      Context.LongTy, Context.UnsignedLongTy ,
785      Context.LongLongTy, Context.UnsignedLongLongTy
786    };
787    for (int Idx = 0; Idx < 6; ++Idx) {
788      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
789      if (FromSize < ToSize ||
790          (FromSize == ToSize &&
791           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
792        // We found the type that we can promote to. If this is the
793        // type we wanted, we have a promotion. Otherwise, no
794        // promotion.
795        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
796      }
797    }
798  }
799
800  // An rvalue for an integral bit-field (9.6) can be converted to an
801  // rvalue of type int if int can represent all the values of the
802  // bit-field; otherwise, it can be converted to unsigned int if
803  // unsigned int can represent all the values of the bit-field. If
804  // the bit-field is larger yet, no integral promotion applies to
805  // it. If the bit-field has an enumerated type, it is treated as any
806  // other value of that type for promotion purposes (C++ 4.5p3).
807  // FIXME: We should delay checking of bit-fields until we actually perform the
808  // conversion.
809  using llvm::APSInt;
810  if (From)
811    if (FieldDecl *MemberDecl = From->getBitField()) {
812      APSInt BitWidth;
813      if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
814          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
815        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
816        ToSize = Context.getTypeSize(ToType);
817
818        // Are we promoting to an int from a bitfield that fits in an int?
819        if (BitWidth < ToSize ||
820            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
821          return To->getKind() == BuiltinType::Int;
822        }
823
824        // Are we promoting to an unsigned int from an unsigned bitfield
825        // that fits into an unsigned int?
826        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
827          return To->getKind() == BuiltinType::UInt;
828        }
829
830        return false;
831      }
832    }
833
834  // An rvalue of type bool can be converted to an rvalue of type int,
835  // with false becoming zero and true becoming one (C++ 4.5p4).
836  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
837    return true;
838  }
839
840  return false;
841}
842
843/// IsFloatingPointPromotion - Determines whether the conversion from
844/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
845/// returns true and sets PromotedType to the promoted type.
846bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
847  /// An rvalue of type float can be converted to an rvalue of type
848  /// double. (C++ 4.6p1).
849  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
850    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
851      if (FromBuiltin->getKind() == BuiltinType::Float &&
852          ToBuiltin->getKind() == BuiltinType::Double)
853        return true;
854
855      // C99 6.3.1.5p1:
856      //   When a float is promoted to double or long double, or a
857      //   double is promoted to long double [...].
858      if (!getLangOptions().CPlusPlus &&
859          (FromBuiltin->getKind() == BuiltinType::Float ||
860           FromBuiltin->getKind() == BuiltinType::Double) &&
861          (ToBuiltin->getKind() == BuiltinType::LongDouble))
862        return true;
863    }
864
865  return false;
866}
867
868/// \brief Determine if a conversion is a complex promotion.
869///
870/// A complex promotion is defined as a complex -> complex conversion
871/// where the conversion between the underlying real types is a
872/// floating-point or integral promotion.
873bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
874  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
875  if (!FromComplex)
876    return false;
877
878  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
879  if (!ToComplex)
880    return false;
881
882  return IsFloatingPointPromotion(FromComplex->getElementType(),
883                                  ToComplex->getElementType()) ||
884    IsIntegralPromotion(0, FromComplex->getElementType(),
885                        ToComplex->getElementType());
886}
887
888/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
889/// the pointer type FromPtr to a pointer to type ToPointee, with the
890/// same type qualifiers as FromPtr has on its pointee type. ToType,
891/// if non-empty, will be a pointer to ToType that may or may not have
892/// the right set of qualifiers on its pointee.
893static QualType
894BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
895                                   QualType ToPointee, QualType ToType,
896                                   ASTContext &Context) {
897  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
898  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
899  Qualifiers Quals = CanonFromPointee.getQualifiers();
900
901  // Exact qualifier match -> return the pointer type we're converting to.
902  if (CanonToPointee.getLocalQualifiers() == Quals) {
903    // ToType is exactly what we need. Return it.
904    if (!ToType.isNull())
905      return ToType;
906
907    // Build a pointer to ToPointee. It has the right qualifiers
908    // already.
909    return Context.getPointerType(ToPointee);
910  }
911
912  // Just build a canonical type that has the right qualifiers.
913  return Context.getPointerType(
914         Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
915                                  Quals));
916}
917
918static bool isNullPointerConstantForConversion(Expr *Expr,
919                                               bool InOverloadResolution,
920                                               ASTContext &Context) {
921  // Handle value-dependent integral null pointer constants correctly.
922  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
923  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
924      Expr->getType()->isIntegralType())
925    return !InOverloadResolution;
926
927  return Expr->isNullPointerConstant(Context,
928                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
929                                        : Expr::NPC_ValueDependentIsNull);
930}
931
932/// IsPointerConversion - Determines whether the conversion of the
933/// expression From, which has the (possibly adjusted) type FromType,
934/// can be converted to the type ToType via a pointer conversion (C++
935/// 4.10). If so, returns true and places the converted type (that
936/// might differ from ToType in its cv-qualifiers at some level) into
937/// ConvertedType.
938///
939/// This routine also supports conversions to and from block pointers
940/// and conversions with Objective-C's 'id', 'id<protocols...>', and
941/// pointers to interfaces. FIXME: Once we've determined the
942/// appropriate overloading rules for Objective-C, we may want to
943/// split the Objective-C checks into a different routine; however,
944/// GCC seems to consider all of these conversions to be pointer
945/// conversions, so for now they live here. IncompatibleObjC will be
946/// set if the conversion is an allowed Objective-C conversion that
947/// should result in a warning.
948bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
949                               bool InOverloadResolution,
950                               QualType& ConvertedType,
951                               bool &IncompatibleObjC) {
952  IncompatibleObjC = false;
953  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
954    return true;
955
956  // Conversion from a null pointer constant to any Objective-C pointer type.
957  if (ToType->isObjCObjectPointerType() &&
958      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
959    ConvertedType = ToType;
960    return true;
961  }
962
963  // Blocks: Block pointers can be converted to void*.
964  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
965      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
966    ConvertedType = ToType;
967    return true;
968  }
969  // Blocks: A null pointer constant can be converted to a block
970  // pointer type.
971  if (ToType->isBlockPointerType() &&
972      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
973    ConvertedType = ToType;
974    return true;
975  }
976
977  // If the left-hand-side is nullptr_t, the right side can be a null
978  // pointer constant.
979  if (ToType->isNullPtrType() &&
980      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
981    ConvertedType = ToType;
982    return true;
983  }
984
985  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
986  if (!ToTypePtr)
987    return false;
988
989  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
990  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
991    ConvertedType = ToType;
992    return true;
993  }
994
995  // Beyond this point, both types need to be pointers.
996  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
997  if (!FromTypePtr)
998    return false;
999
1000  QualType FromPointeeType = FromTypePtr->getPointeeType();
1001  QualType ToPointeeType = ToTypePtr->getPointeeType();
1002
1003  // An rvalue of type "pointer to cv T," where T is an object type,
1004  // can be converted to an rvalue of type "pointer to cv void" (C++
1005  // 4.10p2).
1006  if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
1007    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1008                                                       ToPointeeType,
1009                                                       ToType, Context);
1010    return true;
1011  }
1012
1013  // When we're overloading in C, we allow a special kind of pointer
1014  // conversion for compatible-but-not-identical pointee types.
1015  if (!getLangOptions().CPlusPlus &&
1016      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1017    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1018                                                       ToPointeeType,
1019                                                       ToType, Context);
1020    return true;
1021  }
1022
1023  // C++ [conv.ptr]p3:
1024  //
1025  //   An rvalue of type "pointer to cv D," where D is a class type,
1026  //   can be converted to an rvalue of type "pointer to cv B," where
1027  //   B is a base class (clause 10) of D. If B is an inaccessible
1028  //   (clause 11) or ambiguous (10.2) base class of D, a program that
1029  //   necessitates this conversion is ill-formed. The result of the
1030  //   conversion is a pointer to the base class sub-object of the
1031  //   derived class object. The null pointer value is converted to
1032  //   the null pointer value of the destination type.
1033  //
1034  // Note that we do not check for ambiguity or inaccessibility
1035  // here. That is handled by CheckPointerConversion.
1036  if (getLangOptions().CPlusPlus &&
1037      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1038      !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1039      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1040    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1041                                                       ToPointeeType,
1042                                                       ToType, Context);
1043    return true;
1044  }
1045
1046  return false;
1047}
1048
1049/// isObjCPointerConversion - Determines whether this is an
1050/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1051/// with the same arguments and return values.
1052bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1053                                   QualType& ConvertedType,
1054                                   bool &IncompatibleObjC) {
1055  if (!getLangOptions().ObjC1)
1056    return false;
1057
1058  // First, we handle all conversions on ObjC object pointer types.
1059  const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
1060  const ObjCObjectPointerType *FromObjCPtr =
1061    FromType->getAs<ObjCObjectPointerType>();
1062
1063  if (ToObjCPtr && FromObjCPtr) {
1064    // Objective C++: We're able to convert between "id" or "Class" and a
1065    // pointer to any interface (in both directions).
1066    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1067      ConvertedType = ToType;
1068      return true;
1069    }
1070    // Conversions with Objective-C's id<...>.
1071    if ((FromObjCPtr->isObjCQualifiedIdType() ||
1072         ToObjCPtr->isObjCQualifiedIdType()) &&
1073        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1074                                                  /*compare=*/false)) {
1075      ConvertedType = ToType;
1076      return true;
1077    }
1078    // Objective C++: We're able to convert from a pointer to an
1079    // interface to a pointer to a different interface.
1080    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1081      ConvertedType = ToType;
1082      return true;
1083    }
1084
1085    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1086      // Okay: this is some kind of implicit downcast of Objective-C
1087      // interfaces, which is permitted. However, we're going to
1088      // complain about it.
1089      IncompatibleObjC = true;
1090      ConvertedType = FromType;
1091      return true;
1092    }
1093  }
1094  // Beyond this point, both types need to be C pointers or block pointers.
1095  QualType ToPointeeType;
1096  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1097    ToPointeeType = ToCPtr->getPointeeType();
1098  else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
1099    ToPointeeType = ToBlockPtr->getPointeeType();
1100  else
1101    return false;
1102
1103  QualType FromPointeeType;
1104  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1105    FromPointeeType = FromCPtr->getPointeeType();
1106  else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
1107    FromPointeeType = FromBlockPtr->getPointeeType();
1108  else
1109    return false;
1110
1111  // If we have pointers to pointers, recursively check whether this
1112  // is an Objective-C conversion.
1113  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1114      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1115                              IncompatibleObjC)) {
1116    // We always complain about this conversion.
1117    IncompatibleObjC = true;
1118    ConvertedType = ToType;
1119    return true;
1120  }
1121  // If we have pointers to functions or blocks, check whether the only
1122  // differences in the argument and result types are in Objective-C
1123  // pointer conversions. If so, we permit the conversion (but
1124  // complain about it).
1125  const FunctionProtoType *FromFunctionType
1126    = FromPointeeType->getAs<FunctionProtoType>();
1127  const FunctionProtoType *ToFunctionType
1128    = ToPointeeType->getAs<FunctionProtoType>();
1129  if (FromFunctionType && ToFunctionType) {
1130    // If the function types are exactly the same, this isn't an
1131    // Objective-C pointer conversion.
1132    if (Context.getCanonicalType(FromPointeeType)
1133          == Context.getCanonicalType(ToPointeeType))
1134      return false;
1135
1136    // Perform the quick checks that will tell us whether these
1137    // function types are obviously different.
1138    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1139        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1140        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1141      return false;
1142
1143    bool HasObjCConversion = false;
1144    if (Context.getCanonicalType(FromFunctionType->getResultType())
1145          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1146      // Okay, the types match exactly. Nothing to do.
1147    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1148                                       ToFunctionType->getResultType(),
1149                                       ConvertedType, IncompatibleObjC)) {
1150      // Okay, we have an Objective-C pointer conversion.
1151      HasObjCConversion = true;
1152    } else {
1153      // Function types are too different. Abort.
1154      return false;
1155    }
1156
1157    // Check argument types.
1158    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1159         ArgIdx != NumArgs; ++ArgIdx) {
1160      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1161      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1162      if (Context.getCanonicalType(FromArgType)
1163            == Context.getCanonicalType(ToArgType)) {
1164        // Okay, the types match exactly. Nothing to do.
1165      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1166                                         ConvertedType, IncompatibleObjC)) {
1167        // Okay, we have an Objective-C pointer conversion.
1168        HasObjCConversion = true;
1169      } else {
1170        // Argument types are too different. Abort.
1171        return false;
1172      }
1173    }
1174
1175    if (HasObjCConversion) {
1176      // We had an Objective-C conversion. Allow this pointer
1177      // conversion, but complain about it.
1178      ConvertedType = ToType;
1179      IncompatibleObjC = true;
1180      return true;
1181    }
1182  }
1183
1184  return false;
1185}
1186
1187/// CheckPointerConversion - Check the pointer conversion from the
1188/// expression From to the type ToType. This routine checks for
1189/// ambiguous or inaccessible derived-to-base pointer
1190/// conversions for which IsPointerConversion has already returned
1191/// true. It returns true and produces a diagnostic if there was an
1192/// error, or returns false otherwise.
1193bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1194                                  CastExpr::CastKind &Kind,
1195                                  bool IgnoreBaseAccess) {
1196  QualType FromType = From->getType();
1197
1198  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1199    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1200      QualType FromPointeeType = FromPtrType->getPointeeType(),
1201               ToPointeeType   = ToPtrType->getPointeeType();
1202
1203      if (FromPointeeType->isRecordType() &&
1204          ToPointeeType->isRecordType()) {
1205        // We must have a derived-to-base conversion. Check an
1206        // ambiguous or inaccessible conversion.
1207        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1208                                         From->getExprLoc(),
1209                                         From->getSourceRange(),
1210                                         IgnoreBaseAccess))
1211          return true;
1212
1213        // The conversion was successful.
1214        Kind = CastExpr::CK_DerivedToBase;
1215      }
1216    }
1217  if (const ObjCObjectPointerType *FromPtrType =
1218        FromType->getAs<ObjCObjectPointerType>())
1219    if (const ObjCObjectPointerType *ToPtrType =
1220          ToType->getAs<ObjCObjectPointerType>()) {
1221      // Objective-C++ conversions are always okay.
1222      // FIXME: We should have a different class of conversions for the
1223      // Objective-C++ implicit conversions.
1224      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1225        return false;
1226
1227  }
1228  return false;
1229}
1230
1231/// IsMemberPointerConversion - Determines whether the conversion of the
1232/// expression From, which has the (possibly adjusted) type FromType, can be
1233/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1234/// If so, returns true and places the converted type (that might differ from
1235/// ToType in its cv-qualifiers at some level) into ConvertedType.
1236bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1237                                     QualType ToType,
1238                                     bool InOverloadResolution,
1239                                     QualType &ConvertedType) {
1240  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1241  if (!ToTypePtr)
1242    return false;
1243
1244  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1245  if (From->isNullPointerConstant(Context,
1246                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1247                                        : Expr::NPC_ValueDependentIsNull)) {
1248    ConvertedType = ToType;
1249    return true;
1250  }
1251
1252  // Otherwise, both types have to be member pointers.
1253  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1254  if (!FromTypePtr)
1255    return false;
1256
1257  // A pointer to member of B can be converted to a pointer to member of D,
1258  // where D is derived from B (C++ 4.11p2).
1259  QualType FromClass(FromTypePtr->getClass(), 0);
1260  QualType ToClass(ToTypePtr->getClass(), 0);
1261  // FIXME: What happens when these are dependent? Is this function even called?
1262
1263  if (IsDerivedFrom(ToClass, FromClass)) {
1264    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1265                                                 ToClass.getTypePtr());
1266    return true;
1267  }
1268
1269  return false;
1270}
1271
1272/// CheckMemberPointerConversion - Check the member pointer conversion from the
1273/// expression From to the type ToType. This routine checks for ambiguous or
1274/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1275/// for which IsMemberPointerConversion has already returned true. It returns
1276/// true and produces a diagnostic if there was an error, or returns false
1277/// otherwise.
1278bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1279                                        CastExpr::CastKind &Kind,
1280                                        bool IgnoreBaseAccess) {
1281  (void)IgnoreBaseAccess;
1282  QualType FromType = From->getType();
1283  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1284  if (!FromPtrType) {
1285    // This must be a null pointer to member pointer conversion
1286    assert(From->isNullPointerConstant(Context,
1287                                       Expr::NPC_ValueDependentIsNull) &&
1288           "Expr must be null pointer constant!");
1289    Kind = CastExpr::CK_NullToMemberPointer;
1290    return false;
1291  }
1292
1293  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1294  assert(ToPtrType && "No member pointer cast has a target type "
1295                      "that is not a member pointer.");
1296
1297  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1298  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1299
1300  // FIXME: What about dependent types?
1301  assert(FromClass->isRecordType() && "Pointer into non-class.");
1302  assert(ToClass->isRecordType() && "Pointer into non-class.");
1303
1304  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1305                     /*DetectVirtual=*/true);
1306  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1307  assert(DerivationOkay &&
1308         "Should not have been called if derivation isn't OK.");
1309  (void)DerivationOkay;
1310
1311  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1312                                  getUnqualifiedType())) {
1313    // Derivation is ambiguous. Redo the check to find the exact paths.
1314    Paths.clear();
1315    Paths.setRecordingPaths(true);
1316    bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1317    assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1318    (void)StillOkay;
1319
1320    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1321    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1322      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1323    return true;
1324  }
1325
1326  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1327    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1328      << FromClass << ToClass << QualType(VBase, 0)
1329      << From->getSourceRange();
1330    return true;
1331  }
1332
1333  // Must be a base to derived member conversion.
1334  Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1335  return false;
1336}
1337
1338/// IsQualificationConversion - Determines whether the conversion from
1339/// an rvalue of type FromType to ToType is a qualification conversion
1340/// (C++ 4.4).
1341bool
1342Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
1343  FromType = Context.getCanonicalType(FromType);
1344  ToType = Context.getCanonicalType(ToType);
1345
1346  // If FromType and ToType are the same type, this is not a
1347  // qualification conversion.
1348  if (FromType == ToType)
1349    return false;
1350
1351  // (C++ 4.4p4):
1352  //   A conversion can add cv-qualifiers at levels other than the first
1353  //   in multi-level pointers, subject to the following rules: [...]
1354  bool PreviousToQualsIncludeConst = true;
1355  bool UnwrappedAnyPointer = false;
1356  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1357    // Within each iteration of the loop, we check the qualifiers to
1358    // determine if this still looks like a qualification
1359    // conversion. Then, if all is well, we unwrap one more level of
1360    // pointers or pointers-to-members and do it all again
1361    // until there are no more pointers or pointers-to-members left to
1362    // unwrap.
1363    UnwrappedAnyPointer = true;
1364
1365    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1366    //      2,j, and similarly for volatile.
1367    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1368      return false;
1369
1370    //   -- if the cv 1,j and cv 2,j are different, then const is in
1371    //      every cv for 0 < k < j.
1372    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1373        && !PreviousToQualsIncludeConst)
1374      return false;
1375
1376    // Keep track of whether all prior cv-qualifiers in the "to" type
1377    // include const.
1378    PreviousToQualsIncludeConst
1379      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1380  }
1381
1382  // We are left with FromType and ToType being the pointee types
1383  // after unwrapping the original FromType and ToType the same number
1384  // of types. If we unwrapped any pointers, and if FromType and
1385  // ToType have the same unqualified type (since we checked
1386  // qualifiers above), then this is a qualification conversion.
1387  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
1388}
1389
1390/// Determines whether there is a user-defined conversion sequence
1391/// (C++ [over.ics.user]) that converts expression From to the type
1392/// ToType. If such a conversion exists, User will contain the
1393/// user-defined conversion sequence that performs such a conversion
1394/// and this routine will return true. Otherwise, this routine returns
1395/// false and User is unspecified.
1396///
1397/// \param AllowConversionFunctions true if the conversion should
1398/// consider conversion functions at all. If false, only constructors
1399/// will be considered.
1400///
1401/// \param AllowExplicit  true if the conversion should consider C++0x
1402/// "explicit" conversion functions as well as non-explicit conversion
1403/// functions (C++0x [class.conv.fct]p2).
1404///
1405/// \param ForceRValue  true if the expression should be treated as an rvalue
1406/// for overload resolution.
1407/// \param UserCast true if looking for user defined conversion for a static
1408/// cast.
1409OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1410                                          UserDefinedConversionSequence& User,
1411                                            OverloadCandidateSet& CandidateSet,
1412                                                bool AllowConversionFunctions,
1413                                                bool AllowExplicit,
1414                                                bool ForceRValue,
1415                                                bool UserCast) {
1416  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1417    if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1418      // We're not going to find any constructors.
1419    } else if (CXXRecordDecl *ToRecordDecl
1420                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1421      // C++ [over.match.ctor]p1:
1422      //   When objects of class type are direct-initialized (8.5), or
1423      //   copy-initialized from an expression of the same or a
1424      //   derived class type (8.5), overload resolution selects the
1425      //   constructor. [...] For copy-initialization, the candidate
1426      //   functions are all the converting constructors (12.3.1) of
1427      //   that class. The argument list is the expression-list within
1428      //   the parentheses of the initializer.
1429      bool SuppressUserConversions = !UserCast;
1430      if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1431          IsDerivedFrom(From->getType(), ToType)) {
1432        SuppressUserConversions = false;
1433        AllowConversionFunctions = false;
1434      }
1435
1436      DeclarationName ConstructorName
1437        = Context.DeclarationNames.getCXXConstructorName(
1438                          Context.getCanonicalType(ToType).getUnqualifiedType());
1439      DeclContext::lookup_iterator Con, ConEnd;
1440      for (llvm::tie(Con, ConEnd)
1441             = ToRecordDecl->lookup(ConstructorName);
1442           Con != ConEnd; ++Con) {
1443        // Find the constructor (which may be a template).
1444        CXXConstructorDecl *Constructor = 0;
1445        FunctionTemplateDecl *ConstructorTmpl
1446          = dyn_cast<FunctionTemplateDecl>(*Con);
1447        if (ConstructorTmpl)
1448          Constructor
1449            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1450        else
1451          Constructor = cast<CXXConstructorDecl>(*Con);
1452
1453        if (!Constructor->isInvalidDecl() &&
1454            Constructor->isConvertingConstructor(AllowExplicit)) {
1455          if (ConstructorTmpl)
1456            AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1457                                         &From, 1, CandidateSet,
1458                                         SuppressUserConversions, ForceRValue);
1459          else
1460            // Allow one user-defined conversion when user specifies a
1461            // From->ToType conversion via an static cast (c-style, etc).
1462            AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1463                                 SuppressUserConversions, ForceRValue);
1464        }
1465      }
1466    }
1467  }
1468
1469  if (!AllowConversionFunctions) {
1470    // Don't allow any conversion functions to enter the overload set.
1471  } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1472                                 PDiag(0)
1473                                   << From->getSourceRange())) {
1474    // No conversion functions from incomplete types.
1475  } else if (const RecordType *FromRecordType
1476               = From->getType()->getAs<RecordType>()) {
1477    if (CXXRecordDecl *FromRecordDecl
1478         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1479      // Add all of the conversion functions as candidates.
1480      const UnresolvedSet *Conversions
1481        = FromRecordDecl->getVisibleConversionFunctions();
1482      for (UnresolvedSet::iterator I = Conversions->begin(),
1483             E = Conversions->end(); I != E; ++I) {
1484        NamedDecl *D = *I;
1485        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1486        if (isa<UsingShadowDecl>(D))
1487          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1488
1489        CXXConversionDecl *Conv;
1490        FunctionTemplateDecl *ConvTemplate;
1491        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
1492          Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1493        else
1494          Conv = dyn_cast<CXXConversionDecl>(*I);
1495
1496        if (AllowExplicit || !Conv->isExplicit()) {
1497          if (ConvTemplate)
1498            AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1499                                           From, ToType, CandidateSet);
1500          else
1501            AddConversionCandidate(Conv, ActingContext, From, ToType,
1502                                   CandidateSet);
1503        }
1504      }
1505    }
1506  }
1507
1508  OverloadCandidateSet::iterator Best;
1509  switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1510    case OR_Success:
1511      // Record the standard conversion we used and the conversion function.
1512      if (CXXConstructorDecl *Constructor
1513            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1514        // C++ [over.ics.user]p1:
1515        //   If the user-defined conversion is specified by a
1516        //   constructor (12.3.1), the initial standard conversion
1517        //   sequence converts the source type to the type required by
1518        //   the argument of the constructor.
1519        //
1520        QualType ThisType = Constructor->getThisType(Context);
1521        if (Best->Conversions[0].ConversionKind ==
1522            ImplicitConversionSequence::EllipsisConversion)
1523          User.EllipsisConversion = true;
1524        else {
1525          User.Before = Best->Conversions[0].Standard;
1526          User.EllipsisConversion = false;
1527        }
1528        User.ConversionFunction = Constructor;
1529        User.After.setAsIdentityConversion();
1530        User.After.FromTypePtr
1531          = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
1532        User.After.ToTypePtr = ToType.getAsOpaquePtr();
1533        return OR_Success;
1534      } else if (CXXConversionDecl *Conversion
1535                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1536        // C++ [over.ics.user]p1:
1537        //
1538        //   [...] If the user-defined conversion is specified by a
1539        //   conversion function (12.3.2), the initial standard
1540        //   conversion sequence converts the source type to the
1541        //   implicit object parameter of the conversion function.
1542        User.Before = Best->Conversions[0].Standard;
1543        User.ConversionFunction = Conversion;
1544        User.EllipsisConversion = false;
1545
1546        // C++ [over.ics.user]p2:
1547        //   The second standard conversion sequence converts the
1548        //   result of the user-defined conversion to the target type
1549        //   for the sequence. Since an implicit conversion sequence
1550        //   is an initialization, the special rules for
1551        //   initialization by user-defined conversion apply when
1552        //   selecting the best user-defined conversion for a
1553        //   user-defined conversion sequence (see 13.3.3 and
1554        //   13.3.3.1).
1555        User.After = Best->FinalConversion;
1556        return OR_Success;
1557      } else {
1558        assert(false && "Not a constructor or conversion function?");
1559        return OR_No_Viable_Function;
1560      }
1561
1562    case OR_No_Viable_Function:
1563      return OR_No_Viable_Function;
1564    case OR_Deleted:
1565      // No conversion here! We're done.
1566      return OR_Deleted;
1567
1568    case OR_Ambiguous:
1569      return OR_Ambiguous;
1570    }
1571
1572  return OR_No_Viable_Function;
1573}
1574
1575bool
1576Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
1577  ImplicitConversionSequence ICS;
1578  OverloadCandidateSet CandidateSet;
1579  OverloadingResult OvResult =
1580    IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1581                            CandidateSet, true, false, false);
1582  if (OvResult == OR_Ambiguous)
1583    Diag(From->getSourceRange().getBegin(),
1584         diag::err_typecheck_ambiguous_condition)
1585          << From->getType() << ToType << From->getSourceRange();
1586  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1587    Diag(From->getSourceRange().getBegin(),
1588         diag::err_typecheck_nonviable_condition)
1589    << From->getType() << ToType << From->getSourceRange();
1590  else
1591    return false;
1592  PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1593  return true;
1594}
1595
1596/// CompareImplicitConversionSequences - Compare two implicit
1597/// conversion sequences to determine whether one is better than the
1598/// other or if they are indistinguishable (C++ 13.3.3.2).
1599ImplicitConversionSequence::CompareKind
1600Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1601                                         const ImplicitConversionSequence& ICS2)
1602{
1603  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1604  // conversion sequences (as defined in 13.3.3.1)
1605  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1606  //      conversion sequence than a user-defined conversion sequence or
1607  //      an ellipsis conversion sequence, and
1608  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1609  //      conversion sequence than an ellipsis conversion sequence
1610  //      (13.3.3.1.3).
1611  //
1612  if (ICS1.ConversionKind < ICS2.ConversionKind)
1613    return ImplicitConversionSequence::Better;
1614  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1615    return ImplicitConversionSequence::Worse;
1616
1617  // Two implicit conversion sequences of the same form are
1618  // indistinguishable conversion sequences unless one of the
1619  // following rules apply: (C++ 13.3.3.2p3):
1620  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1621    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1622  else if (ICS1.ConversionKind ==
1623             ImplicitConversionSequence::UserDefinedConversion) {
1624    // User-defined conversion sequence U1 is a better conversion
1625    // sequence than another user-defined conversion sequence U2 if
1626    // they contain the same user-defined conversion function or
1627    // constructor and if the second standard conversion sequence of
1628    // U1 is better than the second standard conversion sequence of
1629    // U2 (C++ 13.3.3.2p3).
1630    if (ICS1.UserDefined.ConversionFunction ==
1631          ICS2.UserDefined.ConversionFunction)
1632      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1633                                                ICS2.UserDefined.After);
1634  }
1635
1636  return ImplicitConversionSequence::Indistinguishable;
1637}
1638
1639/// CompareStandardConversionSequences - Compare two standard
1640/// conversion sequences to determine whether one is better than the
1641/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1642ImplicitConversionSequence::CompareKind
1643Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1644                                         const StandardConversionSequence& SCS2)
1645{
1646  // Standard conversion sequence S1 is a better conversion sequence
1647  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1648
1649  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1650  //     sequences in the canonical form defined by 13.3.3.1.1,
1651  //     excluding any Lvalue Transformation; the identity conversion
1652  //     sequence is considered to be a subsequence of any
1653  //     non-identity conversion sequence) or, if not that,
1654  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1655    // Neither is a proper subsequence of the other. Do nothing.
1656    ;
1657  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1658           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1659           (SCS1.Second == ICK_Identity &&
1660            SCS1.Third == ICK_Identity))
1661    // SCS1 is a proper subsequence of SCS2.
1662    return ImplicitConversionSequence::Better;
1663  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1664           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1665           (SCS2.Second == ICK_Identity &&
1666            SCS2.Third == ICK_Identity))
1667    // SCS2 is a proper subsequence of SCS1.
1668    return ImplicitConversionSequence::Worse;
1669
1670  //  -- the rank of S1 is better than the rank of S2 (by the rules
1671  //     defined below), or, if not that,
1672  ImplicitConversionRank Rank1 = SCS1.getRank();
1673  ImplicitConversionRank Rank2 = SCS2.getRank();
1674  if (Rank1 < Rank2)
1675    return ImplicitConversionSequence::Better;
1676  else if (Rank2 < Rank1)
1677    return ImplicitConversionSequence::Worse;
1678
1679  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1680  // are indistinguishable unless one of the following rules
1681  // applies:
1682
1683  //   A conversion that is not a conversion of a pointer, or
1684  //   pointer to member, to bool is better than another conversion
1685  //   that is such a conversion.
1686  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1687    return SCS2.isPointerConversionToBool()
1688             ? ImplicitConversionSequence::Better
1689             : ImplicitConversionSequence::Worse;
1690
1691  // C++ [over.ics.rank]p4b2:
1692  //
1693  //   If class B is derived directly or indirectly from class A,
1694  //   conversion of B* to A* is better than conversion of B* to
1695  //   void*, and conversion of A* to void* is better than conversion
1696  //   of B* to void*.
1697  bool SCS1ConvertsToVoid
1698    = SCS1.isPointerConversionToVoidPointer(Context);
1699  bool SCS2ConvertsToVoid
1700    = SCS2.isPointerConversionToVoidPointer(Context);
1701  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1702    // Exactly one of the conversion sequences is a conversion to
1703    // a void pointer; it's the worse conversion.
1704    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1705                              : ImplicitConversionSequence::Worse;
1706  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1707    // Neither conversion sequence converts to a void pointer; compare
1708    // their derived-to-base conversions.
1709    if (ImplicitConversionSequence::CompareKind DerivedCK
1710          = CompareDerivedToBaseConversions(SCS1, SCS2))
1711      return DerivedCK;
1712  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1713    // Both conversion sequences are conversions to void
1714    // pointers. Compare the source types to determine if there's an
1715    // inheritance relationship in their sources.
1716    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1717    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1718
1719    // Adjust the types we're converting from via the array-to-pointer
1720    // conversion, if we need to.
1721    if (SCS1.First == ICK_Array_To_Pointer)
1722      FromType1 = Context.getArrayDecayedType(FromType1);
1723    if (SCS2.First == ICK_Array_To_Pointer)
1724      FromType2 = Context.getArrayDecayedType(FromType2);
1725
1726    QualType FromPointee1
1727      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1728    QualType FromPointee2
1729      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1730
1731    if (IsDerivedFrom(FromPointee2, FromPointee1))
1732      return ImplicitConversionSequence::Better;
1733    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1734      return ImplicitConversionSequence::Worse;
1735
1736    // Objective-C++: If one interface is more specific than the
1737    // other, it is the better one.
1738    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1739    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1740    if (FromIface1 && FromIface1) {
1741      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1742        return ImplicitConversionSequence::Better;
1743      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1744        return ImplicitConversionSequence::Worse;
1745    }
1746  }
1747
1748  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1749  // bullet 3).
1750  if (ImplicitConversionSequence::CompareKind QualCK
1751        = CompareQualificationConversions(SCS1, SCS2))
1752    return QualCK;
1753
1754  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1755    // C++0x [over.ics.rank]p3b4:
1756    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1757    //      implicit object parameter of a non-static member function declared
1758    //      without a ref-qualifier, and S1 binds an rvalue reference to an
1759    //      rvalue and S2 binds an lvalue reference.
1760    // FIXME: We don't know if we're dealing with the implicit object parameter,
1761    // or if the member function in this case has a ref qualifier.
1762    // (Of course, we don't have ref qualifiers yet.)
1763    if (SCS1.RRefBinding != SCS2.RRefBinding)
1764      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1765                              : ImplicitConversionSequence::Worse;
1766
1767    // C++ [over.ics.rank]p3b4:
1768    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1769    //      which the references refer are the same type except for
1770    //      top-level cv-qualifiers, and the type to which the reference
1771    //      initialized by S2 refers is more cv-qualified than the type
1772    //      to which the reference initialized by S1 refers.
1773    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1774    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1775    T1 = Context.getCanonicalType(T1);
1776    T2 = Context.getCanonicalType(T2);
1777    if (Context.hasSameUnqualifiedType(T1, T2)) {
1778      if (T2.isMoreQualifiedThan(T1))
1779        return ImplicitConversionSequence::Better;
1780      else if (T1.isMoreQualifiedThan(T2))
1781        return ImplicitConversionSequence::Worse;
1782    }
1783  }
1784
1785  return ImplicitConversionSequence::Indistinguishable;
1786}
1787
1788/// CompareQualificationConversions - Compares two standard conversion
1789/// sequences to determine whether they can be ranked based on their
1790/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1791ImplicitConversionSequence::CompareKind
1792Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1793                                      const StandardConversionSequence& SCS2) {
1794  // C++ 13.3.3.2p3:
1795  //  -- S1 and S2 differ only in their qualification conversion and
1796  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1797  //     cv-qualification signature of type T1 is a proper subset of
1798  //     the cv-qualification signature of type T2, and S1 is not the
1799  //     deprecated string literal array-to-pointer conversion (4.2).
1800  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1801      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1802    return ImplicitConversionSequence::Indistinguishable;
1803
1804  // FIXME: the example in the standard doesn't use a qualification
1805  // conversion (!)
1806  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1807  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1808  T1 = Context.getCanonicalType(T1);
1809  T2 = Context.getCanonicalType(T2);
1810
1811  // If the types are the same, we won't learn anything by unwrapped
1812  // them.
1813  if (Context.hasSameUnqualifiedType(T1, T2))
1814    return ImplicitConversionSequence::Indistinguishable;
1815
1816  ImplicitConversionSequence::CompareKind Result
1817    = ImplicitConversionSequence::Indistinguishable;
1818  while (UnwrapSimilarPointerTypes(T1, T2)) {
1819    // Within each iteration of the loop, we check the qualifiers to
1820    // determine if this still looks like a qualification
1821    // conversion. Then, if all is well, we unwrap one more level of
1822    // pointers or pointers-to-members and do it all again
1823    // until there are no more pointers or pointers-to-members left
1824    // to unwrap. This essentially mimics what
1825    // IsQualificationConversion does, but here we're checking for a
1826    // strict subset of qualifiers.
1827    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1828      // The qualifiers are the same, so this doesn't tell us anything
1829      // about how the sequences rank.
1830      ;
1831    else if (T2.isMoreQualifiedThan(T1)) {
1832      // T1 has fewer qualifiers, so it could be the better sequence.
1833      if (Result == ImplicitConversionSequence::Worse)
1834        // Neither has qualifiers that are a subset of the other's
1835        // qualifiers.
1836        return ImplicitConversionSequence::Indistinguishable;
1837
1838      Result = ImplicitConversionSequence::Better;
1839    } else if (T1.isMoreQualifiedThan(T2)) {
1840      // T2 has fewer qualifiers, so it could be the better sequence.
1841      if (Result == ImplicitConversionSequence::Better)
1842        // Neither has qualifiers that are a subset of the other's
1843        // qualifiers.
1844        return ImplicitConversionSequence::Indistinguishable;
1845
1846      Result = ImplicitConversionSequence::Worse;
1847    } else {
1848      // Qualifiers are disjoint.
1849      return ImplicitConversionSequence::Indistinguishable;
1850    }
1851
1852    // If the types after this point are equivalent, we're done.
1853    if (Context.hasSameUnqualifiedType(T1, T2))
1854      break;
1855  }
1856
1857  // Check that the winning standard conversion sequence isn't using
1858  // the deprecated string literal array to pointer conversion.
1859  switch (Result) {
1860  case ImplicitConversionSequence::Better:
1861    if (SCS1.Deprecated)
1862      Result = ImplicitConversionSequence::Indistinguishable;
1863    break;
1864
1865  case ImplicitConversionSequence::Indistinguishable:
1866    break;
1867
1868  case ImplicitConversionSequence::Worse:
1869    if (SCS2.Deprecated)
1870      Result = ImplicitConversionSequence::Indistinguishable;
1871    break;
1872  }
1873
1874  return Result;
1875}
1876
1877/// CompareDerivedToBaseConversions - Compares two standard conversion
1878/// sequences to determine whether they can be ranked based on their
1879/// various kinds of derived-to-base conversions (C++
1880/// [over.ics.rank]p4b3).  As part of these checks, we also look at
1881/// conversions between Objective-C interface types.
1882ImplicitConversionSequence::CompareKind
1883Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1884                                      const StandardConversionSequence& SCS2) {
1885  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1886  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1887  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1888  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1889
1890  // Adjust the types we're converting from via the array-to-pointer
1891  // conversion, if we need to.
1892  if (SCS1.First == ICK_Array_To_Pointer)
1893    FromType1 = Context.getArrayDecayedType(FromType1);
1894  if (SCS2.First == ICK_Array_To_Pointer)
1895    FromType2 = Context.getArrayDecayedType(FromType2);
1896
1897  // Canonicalize all of the types.
1898  FromType1 = Context.getCanonicalType(FromType1);
1899  ToType1 = Context.getCanonicalType(ToType1);
1900  FromType2 = Context.getCanonicalType(FromType2);
1901  ToType2 = Context.getCanonicalType(ToType2);
1902
1903  // C++ [over.ics.rank]p4b3:
1904  //
1905  //   If class B is derived directly or indirectly from class A and
1906  //   class C is derived directly or indirectly from B,
1907  //
1908  // For Objective-C, we let A, B, and C also be Objective-C
1909  // interfaces.
1910
1911  // Compare based on pointer conversions.
1912  if (SCS1.Second == ICK_Pointer_Conversion &&
1913      SCS2.Second == ICK_Pointer_Conversion &&
1914      /*FIXME: Remove if Objective-C id conversions get their own rank*/
1915      FromType1->isPointerType() && FromType2->isPointerType() &&
1916      ToType1->isPointerType() && ToType2->isPointerType()) {
1917    QualType FromPointee1
1918      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1919    QualType ToPointee1
1920      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1921    QualType FromPointee2
1922      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1923    QualType ToPointee2
1924      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1925
1926    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1927    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1928    const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1929    const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
1930
1931    //   -- conversion of C* to B* is better than conversion of C* to A*,
1932    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1933      if (IsDerivedFrom(ToPointee1, ToPointee2))
1934        return ImplicitConversionSequence::Better;
1935      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1936        return ImplicitConversionSequence::Worse;
1937
1938      if (ToIface1 && ToIface2) {
1939        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1940          return ImplicitConversionSequence::Better;
1941        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1942          return ImplicitConversionSequence::Worse;
1943      }
1944    }
1945
1946    //   -- conversion of B* to A* is better than conversion of C* to A*,
1947    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1948      if (IsDerivedFrom(FromPointee2, FromPointee1))
1949        return ImplicitConversionSequence::Better;
1950      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1951        return ImplicitConversionSequence::Worse;
1952
1953      if (FromIface1 && FromIface2) {
1954        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1955          return ImplicitConversionSequence::Better;
1956        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1957          return ImplicitConversionSequence::Worse;
1958      }
1959    }
1960  }
1961
1962  // Compare based on reference bindings.
1963  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1964      SCS1.Second == ICK_Derived_To_Base) {
1965    //   -- binding of an expression of type C to a reference of type
1966    //      B& is better than binding an expression of type C to a
1967    //      reference of type A&,
1968    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1969        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
1970      if (IsDerivedFrom(ToType1, ToType2))
1971        return ImplicitConversionSequence::Better;
1972      else if (IsDerivedFrom(ToType2, ToType1))
1973        return ImplicitConversionSequence::Worse;
1974    }
1975
1976    //   -- binding of an expression of type B to a reference of type
1977    //      A& is better than binding an expression of type C to a
1978    //      reference of type A&,
1979    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1980        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
1981      if (IsDerivedFrom(FromType2, FromType1))
1982        return ImplicitConversionSequence::Better;
1983      else if (IsDerivedFrom(FromType1, FromType2))
1984        return ImplicitConversionSequence::Worse;
1985    }
1986  }
1987
1988  // Ranking of member-pointer types.
1989  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1990      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1991      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1992    const MemberPointerType * FromMemPointer1 =
1993                                        FromType1->getAs<MemberPointerType>();
1994    const MemberPointerType * ToMemPointer1 =
1995                                          ToType1->getAs<MemberPointerType>();
1996    const MemberPointerType * FromMemPointer2 =
1997                                          FromType2->getAs<MemberPointerType>();
1998    const MemberPointerType * ToMemPointer2 =
1999                                          ToType2->getAs<MemberPointerType>();
2000    const Type *FromPointeeType1 = FromMemPointer1->getClass();
2001    const Type *ToPointeeType1 = ToMemPointer1->getClass();
2002    const Type *FromPointeeType2 = FromMemPointer2->getClass();
2003    const Type *ToPointeeType2 = ToMemPointer2->getClass();
2004    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2005    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2006    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2007    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
2008    // conversion of A::* to B::* is better than conversion of A::* to C::*,
2009    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2010      if (IsDerivedFrom(ToPointee1, ToPointee2))
2011        return ImplicitConversionSequence::Worse;
2012      else if (IsDerivedFrom(ToPointee2, ToPointee1))
2013        return ImplicitConversionSequence::Better;
2014    }
2015    // conversion of B::* to C::* is better than conversion of A::* to C::*
2016    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2017      if (IsDerivedFrom(FromPointee1, FromPointee2))
2018        return ImplicitConversionSequence::Better;
2019      else if (IsDerivedFrom(FromPointee2, FromPointee1))
2020        return ImplicitConversionSequence::Worse;
2021    }
2022  }
2023
2024  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2025      SCS1.Second == ICK_Derived_To_Base) {
2026    //   -- conversion of C to B is better than conversion of C to A,
2027    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2028        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2029      if (IsDerivedFrom(ToType1, ToType2))
2030        return ImplicitConversionSequence::Better;
2031      else if (IsDerivedFrom(ToType2, ToType1))
2032        return ImplicitConversionSequence::Worse;
2033    }
2034
2035    //   -- conversion of B to A is better than conversion of C to A.
2036    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2037        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2038      if (IsDerivedFrom(FromType2, FromType1))
2039        return ImplicitConversionSequence::Better;
2040      else if (IsDerivedFrom(FromType1, FromType2))
2041        return ImplicitConversionSequence::Worse;
2042    }
2043  }
2044
2045  return ImplicitConversionSequence::Indistinguishable;
2046}
2047
2048/// TryCopyInitialization - Try to copy-initialize a value of type
2049/// ToType from the expression From. Return the implicit conversion
2050/// sequence required to pass this argument, which may be a bad
2051/// conversion sequence (meaning that the argument cannot be passed to
2052/// a parameter of this type). If @p SuppressUserConversions, then we
2053/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2054/// then we treat @p From as an rvalue, even if it is an lvalue.
2055ImplicitConversionSequence
2056Sema::TryCopyInitialization(Expr *From, QualType ToType,
2057                            bool SuppressUserConversions, bool ForceRValue,
2058                            bool InOverloadResolution) {
2059  if (ToType->isReferenceType()) {
2060    ImplicitConversionSequence ICS;
2061    CheckReferenceInit(From, ToType,
2062                       /*FIXME:*/From->getLocStart(),
2063                       SuppressUserConversions,
2064                       /*AllowExplicit=*/false,
2065                       ForceRValue,
2066                       &ICS);
2067    return ICS;
2068  } else {
2069    return TryImplicitConversion(From, ToType,
2070                                 SuppressUserConversions,
2071                                 /*AllowExplicit=*/false,
2072                                 ForceRValue,
2073                                 InOverloadResolution);
2074  }
2075}
2076
2077/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2078/// the expression @p From. Returns true (and emits a diagnostic) if there was
2079/// an error, returns false if the initialization succeeded. Elidable should
2080/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2081/// differently in C++0x for this case.
2082bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
2083                                     AssignmentAction Action, bool Elidable) {
2084  if (!getLangOptions().CPlusPlus) {
2085    // In C, argument passing is the same as performing an assignment.
2086    QualType FromType = From->getType();
2087
2088    AssignConvertType ConvTy =
2089      CheckSingleAssignmentConstraints(ToType, From);
2090    if (ConvTy != Compatible &&
2091        CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2092      ConvTy = Compatible;
2093
2094    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2095                                    FromType, From, Action);
2096  }
2097
2098  if (ToType->isReferenceType())
2099    return CheckReferenceInit(From, ToType,
2100                              /*FIXME:*/From->getLocStart(),
2101                              /*SuppressUserConversions=*/false,
2102                              /*AllowExplicit=*/false,
2103                              /*ForceRValue=*/false);
2104
2105  if (!PerformImplicitConversion(From, ToType, Action,
2106                                 /*AllowExplicit=*/false, Elidable))
2107    return false;
2108  if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
2109    return Diag(From->getSourceRange().getBegin(),
2110                diag::err_typecheck_convert_incompatible)
2111      << ToType << From->getType() << Action << From->getSourceRange();
2112  return true;
2113}
2114
2115/// TryObjectArgumentInitialization - Try to initialize the object
2116/// parameter of the given member function (@c Method) from the
2117/// expression @p From.
2118ImplicitConversionSequence
2119Sema::TryObjectArgumentInitialization(QualType FromType,
2120                                      CXXMethodDecl *Method,
2121                                      CXXRecordDecl *ActingContext) {
2122  QualType ClassType = Context.getTypeDeclType(ActingContext);
2123  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2124  //                 const volatile object.
2125  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2126    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2127  QualType ImplicitParamType =  Context.getCVRQualifiedType(ClassType, Quals);
2128
2129  // Set up the conversion sequence as a "bad" conversion, to allow us
2130  // to exit early.
2131  ImplicitConversionSequence ICS;
2132  ICS.Standard.setAsIdentityConversion();
2133  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2134
2135  // We need to have an object of class type.
2136  if (const PointerType *PT = FromType->getAs<PointerType>())
2137    FromType = PT->getPointeeType();
2138
2139  assert(FromType->isRecordType());
2140
2141  // The implicit object parameter is has the type "reference to cv X",
2142  // where X is the class of which the function is a member
2143  // (C++ [over.match.funcs]p4). However, when finding an implicit
2144  // conversion sequence for the argument, we are not allowed to
2145  // create temporaries or perform user-defined conversions
2146  // (C++ [over.match.funcs]p5). We perform a simplified version of
2147  // reference binding here, that allows class rvalues to bind to
2148  // non-constant references.
2149
2150  // First check the qualifiers. We don't care about lvalue-vs-rvalue
2151  // with the implicit object parameter (C++ [over.match.funcs]p5).
2152  QualType FromTypeCanon = Context.getCanonicalType(FromType);
2153  if (ImplicitParamType.getCVRQualifiers()
2154                                    != FromTypeCanon.getLocalCVRQualifiers() &&
2155      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
2156    return ICS;
2157
2158  // Check that we have either the same type or a derived type. It
2159  // affects the conversion rank.
2160  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2161  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
2162    ICS.Standard.Second = ICK_Identity;
2163  else if (IsDerivedFrom(FromType, ClassType))
2164    ICS.Standard.Second = ICK_Derived_To_Base;
2165  else
2166    return ICS;
2167
2168  // Success. Mark this as a reference binding.
2169  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2170  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2171  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2172  ICS.Standard.ReferenceBinding = true;
2173  ICS.Standard.DirectBinding = true;
2174  ICS.Standard.RRefBinding = false;
2175  return ICS;
2176}
2177
2178/// PerformObjectArgumentInitialization - Perform initialization of
2179/// the implicit object parameter for the given Method with the given
2180/// expression.
2181bool
2182Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2183  QualType FromRecordType, DestType;
2184  QualType ImplicitParamRecordType  =
2185    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2186
2187  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
2188    FromRecordType = PT->getPointeeType();
2189    DestType = Method->getThisType(Context);
2190  } else {
2191    FromRecordType = From->getType();
2192    DestType = ImplicitParamRecordType;
2193  }
2194
2195  // Note that we always use the true parent context when performing
2196  // the actual argument initialization.
2197  ImplicitConversionSequence ICS
2198    = TryObjectArgumentInitialization(From->getType(), Method,
2199                                      Method->getParent());
2200  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2201    return Diag(From->getSourceRange().getBegin(),
2202                diag::err_implicit_object_parameter_init)
2203       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2204
2205  if (ICS.Standard.Second == ICK_Derived_To_Base &&
2206      CheckDerivedToBaseConversion(FromRecordType,
2207                                   ImplicitParamRecordType,
2208                                   From->getSourceRange().getBegin(),
2209                                   From->getSourceRange()))
2210    return true;
2211
2212  ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2213                    /*isLvalue=*/true);
2214  return false;
2215}
2216
2217/// TryContextuallyConvertToBool - Attempt to contextually convert the
2218/// expression From to bool (C++0x [conv]p3).
2219ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2220  return TryImplicitConversion(From, Context.BoolTy,
2221                               // FIXME: Are these flags correct?
2222                               /*SuppressUserConversions=*/false,
2223                               /*AllowExplicit=*/true,
2224                               /*ForceRValue=*/false,
2225                               /*InOverloadResolution=*/false);
2226}
2227
2228/// PerformContextuallyConvertToBool - Perform a contextual conversion
2229/// of the expression From to bool (C++0x [conv]p3).
2230bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2231  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2232  if (!PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting))
2233    return false;
2234
2235  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
2236    return  Diag(From->getSourceRange().getBegin(),
2237                 diag::err_typecheck_bool_condition)
2238                  << From->getType() << From->getSourceRange();
2239  return true;
2240}
2241
2242/// AddOverloadCandidate - Adds the given function to the set of
2243/// candidate functions, using the given function call arguments.  If
2244/// @p SuppressUserConversions, then don't allow user-defined
2245/// conversions via constructors or conversion operators.
2246/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2247/// hacky way to implement the overloading rules for elidable copy
2248/// initialization in C++0x (C++0x 12.8p15).
2249///
2250/// \para PartialOverloading true if we are performing "partial" overloading
2251/// based on an incomplete set of function arguments. This feature is used by
2252/// code completion.
2253void
2254Sema::AddOverloadCandidate(FunctionDecl *Function,
2255                           Expr **Args, unsigned NumArgs,
2256                           OverloadCandidateSet& CandidateSet,
2257                           bool SuppressUserConversions,
2258                           bool ForceRValue,
2259                           bool PartialOverloading) {
2260  const FunctionProtoType* Proto
2261    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
2262  assert(Proto && "Functions without a prototype cannot be overloaded");
2263  assert(!isa<CXXConversionDecl>(Function) &&
2264         "Use AddConversionCandidate for conversion functions");
2265  assert(!Function->getDescribedFunctionTemplate() &&
2266         "Use AddTemplateOverloadCandidate for function templates");
2267
2268  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2269    if (!isa<CXXConstructorDecl>(Method)) {
2270      // If we get here, it's because we're calling a member function
2271      // that is named without a member access expression (e.g.,
2272      // "this->f") that was either written explicitly or created
2273      // implicitly. This can happen with a qualified call to a member
2274      // function, e.g., X::f(). We use an empty type for the implied
2275      // object argument (C++ [over.call.func]p3), and the acting context
2276      // is irrelevant.
2277      AddMethodCandidate(Method, Method->getParent(),
2278                         QualType(), Args, NumArgs, CandidateSet,
2279                         SuppressUserConversions, ForceRValue);
2280      return;
2281    }
2282    // We treat a constructor like a non-member function, since its object
2283    // argument doesn't participate in overload resolution.
2284  }
2285
2286  if (!CandidateSet.isNewCandidate(Function))
2287    return;
2288
2289  // Overload resolution is always an unevaluated context.
2290  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2291
2292  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2293    // C++ [class.copy]p3:
2294    //   A member function template is never instantiated to perform the copy
2295    //   of a class object to an object of its class type.
2296    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2297    if (NumArgs == 1 &&
2298        Constructor->isCopyConstructorLikeSpecialization() &&
2299        Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2300      return;
2301  }
2302
2303  // Add this candidate
2304  CandidateSet.push_back(OverloadCandidate());
2305  OverloadCandidate& Candidate = CandidateSet.back();
2306  Candidate.Function = Function;
2307  Candidate.Viable = true;
2308  Candidate.IsSurrogate = false;
2309  Candidate.IgnoreObjectArgument = false;
2310
2311  unsigned NumArgsInProto = Proto->getNumArgs();
2312
2313  // (C++ 13.3.2p2): A candidate function having fewer than m
2314  // parameters is viable only if it has an ellipsis in its parameter
2315  // list (8.3.5).
2316  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2317      !Proto->isVariadic()) {
2318    Candidate.Viable = false;
2319    return;
2320  }
2321
2322  // (C++ 13.3.2p2): A candidate function having more than m parameters
2323  // is viable only if the (m+1)st parameter has a default argument
2324  // (8.3.6). For the purposes of overload resolution, the
2325  // parameter list is truncated on the right, so that there are
2326  // exactly m parameters.
2327  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2328  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
2329    // Not enough arguments.
2330    Candidate.Viable = false;
2331    return;
2332  }
2333
2334  // Determine the implicit conversion sequences for each of the
2335  // arguments.
2336  Candidate.Conversions.resize(NumArgs);
2337  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2338    if (ArgIdx < NumArgsInProto) {
2339      // (C++ 13.3.2p3): for F to be a viable function, there shall
2340      // exist for each argument an implicit conversion sequence
2341      // (13.3.3.1) that converts that argument to the corresponding
2342      // parameter of F.
2343      QualType ParamType = Proto->getArgType(ArgIdx);
2344      Candidate.Conversions[ArgIdx]
2345        = TryCopyInitialization(Args[ArgIdx], ParamType,
2346                                SuppressUserConversions, ForceRValue,
2347                                /*InOverloadResolution=*/true);
2348      if (Candidate.Conversions[ArgIdx].ConversionKind
2349            == ImplicitConversionSequence::BadConversion) {
2350      // 13.3.3.1-p10 If several different sequences of conversions exist that
2351      // each convert the argument to the parameter type, the implicit conversion
2352      // sequence associated with the parameter is defined to be the unique conversion
2353      // sequence designated the ambiguous conversion sequence. For the purpose of
2354      // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2355      // conversion sequence is treated as a user-defined sequence that is
2356      // indistinguishable from any other user-defined conversion sequence
2357        if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
2358          Candidate.Conversions[ArgIdx].ConversionKind =
2359            ImplicitConversionSequence::UserDefinedConversion;
2360          // Set the conversion function to one of them. As due to ambiguity,
2361          // they carry the same weight and is needed for overload resolution
2362          // later.
2363          Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2364            Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2365        }
2366        else {
2367          Candidate.Viable = false;
2368          break;
2369        }
2370      }
2371    } else {
2372      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2373      // argument for which there is no corresponding parameter is
2374      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2375      Candidate.Conversions[ArgIdx].ConversionKind
2376        = ImplicitConversionSequence::EllipsisConversion;
2377    }
2378  }
2379}
2380
2381/// \brief Add all of the function declarations in the given function set to
2382/// the overload canddiate set.
2383void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2384                                 Expr **Args, unsigned NumArgs,
2385                                 OverloadCandidateSet& CandidateSet,
2386                                 bool SuppressUserConversions) {
2387  for (FunctionSet::const_iterator F = Functions.begin(),
2388                                FEnd = Functions.end();
2389       F != FEnd; ++F) {
2390    // FIXME: using declarations
2391    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2392      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2393        AddMethodCandidate(cast<CXXMethodDecl>(FD),
2394                           cast<CXXMethodDecl>(FD)->getParent(),
2395                           Args[0]->getType(), Args + 1, NumArgs - 1,
2396                           CandidateSet, SuppressUserConversions);
2397      else
2398        AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2399                             SuppressUserConversions);
2400    } else {
2401      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2402      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2403          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2404        AddMethodTemplateCandidate(FunTmpl,
2405                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
2406                                   /*FIXME: explicit args */ 0,
2407                                   Args[0]->getType(), Args + 1, NumArgs - 1,
2408                                   CandidateSet,
2409                                   SuppressUserConversions);
2410      else
2411        AddTemplateOverloadCandidate(FunTmpl,
2412                                     /*FIXME: explicit args */ 0,
2413                                     Args, NumArgs, CandidateSet,
2414                                     SuppressUserConversions);
2415    }
2416  }
2417}
2418
2419/// AddMethodCandidate - Adds a named decl (which is some kind of
2420/// method) as a method candidate to the given overload set.
2421void Sema::AddMethodCandidate(NamedDecl *Decl,
2422                              QualType ObjectType,
2423                              Expr **Args, unsigned NumArgs,
2424                              OverloadCandidateSet& CandidateSet,
2425                              bool SuppressUserConversions, bool ForceRValue) {
2426
2427  // FIXME: use this
2428  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
2429
2430  if (isa<UsingShadowDecl>(Decl))
2431    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2432
2433  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2434    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2435           "Expected a member function template");
2436    AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2437                               ObjectType, Args, NumArgs,
2438                               CandidateSet,
2439                               SuppressUserConversions,
2440                               ForceRValue);
2441  } else {
2442    AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2443                       ObjectType, Args, NumArgs,
2444                       CandidateSet, SuppressUserConversions, ForceRValue);
2445  }
2446}
2447
2448/// AddMethodCandidate - Adds the given C++ member function to the set
2449/// of candidate functions, using the given function call arguments
2450/// and the object argument (@c Object). For example, in a call
2451/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2452/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2453/// allow user-defined conversions via constructors or conversion
2454/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2455/// a slightly hacky way to implement the overloading rules for elidable copy
2456/// initialization in C++0x (C++0x 12.8p15).
2457void
2458Sema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2459                         QualType ObjectType, Expr **Args, unsigned NumArgs,
2460                         OverloadCandidateSet& CandidateSet,
2461                         bool SuppressUserConversions, bool ForceRValue) {
2462  const FunctionProtoType* Proto
2463    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
2464  assert(Proto && "Methods without a prototype cannot be overloaded");
2465  assert(!isa<CXXConversionDecl>(Method) &&
2466         "Use AddConversionCandidate for conversion functions");
2467  assert(!isa<CXXConstructorDecl>(Method) &&
2468         "Use AddOverloadCandidate for constructors");
2469
2470  if (!CandidateSet.isNewCandidate(Method))
2471    return;
2472
2473  // Overload resolution is always an unevaluated context.
2474  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2475
2476  // Add this candidate
2477  CandidateSet.push_back(OverloadCandidate());
2478  OverloadCandidate& Candidate = CandidateSet.back();
2479  Candidate.Function = Method;
2480  Candidate.IsSurrogate = false;
2481  Candidate.IgnoreObjectArgument = false;
2482
2483  unsigned NumArgsInProto = Proto->getNumArgs();
2484
2485  // (C++ 13.3.2p2): A candidate function having fewer than m
2486  // parameters is viable only if it has an ellipsis in its parameter
2487  // list (8.3.5).
2488  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2489    Candidate.Viable = false;
2490    return;
2491  }
2492
2493  // (C++ 13.3.2p2): A candidate function having more than m parameters
2494  // is viable only if the (m+1)st parameter has a default argument
2495  // (8.3.6). For the purposes of overload resolution, the
2496  // parameter list is truncated on the right, so that there are
2497  // exactly m parameters.
2498  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2499  if (NumArgs < MinRequiredArgs) {
2500    // Not enough arguments.
2501    Candidate.Viable = false;
2502    return;
2503  }
2504
2505  Candidate.Viable = true;
2506  Candidate.Conversions.resize(NumArgs + 1);
2507
2508  if (Method->isStatic() || ObjectType.isNull())
2509    // The implicit object argument is ignored.
2510    Candidate.IgnoreObjectArgument = true;
2511  else {
2512    // Determine the implicit conversion sequence for the object
2513    // parameter.
2514    Candidate.Conversions[0]
2515      = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
2516    if (Candidate.Conversions[0].ConversionKind
2517          == ImplicitConversionSequence::BadConversion) {
2518      Candidate.Viable = false;
2519      return;
2520    }
2521  }
2522
2523  // Determine the implicit conversion sequences for each of the
2524  // arguments.
2525  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2526    if (ArgIdx < NumArgsInProto) {
2527      // (C++ 13.3.2p3): for F to be a viable function, there shall
2528      // exist for each argument an implicit conversion sequence
2529      // (13.3.3.1) that converts that argument to the corresponding
2530      // parameter of F.
2531      QualType ParamType = Proto->getArgType(ArgIdx);
2532      Candidate.Conversions[ArgIdx + 1]
2533        = TryCopyInitialization(Args[ArgIdx], ParamType,
2534                                SuppressUserConversions, ForceRValue,
2535                                /*InOverloadResolution=*/true);
2536      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2537            == ImplicitConversionSequence::BadConversion) {
2538        Candidate.Viable = false;
2539        break;
2540      }
2541    } else {
2542      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2543      // argument for which there is no corresponding parameter is
2544      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2545      Candidate.Conversions[ArgIdx + 1].ConversionKind
2546        = ImplicitConversionSequence::EllipsisConversion;
2547    }
2548  }
2549}
2550
2551/// \brief Add a C++ member function template as a candidate to the candidate
2552/// set, using template argument deduction to produce an appropriate member
2553/// function template specialization.
2554void
2555Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2556                                 CXXRecordDecl *ActingContext,
2557                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
2558                                 QualType ObjectType,
2559                                 Expr **Args, unsigned NumArgs,
2560                                 OverloadCandidateSet& CandidateSet,
2561                                 bool SuppressUserConversions,
2562                                 bool ForceRValue) {
2563  if (!CandidateSet.isNewCandidate(MethodTmpl))
2564    return;
2565
2566  // C++ [over.match.funcs]p7:
2567  //   In each case where a candidate is a function template, candidate
2568  //   function template specializations are generated using template argument
2569  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2570  //   candidate functions in the usual way.113) A given name can refer to one
2571  //   or more function templates and also to a set of overloaded non-template
2572  //   functions. In such a case, the candidate functions generated from each
2573  //   function template are combined with the set of non-template candidate
2574  //   functions.
2575  TemplateDeductionInfo Info(Context);
2576  FunctionDecl *Specialization = 0;
2577  if (TemplateDeductionResult Result
2578      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
2579                                Args, NumArgs, Specialization, Info)) {
2580        // FIXME: Record what happened with template argument deduction, so
2581        // that we can give the user a beautiful diagnostic.
2582        (void)Result;
2583        return;
2584      }
2585
2586  // Add the function template specialization produced by template argument
2587  // deduction as a candidate.
2588  assert(Specialization && "Missing member function template specialization?");
2589  assert(isa<CXXMethodDecl>(Specialization) &&
2590         "Specialization is not a member function?");
2591  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2592                     ObjectType, Args, NumArgs,
2593                     CandidateSet, SuppressUserConversions, ForceRValue);
2594}
2595
2596/// \brief Add a C++ function template specialization as a candidate
2597/// in the candidate set, using template argument deduction to produce
2598/// an appropriate function template specialization.
2599void
2600Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2601                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
2602                                   Expr **Args, unsigned NumArgs,
2603                                   OverloadCandidateSet& CandidateSet,
2604                                   bool SuppressUserConversions,
2605                                   bool ForceRValue) {
2606  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2607    return;
2608
2609  // C++ [over.match.funcs]p7:
2610  //   In each case where a candidate is a function template, candidate
2611  //   function template specializations are generated using template argument
2612  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2613  //   candidate functions in the usual way.113) A given name can refer to one
2614  //   or more function templates and also to a set of overloaded non-template
2615  //   functions. In such a case, the candidate functions generated from each
2616  //   function template are combined with the set of non-template candidate
2617  //   functions.
2618  TemplateDeductionInfo Info(Context);
2619  FunctionDecl *Specialization = 0;
2620  if (TemplateDeductionResult Result
2621        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2622                                  Args, NumArgs, Specialization, Info)) {
2623    // FIXME: Record what happened with template argument deduction, so
2624    // that we can give the user a beautiful diagnostic.
2625    (void) Result;
2626
2627    CandidateSet.push_back(OverloadCandidate());
2628    OverloadCandidate &Candidate = CandidateSet.back();
2629    Candidate.Function = FunctionTemplate->getTemplatedDecl();
2630    Candidate.Viable = false;
2631    Candidate.IsSurrogate = false;
2632    Candidate.IgnoreObjectArgument = false;
2633    return;
2634  }
2635
2636  // Add the function template specialization produced by template argument
2637  // deduction as a candidate.
2638  assert(Specialization && "Missing function template specialization?");
2639  AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2640                       SuppressUserConversions, ForceRValue);
2641}
2642
2643/// AddConversionCandidate - Add a C++ conversion function as a
2644/// candidate in the candidate set (C++ [over.match.conv],
2645/// C++ [over.match.copy]). From is the expression we're converting from,
2646/// and ToType is the type that we're eventually trying to convert to
2647/// (which may or may not be the same type as the type that the
2648/// conversion function produces).
2649void
2650Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2651                             CXXRecordDecl *ActingContext,
2652                             Expr *From, QualType ToType,
2653                             OverloadCandidateSet& CandidateSet) {
2654  assert(!Conversion->getDescribedFunctionTemplate() &&
2655         "Conversion function templates use AddTemplateConversionCandidate");
2656
2657  if (!CandidateSet.isNewCandidate(Conversion))
2658    return;
2659
2660  // Overload resolution is always an unevaluated context.
2661  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2662
2663  // Add this candidate
2664  CandidateSet.push_back(OverloadCandidate());
2665  OverloadCandidate& Candidate = CandidateSet.back();
2666  Candidate.Function = Conversion;
2667  Candidate.IsSurrogate = false;
2668  Candidate.IgnoreObjectArgument = false;
2669  Candidate.FinalConversion.setAsIdentityConversion();
2670  Candidate.FinalConversion.FromTypePtr
2671    = Conversion->getConversionType().getAsOpaquePtr();
2672  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2673
2674  // Determine the implicit conversion sequence for the implicit
2675  // object parameter.
2676  Candidate.Viable = true;
2677  Candidate.Conversions.resize(1);
2678  Candidate.Conversions[0]
2679    = TryObjectArgumentInitialization(From->getType(), Conversion,
2680                                      ActingContext);
2681  // Conversion functions to a different type in the base class is visible in
2682  // the derived class.  So, a derived to base conversion should not participate
2683  // in overload resolution.
2684  if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2685    Candidate.Conversions[0].Standard.Second = ICK_Identity;
2686  if (Candidate.Conversions[0].ConversionKind
2687      == ImplicitConversionSequence::BadConversion) {
2688    Candidate.Viable = false;
2689    return;
2690  }
2691
2692  // We won't go through a user-define type conversion function to convert a
2693  // derived to base as such conversions are given Conversion Rank. They only
2694  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2695  QualType FromCanon
2696    = Context.getCanonicalType(From->getType().getUnqualifiedType());
2697  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2698  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2699    Candidate.Viable = false;
2700    return;
2701  }
2702
2703
2704  // To determine what the conversion from the result of calling the
2705  // conversion function to the type we're eventually trying to
2706  // convert to (ToType), we need to synthesize a call to the
2707  // conversion function and attempt copy initialization from it. This
2708  // makes sure that we get the right semantics with respect to
2709  // lvalues/rvalues and the type. Fortunately, we can allocate this
2710  // call on the stack and we don't need its arguments to be
2711  // well-formed.
2712  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2713                            From->getLocStart());
2714  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2715                                CastExpr::CK_FunctionToPointerDecay,
2716                                &ConversionRef, false);
2717
2718  // Note that it is safe to allocate CallExpr on the stack here because
2719  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2720  // allocator).
2721  CallExpr Call(Context, &ConversionFn, 0, 0,
2722                Conversion->getConversionType().getNonReferenceType(),
2723                From->getLocStart());
2724  ImplicitConversionSequence ICS =
2725    TryCopyInitialization(&Call, ToType,
2726                          /*SuppressUserConversions=*/true,
2727                          /*ForceRValue=*/false,
2728                          /*InOverloadResolution=*/false);
2729
2730  switch (ICS.ConversionKind) {
2731  case ImplicitConversionSequence::StandardConversion:
2732    Candidate.FinalConversion = ICS.Standard;
2733    break;
2734
2735  case ImplicitConversionSequence::BadConversion:
2736    Candidate.Viable = false;
2737    break;
2738
2739  default:
2740    assert(false &&
2741           "Can only end up with a standard conversion sequence or failure");
2742  }
2743}
2744
2745/// \brief Adds a conversion function template specialization
2746/// candidate to the overload set, using template argument deduction
2747/// to deduce the template arguments of the conversion function
2748/// template from the type that we are converting to (C++
2749/// [temp.deduct.conv]).
2750void
2751Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2752                                     CXXRecordDecl *ActingDC,
2753                                     Expr *From, QualType ToType,
2754                                     OverloadCandidateSet &CandidateSet) {
2755  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2756         "Only conversion function templates permitted here");
2757
2758  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2759    return;
2760
2761  TemplateDeductionInfo Info(Context);
2762  CXXConversionDecl *Specialization = 0;
2763  if (TemplateDeductionResult Result
2764        = DeduceTemplateArguments(FunctionTemplate, ToType,
2765                                  Specialization, Info)) {
2766    // FIXME: Record what happened with template argument deduction, so
2767    // that we can give the user a beautiful diagnostic.
2768    (void)Result;
2769    return;
2770  }
2771
2772  // Add the conversion function template specialization produced by
2773  // template argument deduction as a candidate.
2774  assert(Specialization && "Missing function template specialization?");
2775  AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
2776}
2777
2778/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2779/// converts the given @c Object to a function pointer via the
2780/// conversion function @c Conversion, and then attempts to call it
2781/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2782/// the type of function that we'll eventually be calling.
2783void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2784                                 CXXRecordDecl *ActingContext,
2785                                 const FunctionProtoType *Proto,
2786                                 QualType ObjectType,
2787                                 Expr **Args, unsigned NumArgs,
2788                                 OverloadCandidateSet& CandidateSet) {
2789  if (!CandidateSet.isNewCandidate(Conversion))
2790    return;
2791
2792  // Overload resolution is always an unevaluated context.
2793  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2794
2795  CandidateSet.push_back(OverloadCandidate());
2796  OverloadCandidate& Candidate = CandidateSet.back();
2797  Candidate.Function = 0;
2798  Candidate.Surrogate = Conversion;
2799  Candidate.Viable = true;
2800  Candidate.IsSurrogate = true;
2801  Candidate.IgnoreObjectArgument = false;
2802  Candidate.Conversions.resize(NumArgs + 1);
2803
2804  // Determine the implicit conversion sequence for the implicit
2805  // object parameter.
2806  ImplicitConversionSequence ObjectInit
2807    = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
2808  if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2809    Candidate.Viable = false;
2810    return;
2811  }
2812
2813  // The first conversion is actually a user-defined conversion whose
2814  // first conversion is ObjectInit's standard conversion (which is
2815  // effectively a reference binding). Record it as such.
2816  Candidate.Conversions[0].ConversionKind
2817    = ImplicitConversionSequence::UserDefinedConversion;
2818  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2819  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
2820  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2821  Candidate.Conversions[0].UserDefined.After
2822    = Candidate.Conversions[0].UserDefined.Before;
2823  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2824
2825  // Find the
2826  unsigned NumArgsInProto = Proto->getNumArgs();
2827
2828  // (C++ 13.3.2p2): A candidate function having fewer than m
2829  // parameters is viable only if it has an ellipsis in its parameter
2830  // list (8.3.5).
2831  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2832    Candidate.Viable = false;
2833    return;
2834  }
2835
2836  // Function types don't have any default arguments, so just check if
2837  // we have enough arguments.
2838  if (NumArgs < NumArgsInProto) {
2839    // Not enough arguments.
2840    Candidate.Viable = false;
2841    return;
2842  }
2843
2844  // Determine the implicit conversion sequences for each of the
2845  // arguments.
2846  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2847    if (ArgIdx < NumArgsInProto) {
2848      // (C++ 13.3.2p3): for F to be a viable function, there shall
2849      // exist for each argument an implicit conversion sequence
2850      // (13.3.3.1) that converts that argument to the corresponding
2851      // parameter of F.
2852      QualType ParamType = Proto->getArgType(ArgIdx);
2853      Candidate.Conversions[ArgIdx + 1]
2854        = TryCopyInitialization(Args[ArgIdx], ParamType,
2855                                /*SuppressUserConversions=*/false,
2856                                /*ForceRValue=*/false,
2857                                /*InOverloadResolution=*/false);
2858      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2859            == ImplicitConversionSequence::BadConversion) {
2860        Candidate.Viable = false;
2861        break;
2862      }
2863    } else {
2864      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2865      // argument for which there is no corresponding parameter is
2866      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2867      Candidate.Conversions[ArgIdx + 1].ConversionKind
2868        = ImplicitConversionSequence::EllipsisConversion;
2869    }
2870  }
2871}
2872
2873// FIXME: This will eventually be removed, once we've migrated all of the
2874// operator overloading logic over to the scheme used by binary operators, which
2875// works for template instantiation.
2876void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2877                                 SourceLocation OpLoc,
2878                                 Expr **Args, unsigned NumArgs,
2879                                 OverloadCandidateSet& CandidateSet,
2880                                 SourceRange OpRange) {
2881  FunctionSet Functions;
2882
2883  QualType T1 = Args[0]->getType();
2884  QualType T2;
2885  if (NumArgs > 1)
2886    T2 = Args[1]->getType();
2887
2888  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2889  if (S)
2890    LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2891  ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
2892  AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2893  AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2894  AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
2895}
2896
2897/// \brief Add overload candidates for overloaded operators that are
2898/// member functions.
2899///
2900/// Add the overloaded operator candidates that are member functions
2901/// for the operator Op that was used in an operator expression such
2902/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2903/// CandidateSet will store the added overload candidates. (C++
2904/// [over.match.oper]).
2905void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2906                                       SourceLocation OpLoc,
2907                                       Expr **Args, unsigned NumArgs,
2908                                       OverloadCandidateSet& CandidateSet,
2909                                       SourceRange OpRange) {
2910  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2911
2912  // C++ [over.match.oper]p3:
2913  //   For a unary operator @ with an operand of a type whose
2914  //   cv-unqualified version is T1, and for a binary operator @ with
2915  //   a left operand of a type whose cv-unqualified version is T1 and
2916  //   a right operand of a type whose cv-unqualified version is T2,
2917  //   three sets of candidate functions, designated member
2918  //   candidates, non-member candidates and built-in candidates, are
2919  //   constructed as follows:
2920  QualType T1 = Args[0]->getType();
2921  QualType T2;
2922  if (NumArgs > 1)
2923    T2 = Args[1]->getType();
2924
2925  //     -- If T1 is a class type, the set of member candidates is the
2926  //        result of the qualified lookup of T1::operator@
2927  //        (13.3.1.1.1); otherwise, the set of member candidates is
2928  //        empty.
2929  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
2930    // Complete the type if it can be completed. Otherwise, we're done.
2931    if (RequireCompleteType(OpLoc, T1, PDiag()))
2932      return;
2933
2934    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2935    LookupQualifiedName(Operators, T1Rec->getDecl());
2936    Operators.suppressDiagnostics();
2937
2938    for (LookupResult::iterator Oper = Operators.begin(),
2939                             OperEnd = Operators.end();
2940         Oper != OperEnd;
2941         ++Oper)
2942      AddMethodCandidate(*Oper, Args[0]->getType(),
2943                         Args + 1, NumArgs - 1, CandidateSet,
2944                         /* SuppressUserConversions = */ false);
2945  }
2946}
2947
2948/// AddBuiltinCandidate - Add a candidate for a built-in
2949/// operator. ResultTy and ParamTys are the result and parameter types
2950/// of the built-in candidate, respectively. Args and NumArgs are the
2951/// arguments being passed to the candidate. IsAssignmentOperator
2952/// should be true when this built-in candidate is an assignment
2953/// operator. NumContextualBoolArguments is the number of arguments
2954/// (at the beginning of the argument list) that will be contextually
2955/// converted to bool.
2956void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2957                               Expr **Args, unsigned NumArgs,
2958                               OverloadCandidateSet& CandidateSet,
2959                               bool IsAssignmentOperator,
2960                               unsigned NumContextualBoolArguments) {
2961  // Overload resolution is always an unevaluated context.
2962  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2963
2964  // Add this candidate
2965  CandidateSet.push_back(OverloadCandidate());
2966  OverloadCandidate& Candidate = CandidateSet.back();
2967  Candidate.Function = 0;
2968  Candidate.IsSurrogate = false;
2969  Candidate.IgnoreObjectArgument = false;
2970  Candidate.BuiltinTypes.ResultTy = ResultTy;
2971  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2972    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2973
2974  // Determine the implicit conversion sequences for each of the
2975  // arguments.
2976  Candidate.Viable = true;
2977  Candidate.Conversions.resize(NumArgs);
2978  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2979    // C++ [over.match.oper]p4:
2980    //   For the built-in assignment operators, conversions of the
2981    //   left operand are restricted as follows:
2982    //     -- no temporaries are introduced to hold the left operand, and
2983    //     -- no user-defined conversions are applied to the left
2984    //        operand to achieve a type match with the left-most
2985    //        parameter of a built-in candidate.
2986    //
2987    // We block these conversions by turning off user-defined
2988    // conversions, since that is the only way that initialization of
2989    // a reference to a non-class type can occur from something that
2990    // is not of the same type.
2991    if (ArgIdx < NumContextualBoolArguments) {
2992      assert(ParamTys[ArgIdx] == Context.BoolTy &&
2993             "Contextual conversion to bool requires bool type");
2994      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2995    } else {
2996      Candidate.Conversions[ArgIdx]
2997        = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2998                                ArgIdx == 0 && IsAssignmentOperator,
2999                                /*ForceRValue=*/false,
3000                                /*InOverloadResolution=*/false);
3001    }
3002    if (Candidate.Conversions[ArgIdx].ConversionKind
3003        == ImplicitConversionSequence::BadConversion) {
3004      Candidate.Viable = false;
3005      break;
3006    }
3007  }
3008}
3009
3010/// BuiltinCandidateTypeSet - A set of types that will be used for the
3011/// candidate operator functions for built-in operators (C++
3012/// [over.built]). The types are separated into pointer types and
3013/// enumeration types.
3014class BuiltinCandidateTypeSet  {
3015  /// TypeSet - A set of types.
3016  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
3017
3018  /// PointerTypes - The set of pointer types that will be used in the
3019  /// built-in candidates.
3020  TypeSet PointerTypes;
3021
3022  /// MemberPointerTypes - The set of member pointer types that will be
3023  /// used in the built-in candidates.
3024  TypeSet MemberPointerTypes;
3025
3026  /// EnumerationTypes - The set of enumeration types that will be
3027  /// used in the built-in candidates.
3028  TypeSet EnumerationTypes;
3029
3030  /// Sema - The semantic analysis instance where we are building the
3031  /// candidate type set.
3032  Sema &SemaRef;
3033
3034  /// Context - The AST context in which we will build the type sets.
3035  ASTContext &Context;
3036
3037  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3038                                               const Qualifiers &VisibleQuals);
3039  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
3040
3041public:
3042  /// iterator - Iterates through the types that are part of the set.
3043  typedef TypeSet::iterator iterator;
3044
3045  BuiltinCandidateTypeSet(Sema &SemaRef)
3046    : SemaRef(SemaRef), Context(SemaRef.Context) { }
3047
3048  void AddTypesConvertedFrom(QualType Ty,
3049                             SourceLocation Loc,
3050                             bool AllowUserConversions,
3051                             bool AllowExplicitConversions,
3052                             const Qualifiers &VisibleTypeConversionsQuals);
3053
3054  /// pointer_begin - First pointer type found;
3055  iterator pointer_begin() { return PointerTypes.begin(); }
3056
3057  /// pointer_end - Past the last pointer type found;
3058  iterator pointer_end() { return PointerTypes.end(); }
3059
3060  /// member_pointer_begin - First member pointer type found;
3061  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3062
3063  /// member_pointer_end - Past the last member pointer type found;
3064  iterator member_pointer_end() { return MemberPointerTypes.end(); }
3065
3066  /// enumeration_begin - First enumeration type found;
3067  iterator enumeration_begin() { return EnumerationTypes.begin(); }
3068
3069  /// enumeration_end - Past the last enumeration type found;
3070  iterator enumeration_end() { return EnumerationTypes.end(); }
3071};
3072
3073/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
3074/// the set of pointer types along with any more-qualified variants of
3075/// that type. For example, if @p Ty is "int const *", this routine
3076/// will add "int const *", "int const volatile *", "int const
3077/// restrict *", and "int const volatile restrict *" to the set of
3078/// pointer types. Returns true if the add of @p Ty itself succeeded,
3079/// false otherwise.
3080///
3081/// FIXME: what to do about extended qualifiers?
3082bool
3083BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3084                                             const Qualifiers &VisibleQuals) {
3085
3086  // Insert this type.
3087  if (!PointerTypes.insert(Ty))
3088    return false;
3089
3090  const PointerType *PointerTy = Ty->getAs<PointerType>();
3091  assert(PointerTy && "type was not a pointer type!");
3092
3093  QualType PointeeTy = PointerTy->getPointeeType();
3094  // Don't add qualified variants of arrays. For one, they're not allowed
3095  // (the qualifier would sink to the element type), and for another, the
3096  // only overload situation where it matters is subscript or pointer +- int,
3097  // and those shouldn't have qualifier variants anyway.
3098  if (PointeeTy->isArrayType())
3099    return true;
3100  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3101  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
3102    BaseCVR = Array->getElementType().getCVRQualifiers();
3103  bool hasVolatile = VisibleQuals.hasVolatile();
3104  bool hasRestrict = VisibleQuals.hasRestrict();
3105
3106  // Iterate through all strict supersets of BaseCVR.
3107  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3108    if ((CVR | BaseCVR) != CVR) continue;
3109    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3110    // in the types.
3111    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3112    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
3113    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3114    PointerTypes.insert(Context.getPointerType(QPointeeTy));
3115  }
3116
3117  return true;
3118}
3119
3120/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3121/// to the set of pointer types along with any more-qualified variants of
3122/// that type. For example, if @p Ty is "int const *", this routine
3123/// will add "int const *", "int const volatile *", "int const
3124/// restrict *", and "int const volatile restrict *" to the set of
3125/// pointer types. Returns true if the add of @p Ty itself succeeded,
3126/// false otherwise.
3127///
3128/// FIXME: what to do about extended qualifiers?
3129bool
3130BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3131    QualType Ty) {
3132  // Insert this type.
3133  if (!MemberPointerTypes.insert(Ty))
3134    return false;
3135
3136  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3137  assert(PointerTy && "type was not a member pointer type!");
3138
3139  QualType PointeeTy = PointerTy->getPointeeType();
3140  // Don't add qualified variants of arrays. For one, they're not allowed
3141  // (the qualifier would sink to the element type), and for another, the
3142  // only overload situation where it matters is subscript or pointer +- int,
3143  // and those shouldn't have qualifier variants anyway.
3144  if (PointeeTy->isArrayType())
3145    return true;
3146  const Type *ClassTy = PointerTy->getClass();
3147
3148  // Iterate through all strict supersets of the pointee type's CVR
3149  // qualifiers.
3150  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3151  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3152    if ((CVR | BaseCVR) != CVR) continue;
3153
3154    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3155    MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
3156  }
3157
3158  return true;
3159}
3160
3161/// AddTypesConvertedFrom - Add each of the types to which the type @p
3162/// Ty can be implicit converted to the given set of @p Types. We're
3163/// primarily interested in pointer types and enumeration types. We also
3164/// take member pointer types, for the conditional operator.
3165/// AllowUserConversions is true if we should look at the conversion
3166/// functions of a class type, and AllowExplicitConversions if we
3167/// should also include the explicit conversion functions of a class
3168/// type.
3169void
3170BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
3171                                               SourceLocation Loc,
3172                                               bool AllowUserConversions,
3173                                               bool AllowExplicitConversions,
3174                                               const Qualifiers &VisibleQuals) {
3175  // Only deal with canonical types.
3176  Ty = Context.getCanonicalType(Ty);
3177
3178  // Look through reference types; they aren't part of the type of an
3179  // expression for the purposes of conversions.
3180  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
3181    Ty = RefTy->getPointeeType();
3182
3183  // We don't care about qualifiers on the type.
3184  Ty = Ty.getLocalUnqualifiedType();
3185
3186  // If we're dealing with an array type, decay to the pointer.
3187  if (Ty->isArrayType())
3188    Ty = SemaRef.Context.getArrayDecayedType(Ty);
3189
3190  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
3191    QualType PointeeTy = PointerTy->getPointeeType();
3192
3193    // Insert our type, and its more-qualified variants, into the set
3194    // of types.
3195    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
3196      return;
3197  } else if (Ty->isMemberPointerType()) {
3198    // Member pointers are far easier, since the pointee can't be converted.
3199    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3200      return;
3201  } else if (Ty->isEnumeralType()) {
3202    EnumerationTypes.insert(Ty);
3203  } else if (AllowUserConversions) {
3204    if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
3205      if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
3206        // No conversion functions in incomplete types.
3207        return;
3208      }
3209
3210      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3211      const UnresolvedSet *Conversions
3212        = ClassDecl->getVisibleConversionFunctions();
3213      for (UnresolvedSet::iterator I = Conversions->begin(),
3214             E = Conversions->end(); I != E; ++I) {
3215
3216        // Skip conversion function templates; they don't tell us anything
3217        // about which builtin types we can convert to.
3218        if (isa<FunctionTemplateDecl>(*I))
3219          continue;
3220
3221        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
3222        if (AllowExplicitConversions || !Conv->isExplicit()) {
3223          AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
3224                                VisibleQuals);
3225        }
3226      }
3227    }
3228  }
3229}
3230
3231/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3232/// the volatile- and non-volatile-qualified assignment operators for the
3233/// given type to the candidate set.
3234static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3235                                                   QualType T,
3236                                                   Expr **Args,
3237                                                   unsigned NumArgs,
3238                                    OverloadCandidateSet &CandidateSet) {
3239  QualType ParamTypes[2];
3240
3241  // T& operator=(T&, T)
3242  ParamTypes[0] = S.Context.getLValueReferenceType(T);
3243  ParamTypes[1] = T;
3244  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3245                        /*IsAssignmentOperator=*/true);
3246
3247  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3248    // volatile T& operator=(volatile T&, T)
3249    ParamTypes[0]
3250      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
3251    ParamTypes[1] = T;
3252    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3253                          /*IsAssignmentOperator=*/true);
3254  }
3255}
3256
3257/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3258/// if any, found in visible type conversion functions found in ArgExpr's type.
3259static  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3260    Qualifiers VRQuals;
3261    const RecordType *TyRec;
3262    if (const MemberPointerType *RHSMPType =
3263        ArgExpr->getType()->getAs<MemberPointerType>())
3264      TyRec = cast<RecordType>(RHSMPType->getClass());
3265    else
3266      TyRec = ArgExpr->getType()->getAs<RecordType>();
3267    if (!TyRec) {
3268      // Just to be safe, assume the worst case.
3269      VRQuals.addVolatile();
3270      VRQuals.addRestrict();
3271      return VRQuals;
3272    }
3273
3274    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3275    const UnresolvedSet *Conversions =
3276      ClassDecl->getVisibleConversionFunctions();
3277
3278    for (UnresolvedSet::iterator I = Conversions->begin(),
3279           E = Conversions->end(); I != E; ++I) {
3280      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
3281        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3282        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3283          CanTy = ResTypeRef->getPointeeType();
3284        // Need to go down the pointer/mempointer chain and add qualifiers
3285        // as see them.
3286        bool done = false;
3287        while (!done) {
3288          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3289            CanTy = ResTypePtr->getPointeeType();
3290          else if (const MemberPointerType *ResTypeMPtr =
3291                CanTy->getAs<MemberPointerType>())
3292            CanTy = ResTypeMPtr->getPointeeType();
3293          else
3294            done = true;
3295          if (CanTy.isVolatileQualified())
3296            VRQuals.addVolatile();
3297          if (CanTy.isRestrictQualified())
3298            VRQuals.addRestrict();
3299          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3300            return VRQuals;
3301        }
3302      }
3303    }
3304    return VRQuals;
3305}
3306
3307/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3308/// operator overloads to the candidate set (C++ [over.built]), based
3309/// on the operator @p Op and the arguments given. For example, if the
3310/// operator is a binary '+', this routine might add "int
3311/// operator+(int, int)" to cover integer addition.
3312void
3313Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3314                                   SourceLocation OpLoc,
3315                                   Expr **Args, unsigned NumArgs,
3316                                   OverloadCandidateSet& CandidateSet) {
3317  // The set of "promoted arithmetic types", which are the arithmetic
3318  // types are that preserved by promotion (C++ [over.built]p2). Note
3319  // that the first few of these types are the promoted integral
3320  // types; these types need to be first.
3321  // FIXME: What about complex?
3322  const unsigned FirstIntegralType = 0;
3323  const unsigned LastIntegralType = 13;
3324  const unsigned FirstPromotedIntegralType = 7,
3325                 LastPromotedIntegralType = 13;
3326  const unsigned FirstPromotedArithmeticType = 7,
3327                 LastPromotedArithmeticType = 16;
3328  const unsigned NumArithmeticTypes = 16;
3329  QualType ArithmeticTypes[NumArithmeticTypes] = {
3330    Context.BoolTy, Context.CharTy, Context.WCharTy,
3331// FIXME:   Context.Char16Ty, Context.Char32Ty,
3332    Context.SignedCharTy, Context.ShortTy,
3333    Context.UnsignedCharTy, Context.UnsignedShortTy,
3334    Context.IntTy, Context.LongTy, Context.LongLongTy,
3335    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3336    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3337  };
3338  assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3339         "Invalid first promoted integral type");
3340  assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3341           == Context.UnsignedLongLongTy &&
3342         "Invalid last promoted integral type");
3343  assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3344         "Invalid first promoted arithmetic type");
3345  assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3346            == Context.LongDoubleTy &&
3347         "Invalid last promoted arithmetic type");
3348
3349  // Find all of the types that the arguments can convert to, but only
3350  // if the operator we're looking at has built-in operator candidates
3351  // that make use of these types.
3352  Qualifiers VisibleTypeConversionsQuals;
3353  VisibleTypeConversionsQuals.addConst();
3354  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3355    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3356
3357  BuiltinCandidateTypeSet CandidateTypes(*this);
3358  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3359      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3360      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3361      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3362      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3363      (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3364    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3365      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3366                                           OpLoc,
3367                                           true,
3368                                           (Op == OO_Exclaim ||
3369                                            Op == OO_AmpAmp ||
3370                                            Op == OO_PipePipe),
3371                                           VisibleTypeConversionsQuals);
3372  }
3373
3374  bool isComparison = false;
3375  switch (Op) {
3376  case OO_None:
3377  case NUM_OVERLOADED_OPERATORS:
3378    assert(false && "Expected an overloaded operator");
3379    break;
3380
3381  case OO_Star: // '*' is either unary or binary
3382    if (NumArgs == 1)
3383      goto UnaryStar;
3384    else
3385      goto BinaryStar;
3386    break;
3387
3388  case OO_Plus: // '+' is either unary or binary
3389    if (NumArgs == 1)
3390      goto UnaryPlus;
3391    else
3392      goto BinaryPlus;
3393    break;
3394
3395  case OO_Minus: // '-' is either unary or binary
3396    if (NumArgs == 1)
3397      goto UnaryMinus;
3398    else
3399      goto BinaryMinus;
3400    break;
3401
3402  case OO_Amp: // '&' is either unary or binary
3403    if (NumArgs == 1)
3404      goto UnaryAmp;
3405    else
3406      goto BinaryAmp;
3407
3408  case OO_PlusPlus:
3409  case OO_MinusMinus:
3410    // C++ [over.built]p3:
3411    //
3412    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
3413    //   is either volatile or empty, there exist candidate operator
3414    //   functions of the form
3415    //
3416    //       VQ T&      operator++(VQ T&);
3417    //       T          operator++(VQ T&, int);
3418    //
3419    // C++ [over.built]p4:
3420    //
3421    //   For every pair (T, VQ), where T is an arithmetic type other
3422    //   than bool, and VQ is either volatile or empty, there exist
3423    //   candidate operator functions of the form
3424    //
3425    //       VQ T&      operator--(VQ T&);
3426    //       T          operator--(VQ T&, int);
3427    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3428         Arith < NumArithmeticTypes; ++Arith) {
3429      QualType ArithTy = ArithmeticTypes[Arith];
3430      QualType ParamTypes[2]
3431        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3432
3433      // Non-volatile version.
3434      if (NumArgs == 1)
3435        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3436      else
3437        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3438      // heuristic to reduce number of builtin candidates in the set.
3439      // Add volatile version only if there are conversions to a volatile type.
3440      if (VisibleTypeConversionsQuals.hasVolatile()) {
3441        // Volatile version
3442        ParamTypes[0]
3443          = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3444        if (NumArgs == 1)
3445          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3446        else
3447          AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3448      }
3449    }
3450
3451    // C++ [over.built]p5:
3452    //
3453    //   For every pair (T, VQ), where T is a cv-qualified or
3454    //   cv-unqualified object type, and VQ is either volatile or
3455    //   empty, there exist candidate operator functions of the form
3456    //
3457    //       T*VQ&      operator++(T*VQ&);
3458    //       T*VQ&      operator--(T*VQ&);
3459    //       T*         operator++(T*VQ&, int);
3460    //       T*         operator--(T*VQ&, int);
3461    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3462         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3463      // Skip pointer types that aren't pointers to object types.
3464      if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3465        continue;
3466
3467      QualType ParamTypes[2] = {
3468        Context.getLValueReferenceType(*Ptr), Context.IntTy
3469      };
3470
3471      // Without volatile
3472      if (NumArgs == 1)
3473        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3474      else
3475        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3476
3477      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3478          VisibleTypeConversionsQuals.hasVolatile()) {
3479        // With volatile
3480        ParamTypes[0]
3481          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3482        if (NumArgs == 1)
3483          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3484        else
3485          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3486      }
3487    }
3488    break;
3489
3490  UnaryStar:
3491    // C++ [over.built]p6:
3492    //   For every cv-qualified or cv-unqualified object type T, there
3493    //   exist candidate operator functions of the form
3494    //
3495    //       T&         operator*(T*);
3496    //
3497    // C++ [over.built]p7:
3498    //   For every function type T, there exist candidate operator
3499    //   functions of the form
3500    //       T&         operator*(T*);
3501    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3502         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3503      QualType ParamTy = *Ptr;
3504      QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3505      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3506                          &ParamTy, Args, 1, CandidateSet);
3507    }
3508    break;
3509
3510  UnaryPlus:
3511    // C++ [over.built]p8:
3512    //   For every type T, there exist candidate operator functions of
3513    //   the form
3514    //
3515    //       T*         operator+(T*);
3516    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3517         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3518      QualType ParamTy = *Ptr;
3519      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3520    }
3521
3522    // Fall through
3523
3524  UnaryMinus:
3525    // C++ [over.built]p9:
3526    //  For every promoted arithmetic type T, there exist candidate
3527    //  operator functions of the form
3528    //
3529    //       T         operator+(T);
3530    //       T         operator-(T);
3531    for (unsigned Arith = FirstPromotedArithmeticType;
3532         Arith < LastPromotedArithmeticType; ++Arith) {
3533      QualType ArithTy = ArithmeticTypes[Arith];
3534      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3535    }
3536    break;
3537
3538  case OO_Tilde:
3539    // C++ [over.built]p10:
3540    //   For every promoted integral type T, there exist candidate
3541    //   operator functions of the form
3542    //
3543    //        T         operator~(T);
3544    for (unsigned Int = FirstPromotedIntegralType;
3545         Int < LastPromotedIntegralType; ++Int) {
3546      QualType IntTy = ArithmeticTypes[Int];
3547      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3548    }
3549    break;
3550
3551  case OO_New:
3552  case OO_Delete:
3553  case OO_Array_New:
3554  case OO_Array_Delete:
3555  case OO_Call:
3556    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3557    break;
3558
3559  case OO_Comma:
3560  UnaryAmp:
3561  case OO_Arrow:
3562    // C++ [over.match.oper]p3:
3563    //   -- For the operator ',', the unary operator '&', or the
3564    //      operator '->', the built-in candidates set is empty.
3565    break;
3566
3567  case OO_EqualEqual:
3568  case OO_ExclaimEqual:
3569    // C++ [over.match.oper]p16:
3570    //   For every pointer to member type T, there exist candidate operator
3571    //   functions of the form
3572    //
3573    //        bool operator==(T,T);
3574    //        bool operator!=(T,T);
3575    for (BuiltinCandidateTypeSet::iterator
3576           MemPtr = CandidateTypes.member_pointer_begin(),
3577           MemPtrEnd = CandidateTypes.member_pointer_end();
3578         MemPtr != MemPtrEnd;
3579         ++MemPtr) {
3580      QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3581      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3582    }
3583
3584    // Fall through
3585
3586  case OO_Less:
3587  case OO_Greater:
3588  case OO_LessEqual:
3589  case OO_GreaterEqual:
3590    // C++ [over.built]p15:
3591    //
3592    //   For every pointer or enumeration type T, there exist
3593    //   candidate operator functions of the form
3594    //
3595    //        bool       operator<(T, T);
3596    //        bool       operator>(T, T);
3597    //        bool       operator<=(T, T);
3598    //        bool       operator>=(T, T);
3599    //        bool       operator==(T, T);
3600    //        bool       operator!=(T, T);
3601    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3602         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3603      QualType ParamTypes[2] = { *Ptr, *Ptr };
3604      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3605    }
3606    for (BuiltinCandidateTypeSet::iterator Enum
3607           = CandidateTypes.enumeration_begin();
3608         Enum != CandidateTypes.enumeration_end(); ++Enum) {
3609      QualType ParamTypes[2] = { *Enum, *Enum };
3610      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3611    }
3612
3613    // Fall through.
3614    isComparison = true;
3615
3616  BinaryPlus:
3617  BinaryMinus:
3618    if (!isComparison) {
3619      // We didn't fall through, so we must have OO_Plus or OO_Minus.
3620
3621      // C++ [over.built]p13:
3622      //
3623      //   For every cv-qualified or cv-unqualified object type T
3624      //   there exist candidate operator functions of the form
3625      //
3626      //      T*         operator+(T*, ptrdiff_t);
3627      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
3628      //      T*         operator-(T*, ptrdiff_t);
3629      //      T*         operator+(ptrdiff_t, T*);
3630      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
3631      //
3632      // C++ [over.built]p14:
3633      //
3634      //   For every T, where T is a pointer to object type, there
3635      //   exist candidate operator functions of the form
3636      //
3637      //      ptrdiff_t  operator-(T, T);
3638      for (BuiltinCandidateTypeSet::iterator Ptr
3639             = CandidateTypes.pointer_begin();
3640           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3641        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3642
3643        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3644        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3645
3646        if (Op == OO_Plus) {
3647          // T* operator+(ptrdiff_t, T*);
3648          ParamTypes[0] = ParamTypes[1];
3649          ParamTypes[1] = *Ptr;
3650          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3651        } else {
3652          // ptrdiff_t operator-(T, T);
3653          ParamTypes[1] = *Ptr;
3654          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3655                              Args, 2, CandidateSet);
3656        }
3657      }
3658    }
3659    // Fall through
3660
3661  case OO_Slash:
3662  BinaryStar:
3663  Conditional:
3664    // C++ [over.built]p12:
3665    //
3666    //   For every pair of promoted arithmetic types L and R, there
3667    //   exist candidate operator functions of the form
3668    //
3669    //        LR         operator*(L, R);
3670    //        LR         operator/(L, R);
3671    //        LR         operator+(L, R);
3672    //        LR         operator-(L, R);
3673    //        bool       operator<(L, R);
3674    //        bool       operator>(L, R);
3675    //        bool       operator<=(L, R);
3676    //        bool       operator>=(L, R);
3677    //        bool       operator==(L, R);
3678    //        bool       operator!=(L, R);
3679    //
3680    //   where LR is the result of the usual arithmetic conversions
3681    //   between types L and R.
3682    //
3683    // C++ [over.built]p24:
3684    //
3685    //   For every pair of promoted arithmetic types L and R, there exist
3686    //   candidate operator functions of the form
3687    //
3688    //        LR       operator?(bool, L, R);
3689    //
3690    //   where LR is the result of the usual arithmetic conversions
3691    //   between types L and R.
3692    // Our candidates ignore the first parameter.
3693    for (unsigned Left = FirstPromotedArithmeticType;
3694         Left < LastPromotedArithmeticType; ++Left) {
3695      for (unsigned Right = FirstPromotedArithmeticType;
3696           Right < LastPromotedArithmeticType; ++Right) {
3697        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3698        QualType Result
3699          = isComparison
3700          ? Context.BoolTy
3701          : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3702        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3703      }
3704    }
3705    break;
3706
3707  case OO_Percent:
3708  BinaryAmp:
3709  case OO_Caret:
3710  case OO_Pipe:
3711  case OO_LessLess:
3712  case OO_GreaterGreater:
3713    // C++ [over.built]p17:
3714    //
3715    //   For every pair of promoted integral types L and R, there
3716    //   exist candidate operator functions of the form
3717    //
3718    //      LR         operator%(L, R);
3719    //      LR         operator&(L, R);
3720    //      LR         operator^(L, R);
3721    //      LR         operator|(L, R);
3722    //      L          operator<<(L, R);
3723    //      L          operator>>(L, R);
3724    //
3725    //   where LR is the result of the usual arithmetic conversions
3726    //   between types L and R.
3727    for (unsigned Left = FirstPromotedIntegralType;
3728         Left < LastPromotedIntegralType; ++Left) {
3729      for (unsigned Right = FirstPromotedIntegralType;
3730           Right < LastPromotedIntegralType; ++Right) {
3731        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3732        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3733            ? LandR[0]
3734            : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3735        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3736      }
3737    }
3738    break;
3739
3740  case OO_Equal:
3741    // C++ [over.built]p20:
3742    //
3743    //   For every pair (T, VQ), where T is an enumeration or
3744    //   pointer to member type and VQ is either volatile or
3745    //   empty, there exist candidate operator functions of the form
3746    //
3747    //        VQ T&      operator=(VQ T&, T);
3748    for (BuiltinCandidateTypeSet::iterator
3749           Enum = CandidateTypes.enumeration_begin(),
3750           EnumEnd = CandidateTypes.enumeration_end();
3751         Enum != EnumEnd; ++Enum)
3752      AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3753                                             CandidateSet);
3754    for (BuiltinCandidateTypeSet::iterator
3755           MemPtr = CandidateTypes.member_pointer_begin(),
3756         MemPtrEnd = CandidateTypes.member_pointer_end();
3757         MemPtr != MemPtrEnd; ++MemPtr)
3758      AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3759                                             CandidateSet);
3760      // Fall through.
3761
3762  case OO_PlusEqual:
3763  case OO_MinusEqual:
3764    // C++ [over.built]p19:
3765    //
3766    //   For every pair (T, VQ), where T is any type and VQ is either
3767    //   volatile or empty, there exist candidate operator functions
3768    //   of the form
3769    //
3770    //        T*VQ&      operator=(T*VQ&, T*);
3771    //
3772    // C++ [over.built]p21:
3773    //
3774    //   For every pair (T, VQ), where T is a cv-qualified or
3775    //   cv-unqualified object type and VQ is either volatile or
3776    //   empty, there exist candidate operator functions of the form
3777    //
3778    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
3779    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
3780    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3781         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3782      QualType ParamTypes[2];
3783      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3784
3785      // non-volatile version
3786      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3787      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3788                          /*IsAssigmentOperator=*/Op == OO_Equal);
3789
3790      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3791          VisibleTypeConversionsQuals.hasVolatile()) {
3792        // volatile version
3793        ParamTypes[0]
3794          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3795        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3796                            /*IsAssigmentOperator=*/Op == OO_Equal);
3797      }
3798    }
3799    // Fall through.
3800
3801  case OO_StarEqual:
3802  case OO_SlashEqual:
3803    // C++ [over.built]p18:
3804    //
3805    //   For every triple (L, VQ, R), where L is an arithmetic type,
3806    //   VQ is either volatile or empty, and R is a promoted
3807    //   arithmetic type, there exist candidate operator functions of
3808    //   the form
3809    //
3810    //        VQ L&      operator=(VQ L&, R);
3811    //        VQ L&      operator*=(VQ L&, R);
3812    //        VQ L&      operator/=(VQ L&, R);
3813    //        VQ L&      operator+=(VQ L&, R);
3814    //        VQ L&      operator-=(VQ L&, R);
3815    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3816      for (unsigned Right = FirstPromotedArithmeticType;
3817           Right < LastPromotedArithmeticType; ++Right) {
3818        QualType ParamTypes[2];
3819        ParamTypes[1] = ArithmeticTypes[Right];
3820
3821        // Add this built-in operator as a candidate (VQ is empty).
3822        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3823        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3824                            /*IsAssigmentOperator=*/Op == OO_Equal);
3825
3826        // Add this built-in operator as a candidate (VQ is 'volatile').
3827        if (VisibleTypeConversionsQuals.hasVolatile()) {
3828          ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3829          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3830          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3831                              /*IsAssigmentOperator=*/Op == OO_Equal);
3832        }
3833      }
3834    }
3835    break;
3836
3837  case OO_PercentEqual:
3838  case OO_LessLessEqual:
3839  case OO_GreaterGreaterEqual:
3840  case OO_AmpEqual:
3841  case OO_CaretEqual:
3842  case OO_PipeEqual:
3843    // C++ [over.built]p22:
3844    //
3845    //   For every triple (L, VQ, R), where L is an integral type, VQ
3846    //   is either volatile or empty, and R is a promoted integral
3847    //   type, there exist candidate operator functions of the form
3848    //
3849    //        VQ L&       operator%=(VQ L&, R);
3850    //        VQ L&       operator<<=(VQ L&, R);
3851    //        VQ L&       operator>>=(VQ L&, R);
3852    //        VQ L&       operator&=(VQ L&, R);
3853    //        VQ L&       operator^=(VQ L&, R);
3854    //        VQ L&       operator|=(VQ L&, R);
3855    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3856      for (unsigned Right = FirstPromotedIntegralType;
3857           Right < LastPromotedIntegralType; ++Right) {
3858        QualType ParamTypes[2];
3859        ParamTypes[1] = ArithmeticTypes[Right];
3860
3861        // Add this built-in operator as a candidate (VQ is empty).
3862        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3863        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3864        if (VisibleTypeConversionsQuals.hasVolatile()) {
3865          // Add this built-in operator as a candidate (VQ is 'volatile').
3866          ParamTypes[0] = ArithmeticTypes[Left];
3867          ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3868          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3869          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3870        }
3871      }
3872    }
3873    break;
3874
3875  case OO_Exclaim: {
3876    // C++ [over.operator]p23:
3877    //
3878    //   There also exist candidate operator functions of the form
3879    //
3880    //        bool        operator!(bool);
3881    //        bool        operator&&(bool, bool);     [BELOW]
3882    //        bool        operator||(bool, bool);     [BELOW]
3883    QualType ParamTy = Context.BoolTy;
3884    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3885                        /*IsAssignmentOperator=*/false,
3886                        /*NumContextualBoolArguments=*/1);
3887    break;
3888  }
3889
3890  case OO_AmpAmp:
3891  case OO_PipePipe: {
3892    // C++ [over.operator]p23:
3893    //
3894    //   There also exist candidate operator functions of the form
3895    //
3896    //        bool        operator!(bool);            [ABOVE]
3897    //        bool        operator&&(bool, bool);
3898    //        bool        operator||(bool, bool);
3899    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3900    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3901                        /*IsAssignmentOperator=*/false,
3902                        /*NumContextualBoolArguments=*/2);
3903    break;
3904  }
3905
3906  case OO_Subscript:
3907    // C++ [over.built]p13:
3908    //
3909    //   For every cv-qualified or cv-unqualified object type T there
3910    //   exist candidate operator functions of the form
3911    //
3912    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
3913    //        T&         operator[](T*, ptrdiff_t);
3914    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
3915    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
3916    //        T&         operator[](ptrdiff_t, T*);
3917    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3918         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3919      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3920      QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
3921      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3922
3923      // T& operator[](T*, ptrdiff_t)
3924      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3925
3926      // T& operator[](ptrdiff_t, T*);
3927      ParamTypes[0] = ParamTypes[1];
3928      ParamTypes[1] = *Ptr;
3929      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3930    }
3931    break;
3932
3933  case OO_ArrowStar:
3934    // C++ [over.built]p11:
3935    //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3936    //    C1 is the same type as C2 or is a derived class of C2, T is an object
3937    //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3938    //    there exist candidate operator functions of the form
3939    //    CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3940    //    where CV12 is the union of CV1 and CV2.
3941    {
3942      for (BuiltinCandidateTypeSet::iterator Ptr =
3943             CandidateTypes.pointer_begin();
3944           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3945        QualType C1Ty = (*Ptr);
3946        QualType C1;
3947        QualifierCollector Q1;
3948        if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
3949          C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
3950          if (!isa<RecordType>(C1))
3951            continue;
3952          // heuristic to reduce number of builtin candidates in the set.
3953          // Add volatile/restrict version only if there are conversions to a
3954          // volatile/restrict type.
3955          if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3956            continue;
3957          if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3958            continue;
3959        }
3960        for (BuiltinCandidateTypeSet::iterator
3961             MemPtr = CandidateTypes.member_pointer_begin(),
3962             MemPtrEnd = CandidateTypes.member_pointer_end();
3963             MemPtr != MemPtrEnd; ++MemPtr) {
3964          const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3965          QualType C2 = QualType(mptr->getClass(), 0);
3966          C2 = C2.getUnqualifiedType();
3967          if (C1 != C2 && !IsDerivedFrom(C1, C2))
3968            break;
3969          QualType ParamTypes[2] = { *Ptr, *MemPtr };
3970          // build CV12 T&
3971          QualType T = mptr->getPointeeType();
3972          if (!VisibleTypeConversionsQuals.hasVolatile() &&
3973              T.isVolatileQualified())
3974            continue;
3975          if (!VisibleTypeConversionsQuals.hasRestrict() &&
3976              T.isRestrictQualified())
3977            continue;
3978          T = Q1.apply(T);
3979          QualType ResultTy = Context.getLValueReferenceType(T);
3980          AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3981        }
3982      }
3983    }
3984    break;
3985
3986  case OO_Conditional:
3987    // Note that we don't consider the first argument, since it has been
3988    // contextually converted to bool long ago. The candidates below are
3989    // therefore added as binary.
3990    //
3991    // C++ [over.built]p24:
3992    //   For every type T, where T is a pointer or pointer-to-member type,
3993    //   there exist candidate operator functions of the form
3994    //
3995    //        T        operator?(bool, T, T);
3996    //
3997    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3998         E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3999      QualType ParamTypes[2] = { *Ptr, *Ptr };
4000      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4001    }
4002    for (BuiltinCandidateTypeSet::iterator Ptr =
4003           CandidateTypes.member_pointer_begin(),
4004         E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4005      QualType ParamTypes[2] = { *Ptr, *Ptr };
4006      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4007    }
4008    goto Conditional;
4009  }
4010}
4011
4012/// \brief Add function candidates found via argument-dependent lookup
4013/// to the set of overloading candidates.
4014///
4015/// This routine performs argument-dependent name lookup based on the
4016/// given function name (which may also be an operator name) and adds
4017/// all of the overload candidates found by ADL to the overload
4018/// candidate set (C++ [basic.lookup.argdep]).
4019void
4020Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4021                                           Expr **Args, unsigned NumArgs,
4022                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4023                                           OverloadCandidateSet& CandidateSet,
4024                                           bool PartialOverloading) {
4025  FunctionSet Functions;
4026
4027  // FIXME: Should we be trafficking in canonical function decls throughout?
4028
4029  // Record all of the function candidates that we've already
4030  // added to the overload set, so that we don't add those same
4031  // candidates a second time.
4032  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4033                                   CandEnd = CandidateSet.end();
4034       Cand != CandEnd; ++Cand)
4035    if (Cand->Function) {
4036      Functions.insert(Cand->Function);
4037      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4038        Functions.insert(FunTmpl);
4039    }
4040
4041  // FIXME: Pass in the explicit template arguments?
4042  ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
4043
4044  // Erase all of the candidates we already knew about.
4045  // FIXME: This is suboptimal. Is there a better way?
4046  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4047                                   CandEnd = CandidateSet.end();
4048       Cand != CandEnd; ++Cand)
4049    if (Cand->Function) {
4050      Functions.erase(Cand->Function);
4051      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4052        Functions.erase(FunTmpl);
4053    }
4054
4055  // For each of the ADL candidates we found, add it to the overload
4056  // set.
4057  for (FunctionSet::iterator Func = Functions.begin(),
4058                          FuncEnd = Functions.end();
4059       Func != FuncEnd; ++Func) {
4060    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
4061      if (ExplicitTemplateArgs)
4062        continue;
4063
4064      AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4065                           false, false, PartialOverloading);
4066    } else
4067      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
4068                                   ExplicitTemplateArgs,
4069                                   Args, NumArgs, CandidateSet);
4070  }
4071}
4072
4073/// isBetterOverloadCandidate - Determines whether the first overload
4074/// candidate is a better candidate than the second (C++ 13.3.3p1).
4075bool
4076Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
4077                                const OverloadCandidate& Cand2) {
4078  // Define viable functions to be better candidates than non-viable
4079  // functions.
4080  if (!Cand2.Viable)
4081    return Cand1.Viable;
4082  else if (!Cand1.Viable)
4083    return false;
4084
4085  // C++ [over.match.best]p1:
4086  //
4087  //   -- if F is a static member function, ICS1(F) is defined such
4088  //      that ICS1(F) is neither better nor worse than ICS1(G) for
4089  //      any function G, and, symmetrically, ICS1(G) is neither
4090  //      better nor worse than ICS1(F).
4091  unsigned StartArg = 0;
4092  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4093    StartArg = 1;
4094
4095  // C++ [over.match.best]p1:
4096  //   A viable function F1 is defined to be a better function than another
4097  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
4098  //   conversion sequence than ICSi(F2), and then...
4099  unsigned NumArgs = Cand1.Conversions.size();
4100  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4101  bool HasBetterConversion = false;
4102  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
4103    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4104                                               Cand2.Conversions[ArgIdx])) {
4105    case ImplicitConversionSequence::Better:
4106      // Cand1 has a better conversion sequence.
4107      HasBetterConversion = true;
4108      break;
4109
4110    case ImplicitConversionSequence::Worse:
4111      // Cand1 can't be better than Cand2.
4112      return false;
4113
4114    case ImplicitConversionSequence::Indistinguishable:
4115      // Do nothing.
4116      break;
4117    }
4118  }
4119
4120  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
4121  //       ICSj(F2), or, if not that,
4122  if (HasBetterConversion)
4123    return true;
4124
4125  //     - F1 is a non-template function and F2 is a function template
4126  //       specialization, or, if not that,
4127  if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4128      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4129    return true;
4130
4131  //   -- F1 and F2 are function template specializations, and the function
4132  //      template for F1 is more specialized than the template for F2
4133  //      according to the partial ordering rules described in 14.5.5.2, or,
4134  //      if not that,
4135  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4136      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4137    if (FunctionTemplateDecl *BetterTemplate
4138          = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4139                                       Cand2.Function->getPrimaryTemplate(),
4140                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4141                                                             : TPOC_Call))
4142      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
4143
4144  //   -- the context is an initialization by user-defined conversion
4145  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
4146  //      from the return type of F1 to the destination type (i.e.,
4147  //      the type of the entity being initialized) is a better
4148  //      conversion sequence than the standard conversion sequence
4149  //      from the return type of F2 to the destination type.
4150  if (Cand1.Function && Cand2.Function &&
4151      isa<CXXConversionDecl>(Cand1.Function) &&
4152      isa<CXXConversionDecl>(Cand2.Function)) {
4153    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4154                                               Cand2.FinalConversion)) {
4155    case ImplicitConversionSequence::Better:
4156      // Cand1 has a better conversion sequence.
4157      return true;
4158
4159    case ImplicitConversionSequence::Worse:
4160      // Cand1 can't be better than Cand2.
4161      return false;
4162
4163    case ImplicitConversionSequence::Indistinguishable:
4164      // Do nothing
4165      break;
4166    }
4167  }
4168
4169  return false;
4170}
4171
4172/// \brief Computes the best viable function (C++ 13.3.3)
4173/// within an overload candidate set.
4174///
4175/// \param CandidateSet the set of candidate functions.
4176///
4177/// \param Loc the location of the function name (or operator symbol) for
4178/// which overload resolution occurs.
4179///
4180/// \param Best f overload resolution was successful or found a deleted
4181/// function, Best points to the candidate function found.
4182///
4183/// \returns The result of overload resolution.
4184OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4185                                           SourceLocation Loc,
4186                                        OverloadCandidateSet::iterator& Best) {
4187  // Find the best viable function.
4188  Best = CandidateSet.end();
4189  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4190       Cand != CandidateSet.end(); ++Cand) {
4191    if (Cand->Viable) {
4192      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4193        Best = Cand;
4194    }
4195  }
4196
4197  // If we didn't find any viable functions, abort.
4198  if (Best == CandidateSet.end())
4199    return OR_No_Viable_Function;
4200
4201  // Make sure that this function is better than every other viable
4202  // function. If not, we have an ambiguity.
4203  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4204       Cand != CandidateSet.end(); ++Cand) {
4205    if (Cand->Viable &&
4206        Cand != Best &&
4207        !isBetterOverloadCandidate(*Best, *Cand)) {
4208      Best = CandidateSet.end();
4209      return OR_Ambiguous;
4210    }
4211  }
4212
4213  // Best is the best viable function.
4214  if (Best->Function &&
4215      (Best->Function->isDeleted() ||
4216       Best->Function->getAttr<UnavailableAttr>()))
4217    return OR_Deleted;
4218
4219  // C++ [basic.def.odr]p2:
4220  //   An overloaded function is used if it is selected by overload resolution
4221  //   when referred to from a potentially-evaluated expression. [Note: this
4222  //   covers calls to named functions (5.2.2), operator overloading
4223  //   (clause 13), user-defined conversions (12.3.2), allocation function for
4224  //   placement new (5.3.4), as well as non-default initialization (8.5).
4225  if (Best->Function)
4226    MarkDeclarationReferenced(Loc, Best->Function);
4227  return OR_Success;
4228}
4229
4230/// PrintOverloadCandidates - When overload resolution fails, prints
4231/// diagnostic messages containing the candidates in the candidate
4232/// set. If OnlyViable is true, only viable candidates will be printed.
4233void
4234Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
4235                              bool OnlyViable,
4236                              const char *Opc,
4237                              SourceLocation OpLoc) {
4238  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4239                             LastCand = CandidateSet.end();
4240  bool Reported = false;
4241  for (; Cand != LastCand; ++Cand) {
4242    if (Cand->Viable || !OnlyViable) {
4243      if (Cand->Function) {
4244        if (Cand->Function->isDeleted() ||
4245            Cand->Function->getAttr<UnavailableAttr>()) {
4246          // Deleted or "unavailable" function.
4247          Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4248            << Cand->Function->isDeleted();
4249        } else if (FunctionTemplateDecl *FunTmpl
4250                     = Cand->Function->getPrimaryTemplate()) {
4251          // Function template specialization
4252          // FIXME: Give a better reason!
4253          Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4254            << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4255                              *Cand->Function->getTemplateSpecializationArgs());
4256        } else {
4257          // Normal function
4258          bool errReported = false;
4259          if (!Cand->Viable && Cand->Conversions.size() > 0) {
4260            for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4261              const ImplicitConversionSequence &Conversion =
4262                                                        Cand->Conversions[i];
4263              if ((Conversion.ConversionKind !=
4264                   ImplicitConversionSequence::BadConversion) ||
4265                  Conversion.ConversionFunctionSet.size() == 0)
4266                continue;
4267              Diag(Cand->Function->getLocation(),
4268                   diag::err_ovl_candidate_not_viable) << (i+1);
4269              errReported = true;
4270              for (int j = Conversion.ConversionFunctionSet.size()-1;
4271                   j >= 0; j--) {
4272                FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4273                Diag(Func->getLocation(), diag::err_ovl_candidate);
4274              }
4275            }
4276          }
4277          if (!errReported)
4278            Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
4279        }
4280      } else if (Cand->IsSurrogate) {
4281        // Desugar the type of the surrogate down to a function type,
4282        // retaining as many typedefs as possible while still showing
4283        // the function type (and, therefore, its parameter types).
4284        QualType FnType = Cand->Surrogate->getConversionType();
4285        bool isLValueReference = false;
4286        bool isRValueReference = false;
4287        bool isPointer = false;
4288        if (const LValueReferenceType *FnTypeRef =
4289              FnType->getAs<LValueReferenceType>()) {
4290          FnType = FnTypeRef->getPointeeType();
4291          isLValueReference = true;
4292        } else if (const RValueReferenceType *FnTypeRef =
4293                     FnType->getAs<RValueReferenceType>()) {
4294          FnType = FnTypeRef->getPointeeType();
4295          isRValueReference = true;
4296        }
4297        if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4298          FnType = FnTypePtr->getPointeeType();
4299          isPointer = true;
4300        }
4301        // Desugar down to a function type.
4302        FnType = QualType(FnType->getAs<FunctionType>(), 0);
4303        // Reconstruct the pointer/reference as appropriate.
4304        if (isPointer) FnType = Context.getPointerType(FnType);
4305        if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4306        if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
4307
4308        Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
4309          << FnType;
4310      } else if (OnlyViable) {
4311        assert(Cand->Conversions.size() <= 2 &&
4312               "builtin-binary-operator-not-binary");
4313        std::string TypeStr("operator");
4314        TypeStr += Opc;
4315        TypeStr += "(";
4316        TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4317        if (Cand->Conversions.size() == 1) {
4318          TypeStr += ")";
4319          Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4320        }
4321        else {
4322          TypeStr += ", ";
4323          TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4324          TypeStr += ")";
4325          Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4326        }
4327      }
4328      else if (!Cand->Viable && !Reported) {
4329        // Non-viability might be due to ambiguous user-defined conversions,
4330        // needed for built-in operators. Report them as well, but only once
4331        // as we have typically many built-in candidates.
4332        unsigned NoOperands = Cand->Conversions.size();
4333        for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4334          const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4335          if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4336              ICS.ConversionFunctionSet.empty())
4337            continue;
4338          if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4339                         Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4340            QualType FromTy =
4341              QualType(
4342                     static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4343            Diag(OpLoc,diag::note_ambiguous_type_conversion)
4344                  << FromTy << Func->getConversionType();
4345          }
4346          for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4347            FunctionDecl *Func =
4348              Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4349            Diag(Func->getLocation(),diag::err_ovl_candidate);
4350          }
4351        }
4352        Reported = true;
4353      }
4354    }
4355  }
4356}
4357
4358/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4359/// an overloaded function (C++ [over.over]), where @p From is an
4360/// expression with overloaded function type and @p ToType is the type
4361/// we're trying to resolve to. For example:
4362///
4363/// @code
4364/// int f(double);
4365/// int f(int);
4366///
4367/// int (*pfd)(double) = f; // selects f(double)
4368/// @endcode
4369///
4370/// This routine returns the resulting FunctionDecl if it could be
4371/// resolved, and NULL otherwise. When @p Complain is true, this
4372/// routine will emit diagnostics if there is an error.
4373FunctionDecl *
4374Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
4375                                         bool Complain) {
4376  QualType FunctionType = ToType;
4377  bool IsMember = false;
4378  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
4379    FunctionType = ToTypePtr->getPointeeType();
4380  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
4381    FunctionType = ToTypeRef->getPointeeType();
4382  else if (const MemberPointerType *MemTypePtr =
4383                    ToType->getAs<MemberPointerType>()) {
4384    FunctionType = MemTypePtr->getPointeeType();
4385    IsMember = true;
4386  }
4387
4388  // We only look at pointers or references to functions.
4389  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
4390  if (!FunctionType->isFunctionType())
4391    return 0;
4392
4393  // Find the actual overloaded function declaration.
4394
4395  // C++ [over.over]p1:
4396  //   [...] [Note: any redundant set of parentheses surrounding the
4397  //   overloaded function name is ignored (5.1). ]
4398  Expr *OvlExpr = From->IgnoreParens();
4399
4400  // C++ [over.over]p1:
4401  //   [...] The overloaded function name can be preceded by the &
4402  //   operator.
4403  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4404    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4405      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4406  }
4407
4408  bool HasExplicitTemplateArgs = false;
4409  TemplateArgumentListInfo ExplicitTemplateArgs;
4410
4411  llvm::SmallVector<NamedDecl*,8> Fns;
4412
4413  // Look into the overloaded expression.
4414  if (UnresolvedLookupExpr *UL
4415               = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4416    Fns.append(UL->decls_begin(), UL->decls_end());
4417    if (UL->hasExplicitTemplateArgs()) {
4418      HasExplicitTemplateArgs = true;
4419      UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4420    }
4421  } else if (UnresolvedMemberExpr *ME
4422               = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4423    Fns.append(ME->decls_begin(), ME->decls_end());
4424    if (ME->hasExplicitTemplateArgs()) {
4425      HasExplicitTemplateArgs = true;
4426      ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4427    }
4428  }
4429
4430  // If we didn't actually find anything, we're done.
4431  if (Fns.empty())
4432    return 0;
4433
4434  // Look through all of the overloaded functions, searching for one
4435  // whose type matches exactly.
4436  llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
4437  bool FoundNonTemplateFunction = false;
4438  for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4439         E = Fns.end(); I != E; ++I) {
4440    // C++ [over.over]p3:
4441    //   Non-member functions and static member functions match
4442    //   targets of type "pointer-to-function" or "reference-to-function."
4443    //   Nonstatic member functions match targets of
4444    //   type "pointer-to-member-function."
4445    // Note that according to DR 247, the containing class does not matter.
4446
4447    if (FunctionTemplateDecl *FunctionTemplate
4448          = dyn_cast<FunctionTemplateDecl>(*I)) {
4449      if (CXXMethodDecl *Method
4450            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
4451        // Skip non-static function templates when converting to pointer, and
4452        // static when converting to member pointer.
4453        if (Method->isStatic() == IsMember)
4454          continue;
4455      } else if (IsMember)
4456        continue;
4457
4458      // C++ [over.over]p2:
4459      //   If the name is a function template, template argument deduction is
4460      //   done (14.8.2.2), and if the argument deduction succeeds, the
4461      //   resulting template argument list is used to generate a single
4462      //   function template specialization, which is added to the set of
4463      //   overloaded functions considered.
4464      // FIXME: We don't really want to build the specialization here, do we?
4465      FunctionDecl *Specialization = 0;
4466      TemplateDeductionInfo Info(Context);
4467      if (TemplateDeductionResult Result
4468            = DeduceTemplateArguments(FunctionTemplate,
4469                       (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
4470                                      FunctionType, Specialization, Info)) {
4471        // FIXME: make a note of the failed deduction for diagnostics.
4472        (void)Result;
4473      } else {
4474        // FIXME: If the match isn't exact, shouldn't we just drop this as
4475        // a candidate? Find a testcase before changing the code.
4476        assert(FunctionType
4477                 == Context.getCanonicalType(Specialization->getType()));
4478        Matches.insert(
4479                cast<FunctionDecl>(Specialization->getCanonicalDecl()));
4480      }
4481
4482      continue;
4483    }
4484
4485    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
4486      // Skip non-static functions when converting to pointer, and static
4487      // when converting to member pointer.
4488      if (Method->isStatic() == IsMember)
4489        continue;
4490
4491      // If we have explicit template arguments, skip non-templates.
4492      if (HasExplicitTemplateArgs)
4493        continue;
4494    } else if (IsMember)
4495      continue;
4496
4497    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
4498      QualType ResultTy;
4499      if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4500          IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4501                               ResultTy)) {
4502        Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
4503        FoundNonTemplateFunction = true;
4504      }
4505    }
4506  }
4507
4508  // If there were 0 or 1 matches, we're done.
4509  if (Matches.empty())
4510    return 0;
4511  else if (Matches.size() == 1) {
4512    FunctionDecl *Result = *Matches.begin();
4513    MarkDeclarationReferenced(From->getLocStart(), Result);
4514    return Result;
4515  }
4516
4517  // C++ [over.over]p4:
4518  //   If more than one function is selected, [...]
4519  typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
4520  if (!FoundNonTemplateFunction) {
4521    //   [...] and any given function template specialization F1 is
4522    //   eliminated if the set contains a second function template
4523    //   specialization whose function template is more specialized
4524    //   than the function template of F1 according to the partial
4525    //   ordering rules of 14.5.5.2.
4526
4527    // The algorithm specified above is quadratic. We instead use a
4528    // two-pass algorithm (similar to the one used to identify the
4529    // best viable function in an overload set) that identifies the
4530    // best function template (if it exists).
4531    llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4532                                                         Matches.end());
4533    FunctionDecl *Result =
4534        getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4535                           TPOC_Other, From->getLocStart(),
4536                           PDiag(),
4537                           PDiag(diag::err_addr_ovl_ambiguous)
4538                               << TemplateMatches[0]->getDeclName(),
4539                           PDiag(diag::err_ovl_template_candidate));
4540    MarkDeclarationReferenced(From->getLocStart(), Result);
4541    return Result;
4542  }
4543
4544  //   [...] any function template specializations in the set are
4545  //   eliminated if the set also contains a non-template function, [...]
4546  llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4547  for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4548    if ((*M)->getPrimaryTemplate() == 0)
4549      RemainingMatches.push_back(*M);
4550
4551  // [...] After such eliminations, if any, there shall remain exactly one
4552  // selected function.
4553  if (RemainingMatches.size() == 1) {
4554    FunctionDecl *Result = RemainingMatches.front();
4555    MarkDeclarationReferenced(From->getLocStart(), Result);
4556    return Result;
4557  }
4558
4559  // FIXME: We should probably return the same thing that BestViableFunction
4560  // returns (even if we issue the diagnostics here).
4561  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4562    << RemainingMatches[0]->getDeclName();
4563  for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4564    Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
4565  return 0;
4566}
4567
4568/// \brief Add a single candidate to the overload set.
4569static void AddOverloadedCallCandidate(Sema &S,
4570                                       NamedDecl *Callee,
4571                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4572                                       Expr **Args, unsigned NumArgs,
4573                                       OverloadCandidateSet &CandidateSet,
4574                                       bool PartialOverloading) {
4575  if (isa<UsingShadowDecl>(Callee))
4576    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4577
4578  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4579    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
4580    S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4581                           PartialOverloading);
4582    return;
4583  }
4584
4585  if (FunctionTemplateDecl *FuncTemplate
4586      = dyn_cast<FunctionTemplateDecl>(Callee)) {
4587    S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
4588                                   Args, NumArgs, CandidateSet);
4589    return;
4590  }
4591
4592  assert(false && "unhandled case in overloaded call candidate");
4593
4594  // do nothing?
4595}
4596
4597/// \brief Add the overload candidates named by callee and/or found by argument
4598/// dependent lookup to the given overload set.
4599void Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
4600                                       DeclarationName &UnqualifiedName,
4601                                       bool ArgumentDependentLookup,
4602                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
4603                                       Expr **Args, unsigned NumArgs,
4604                                       OverloadCandidateSet &CandidateSet,
4605                                       bool PartialOverloading) {
4606
4607#ifndef NDEBUG
4608  // Verify that ArgumentDependentLookup is consistent with the rules
4609  // in C++0x [basic.lookup.argdep]p3:
4610  //
4611  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
4612  //   and let Y be the lookup set produced by argument dependent
4613  //   lookup (defined as follows). If X contains
4614  //
4615  //     -- a declaration of a class member, or
4616  //
4617  //     -- a block-scope function declaration that is not a
4618  //        using-declaration, or
4619  //
4620  //     -- a declaration that is neither a function or a function
4621  //        template
4622  //
4623  //   then Y is empty.
4624
4625  if (ArgumentDependentLookup) {
4626    for (unsigned I = 0; I < Fns.size(); ++I) {
4627      assert(!Fns[I]->getDeclContext()->isRecord());
4628      assert(isa<UsingShadowDecl>(Fns[I]) ||
4629             !Fns[I]->getDeclContext()->isFunctionOrMethod());
4630      assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4631    }
4632  }
4633#endif
4634
4635  for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4636         E = Fns.end(); I != E; ++I)
4637    AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
4638                               Args, NumArgs, CandidateSet,
4639                               PartialOverloading);
4640
4641  if (ArgumentDependentLookup)
4642    AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4643                                         ExplicitTemplateArgs,
4644                                         CandidateSet,
4645                                         PartialOverloading);
4646}
4647
4648/// Attempts to recover from a call where no functions were found.
4649///
4650/// Returns true if new candidates were found.
4651static bool AddRecoveryCallCandidates(Sema &SemaRef, Expr *Fn,
4652                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
4653                                      Expr **Args, unsigned NumArgs,
4654                                      OverloadCandidateSet &CandidateSet) {
4655  UnresolvedLookupExpr *ULE
4656    = cast<UnresolvedLookupExpr>(Fn->IgnoreParenCasts());
4657
4658  CXXScopeSpec SS;
4659  if (ULE->getQualifier()) {
4660    SS.setScopeRep(ULE->getQualifier());
4661    SS.setRange(ULE->getQualifierRange());
4662  }
4663
4664  LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
4665                 Sema::LookupOrdinaryName);
4666  if (SemaRef.DiagnoseEmptyLookup(SS, R))
4667    return false;
4668
4669  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
4670    AddOverloadedCallCandidate(SemaRef, *I, ExplicitTemplateArgs,
4671                               Args, NumArgs, CandidateSet, false);
4672  }
4673  return true;
4674}
4675
4676/// ResolveOverloadedCallFn - Given the call expression that calls Fn
4677/// (which eventually refers to the declaration Func) and the call
4678/// arguments Args/NumArgs, attempt to resolve the function call down
4679/// to a specific function. If overload resolution succeeds, returns
4680/// the function declaration produced by overload
4681/// resolution. Otherwise, emits diagnostics, deletes all of the
4682/// arguments and Fn, and returns NULL.
4683FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4684                                     llvm::SmallVectorImpl<NamedDecl*> &Fns,
4685                                            DeclarationName UnqualifiedName,
4686                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4687                                            SourceLocation LParenLoc,
4688                                            Expr **Args, unsigned NumArgs,
4689                                            SourceLocation *CommaLocs,
4690                                            SourceLocation RParenLoc,
4691                                            bool ArgumentDependentLookup) {
4692  OverloadCandidateSet CandidateSet;
4693
4694  // Add the functions denoted by Callee to the set of candidate
4695  // functions.
4696  AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
4697                              ExplicitTemplateArgs, Args, NumArgs,
4698                              CandidateSet);
4699
4700  // If we found nothing, try to recover.
4701  // AddRecoveryCallCandidates diagnoses the error itself, so we just
4702  // bailout out if it fails.
4703  if (CandidateSet.empty() &&
4704      !AddRecoveryCallCandidates(*this, Fn, ExplicitTemplateArgs,
4705                                 Args, NumArgs, CandidateSet)) {
4706    Fn->Destroy(Context);
4707    for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4708      Args[Arg]->Destroy(Context);
4709    return 0;
4710  }
4711
4712  OverloadCandidateSet::iterator Best;
4713  switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
4714  case OR_Success:
4715    return Best->Function;
4716
4717  case OR_No_Viable_Function:
4718    Diag(Fn->getSourceRange().getBegin(),
4719         diag::err_ovl_no_viable_function_in_call)
4720      << UnqualifiedName << Fn->getSourceRange();
4721    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4722    break;
4723
4724  case OR_Ambiguous:
4725    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
4726      << UnqualifiedName << Fn->getSourceRange();
4727    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4728    break;
4729
4730  case OR_Deleted:
4731    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4732      << Best->Function->isDeleted()
4733      << UnqualifiedName
4734      << Fn->getSourceRange();
4735    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4736    break;
4737  }
4738
4739  // Overload resolution failed. Destroy all of the subexpressions and
4740  // return NULL.
4741  Fn->Destroy(Context);
4742  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4743    Args[Arg]->Destroy(Context);
4744  return 0;
4745}
4746
4747static bool IsOverloaded(const Sema::FunctionSet &Functions) {
4748  return Functions.size() > 1 ||
4749    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4750}
4751
4752/// \brief Create a unary operation that may resolve to an overloaded
4753/// operator.
4754///
4755/// \param OpLoc The location of the operator itself (e.g., '*').
4756///
4757/// \param OpcIn The UnaryOperator::Opcode that describes this
4758/// operator.
4759///
4760/// \param Functions The set of non-member functions that will be
4761/// considered by overload resolution. The caller needs to build this
4762/// set based on the context using, e.g.,
4763/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4764/// set should not contain any member functions; those will be added
4765/// by CreateOverloadedUnaryOp().
4766///
4767/// \param input The input argument.
4768Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4769                                                     unsigned OpcIn,
4770                                                     FunctionSet &Functions,
4771                                                     ExprArg input) {
4772  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4773  Expr *Input = (Expr *)input.get();
4774
4775  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4776  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4777  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4778
4779  Expr *Args[2] = { Input, 0 };
4780  unsigned NumArgs = 1;
4781
4782  // For post-increment and post-decrement, add the implicit '0' as
4783  // the second argument, so that we know this is a post-increment or
4784  // post-decrement.
4785  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4786    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4787    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4788                                           SourceLocation());
4789    NumArgs = 2;
4790  }
4791
4792  if (Input->isTypeDependent()) {
4793    UnresolvedLookupExpr *Fn
4794      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4795                                     0, SourceRange(), OpName, OpLoc,
4796                                     /*ADL*/ true, IsOverloaded(Functions));
4797    for (FunctionSet::iterator Func = Functions.begin(),
4798                            FuncEnd = Functions.end();
4799         Func != FuncEnd; ++Func)
4800      Fn->addDecl(*Func);
4801
4802    input.release();
4803    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4804                                                   &Args[0], NumArgs,
4805                                                   Context.DependentTy,
4806                                                   OpLoc));
4807  }
4808
4809  // Build an empty overload set.
4810  OverloadCandidateSet CandidateSet;
4811
4812  // Add the candidates from the given function set.
4813  AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4814
4815  // Add operator candidates that are member functions.
4816  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4817
4818  // Add builtin operator candidates.
4819  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4820
4821  // Perform overload resolution.
4822  OverloadCandidateSet::iterator Best;
4823  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4824  case OR_Success: {
4825    // We found a built-in operator or an overloaded operator.
4826    FunctionDecl *FnDecl = Best->Function;
4827
4828    if (FnDecl) {
4829      // We matched an overloaded operator. Build a call to that
4830      // operator.
4831
4832      // Convert the arguments.
4833      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4834        if (PerformObjectArgumentInitialization(Input, Method))
4835          return ExprError();
4836      } else {
4837        // Convert the arguments.
4838        if (PerformCopyInitialization(Input,
4839                                      FnDecl->getParamDecl(0)->getType(),
4840                                      AA_Passing))
4841          return ExprError();
4842      }
4843
4844      // Determine the result type
4845      QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
4846
4847      // Build the actual expression node.
4848      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4849                                               SourceLocation());
4850      UsualUnaryConversions(FnExpr);
4851
4852      input.release();
4853      Args[0] = Input;
4854      ExprOwningPtr<CallExpr> TheCall(this,
4855        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4856                                          Args, NumArgs, ResultTy, OpLoc));
4857
4858      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4859                              FnDecl))
4860        return ExprError();
4861
4862      return MaybeBindToTemporary(TheCall.release());
4863    } else {
4864      // We matched a built-in operator. Convert the arguments, then
4865      // break out so that we will build the appropriate built-in
4866      // operator node.
4867        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4868                                      Best->Conversions[0], AA_Passing))
4869          return ExprError();
4870
4871        break;
4872      }
4873    }
4874
4875    case OR_No_Viable_Function:
4876      // No viable function; fall through to handling this as a
4877      // built-in operator, which will produce an error message for us.
4878      break;
4879
4880    case OR_Ambiguous:
4881      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4882          << UnaryOperator::getOpcodeStr(Opc)
4883          << Input->getSourceRange();
4884      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4885                              UnaryOperator::getOpcodeStr(Opc), OpLoc);
4886      return ExprError();
4887
4888    case OR_Deleted:
4889      Diag(OpLoc, diag::err_ovl_deleted_oper)
4890        << Best->Function->isDeleted()
4891        << UnaryOperator::getOpcodeStr(Opc)
4892        << Input->getSourceRange();
4893      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4894      return ExprError();
4895    }
4896
4897  // Either we found no viable overloaded operator or we matched a
4898  // built-in operator. In either case, fall through to trying to
4899  // build a built-in operation.
4900  input.release();
4901  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4902}
4903
4904/// \brief Create a binary operation that may resolve to an overloaded
4905/// operator.
4906///
4907/// \param OpLoc The location of the operator itself (e.g., '+').
4908///
4909/// \param OpcIn The BinaryOperator::Opcode that describes this
4910/// operator.
4911///
4912/// \param Functions The set of non-member functions that will be
4913/// considered by overload resolution. The caller needs to build this
4914/// set based on the context using, e.g.,
4915/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4916/// set should not contain any member functions; those will be added
4917/// by CreateOverloadedBinOp().
4918///
4919/// \param LHS Left-hand argument.
4920/// \param RHS Right-hand argument.
4921Sema::OwningExprResult
4922Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
4923                            unsigned OpcIn,
4924                            FunctionSet &Functions,
4925                            Expr *LHS, Expr *RHS) {
4926  Expr *Args[2] = { LHS, RHS };
4927  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
4928
4929  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4930  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4931  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4932
4933  // If either side is type-dependent, create an appropriate dependent
4934  // expression.
4935  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4936    if (Functions.empty()) {
4937      // If there are no functions to store, just build a dependent
4938      // BinaryOperator or CompoundAssignment.
4939      if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4940        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4941                                                  Context.DependentTy, OpLoc));
4942
4943      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4944                                                        Context.DependentTy,
4945                                                        Context.DependentTy,
4946                                                        Context.DependentTy,
4947                                                        OpLoc));
4948    }
4949
4950    UnresolvedLookupExpr *Fn
4951      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4952                                     0, SourceRange(), OpName, OpLoc,
4953                                     /* ADL */ true, IsOverloaded(Functions));
4954
4955    for (FunctionSet::iterator Func = Functions.begin(),
4956                            FuncEnd = Functions.end();
4957         Func != FuncEnd; ++Func)
4958      Fn->addDecl(*Func);
4959
4960    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4961                                                   Args, 2,
4962                                                   Context.DependentTy,
4963                                                   OpLoc));
4964  }
4965
4966  // If this is the .* operator, which is not overloadable, just
4967  // create a built-in binary operator.
4968  if (Opc == BinaryOperator::PtrMemD)
4969    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4970
4971  // If this is the assignment operator, we only perform overload resolution
4972  // if the left-hand side is a class or enumeration type. This is actually
4973  // a hack. The standard requires that we do overload resolution between the
4974  // various built-in candidates, but as DR507 points out, this can lead to
4975  // problems. So we do it this way, which pretty much follows what GCC does.
4976  // Note that we go the traditional code path for compound assignment forms.
4977  if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
4978    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4979
4980  // Build an empty overload set.
4981  OverloadCandidateSet CandidateSet;
4982
4983  // Add the candidates from the given function set.
4984  AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4985
4986  // Add operator candidates that are member functions.
4987  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4988
4989  // Add builtin operator candidates.
4990  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4991
4992  // Perform overload resolution.
4993  OverloadCandidateSet::iterator Best;
4994  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4995    case OR_Success: {
4996      // We found a built-in operator or an overloaded operator.
4997      FunctionDecl *FnDecl = Best->Function;
4998
4999      if (FnDecl) {
5000        // We matched an overloaded operator. Build a call to that
5001        // operator.
5002
5003        // Convert the arguments.
5004        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
5005          if (PerformObjectArgumentInitialization(Args[0], Method) ||
5006              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
5007                                        AA_Passing))
5008            return ExprError();
5009        } else {
5010          // Convert the arguments.
5011          if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
5012                                        AA_Passing) ||
5013              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
5014                                        AA_Passing))
5015            return ExprError();
5016        }
5017
5018        // Determine the result type
5019        QualType ResultTy
5020          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5021        ResultTy = ResultTy.getNonReferenceType();
5022
5023        // Build the actual expression node.
5024        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5025                                                 OpLoc);
5026        UsualUnaryConversions(FnExpr);
5027
5028        ExprOwningPtr<CXXOperatorCallExpr>
5029          TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
5030                                                          Args, 2, ResultTy,
5031                                                          OpLoc));
5032
5033        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
5034                                FnDecl))
5035          return ExprError();
5036
5037        return MaybeBindToTemporary(TheCall.release());
5038      } else {
5039        // We matched a built-in operator. Convert the arguments, then
5040        // break out so that we will build the appropriate built-in
5041        // operator node.
5042        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5043                                      Best->Conversions[0], AA_Passing) ||
5044            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5045                                      Best->Conversions[1], AA_Passing))
5046          return ExprError();
5047
5048        break;
5049      }
5050    }
5051
5052    case OR_No_Viable_Function: {
5053      // C++ [over.match.oper]p9:
5054      //   If the operator is the operator , [...] and there are no
5055      //   viable functions, then the operator is assumed to be the
5056      //   built-in operator and interpreted according to clause 5.
5057      if (Opc == BinaryOperator::Comma)
5058        break;
5059
5060      // For class as left operand for assignment or compound assigment operator
5061      // do not fall through to handling in built-in, but report that no overloaded
5062      // assignment operator found
5063      OwningExprResult Result = ExprError();
5064      if (Args[0]->getType()->isRecordType() &&
5065          Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
5066        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
5067             << BinaryOperator::getOpcodeStr(Opc)
5068             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5069      } else {
5070        // No viable function; try to create a built-in operation, which will
5071        // produce an error. Then, show the non-viable candidates.
5072        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5073      }
5074      assert(Result.isInvalid() &&
5075             "C++ binary operator overloading is missing candidates!");
5076      if (Result.isInvalid())
5077        PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5078                                BinaryOperator::getOpcodeStr(Opc), OpLoc);
5079      return move(Result);
5080    }
5081
5082    case OR_Ambiguous:
5083      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5084          << BinaryOperator::getOpcodeStr(Opc)
5085          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5086      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5087                              BinaryOperator::getOpcodeStr(Opc), OpLoc);
5088      return ExprError();
5089
5090    case OR_Deleted:
5091      Diag(OpLoc, diag::err_ovl_deleted_oper)
5092        << Best->Function->isDeleted()
5093        << BinaryOperator::getOpcodeStr(Opc)
5094        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5095      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5096      return ExprError();
5097    }
5098
5099  // We matched a built-in operator; build it.
5100  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5101}
5102
5103Action::OwningExprResult
5104Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5105                                         SourceLocation RLoc,
5106                                         ExprArg Base, ExprArg Idx) {
5107  Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5108                    static_cast<Expr*>(Idx.get()) };
5109  DeclarationName OpName =
5110      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5111
5112  // If either side is type-dependent, create an appropriate dependent
5113  // expression.
5114  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5115
5116    UnresolvedLookupExpr *Fn
5117      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5118                                     0, SourceRange(), OpName, LLoc,
5119                                     /*ADL*/ true, /*Overloaded*/ false);
5120    // Can't add any actual overloads yet
5121
5122    Base.release();
5123    Idx.release();
5124    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5125                                                   Args, 2,
5126                                                   Context.DependentTy,
5127                                                   RLoc));
5128  }
5129
5130  // Build an empty overload set.
5131  OverloadCandidateSet CandidateSet;
5132
5133  // Subscript can only be overloaded as a member function.
5134
5135  // Add operator candidates that are member functions.
5136  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5137
5138  // Add builtin operator candidates.
5139  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5140
5141  // Perform overload resolution.
5142  OverloadCandidateSet::iterator Best;
5143  switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5144    case OR_Success: {
5145      // We found a built-in operator or an overloaded operator.
5146      FunctionDecl *FnDecl = Best->Function;
5147
5148      if (FnDecl) {
5149        // We matched an overloaded operator. Build a call to that
5150        // operator.
5151
5152        // Convert the arguments.
5153        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5154        if (PerformObjectArgumentInitialization(Args[0], Method) ||
5155            PerformCopyInitialization(Args[1],
5156                                      FnDecl->getParamDecl(0)->getType(),
5157                                      AA_Passing))
5158          return ExprError();
5159
5160        // Determine the result type
5161        QualType ResultTy
5162          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5163        ResultTy = ResultTy.getNonReferenceType();
5164
5165        // Build the actual expression node.
5166        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5167                                                 LLoc);
5168        UsualUnaryConversions(FnExpr);
5169
5170        Base.release();
5171        Idx.release();
5172        ExprOwningPtr<CXXOperatorCallExpr>
5173          TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5174                                                          FnExpr, Args, 2,
5175                                                          ResultTy, RLoc));
5176
5177        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5178                                FnDecl))
5179          return ExprError();
5180
5181        return MaybeBindToTemporary(TheCall.release());
5182      } else {
5183        // We matched a built-in operator. Convert the arguments, then
5184        // break out so that we will build the appropriate built-in
5185        // operator node.
5186        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5187                                      Best->Conversions[0], AA_Passing) ||
5188            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5189                                      Best->Conversions[1], AA_Passing))
5190          return ExprError();
5191
5192        break;
5193      }
5194    }
5195
5196    case OR_No_Viable_Function: {
5197      // No viable function; try to create a built-in operation, which will
5198      // produce an error. Then, show the non-viable candidates.
5199      OwningExprResult Result =
5200          CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5201      assert(Result.isInvalid() &&
5202             "C++ subscript operator overloading is missing candidates!");
5203      if (Result.isInvalid())
5204        PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5205                                "[]", LLoc);
5206      return move(Result);
5207    }
5208
5209    case OR_Ambiguous:
5210      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
5211          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5212      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5213                              "[]", LLoc);
5214      return ExprError();
5215
5216    case OR_Deleted:
5217      Diag(LLoc, diag::err_ovl_deleted_oper)
5218        << Best->Function->isDeleted() << "[]"
5219        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5220      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5221      return ExprError();
5222    }
5223
5224  // We matched a built-in operator; build it.
5225  Base.release();
5226  Idx.release();
5227  return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5228                                         Owned(Args[1]), RLoc);
5229}
5230
5231/// BuildCallToMemberFunction - Build a call to a member
5232/// function. MemExpr is the expression that refers to the member
5233/// function (and includes the object parameter), Args/NumArgs are the
5234/// arguments to the function call (not including the object
5235/// parameter). The caller needs to validate that the member
5236/// expression refers to a member function or an overloaded member
5237/// function.
5238Sema::OwningExprResult
5239Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5240                                SourceLocation LParenLoc, Expr **Args,
5241                                unsigned NumArgs, SourceLocation *CommaLocs,
5242                                SourceLocation RParenLoc) {
5243  // Dig out the member expression. This holds both the object
5244  // argument and the member function we're referring to.
5245  Expr *NakedMemExpr = MemExprE->IgnoreParens();
5246
5247  MemberExpr *MemExpr;
5248  CXXMethodDecl *Method = 0;
5249  if (isa<MemberExpr>(NakedMemExpr)) {
5250    MemExpr = cast<MemberExpr>(NakedMemExpr);
5251    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5252  } else {
5253    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
5254
5255    QualType ObjectType = UnresExpr->getBaseType();
5256
5257    // Add overload candidates
5258    OverloadCandidateSet CandidateSet;
5259
5260    // FIXME: avoid copy.
5261    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5262    if (UnresExpr->hasExplicitTemplateArgs()) {
5263      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5264      TemplateArgs = &TemplateArgsBuffer;
5265    }
5266
5267    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5268           E = UnresExpr->decls_end(); I != E; ++I) {
5269
5270      NamedDecl *Func = *I;
5271      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5272      if (isa<UsingShadowDecl>(Func))
5273        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5274
5275      if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
5276        // If explicit template arguments were provided, we can't call a
5277        // non-template member function.
5278        if (TemplateArgs)
5279          continue;
5280
5281        AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5282                           CandidateSet, /*SuppressUserConversions=*/false);
5283      } else {
5284        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
5285                                   ActingDC, TemplateArgs,
5286                                   ObjectType, Args, NumArgs,
5287                                   CandidateSet,
5288                                   /*SuppressUsedConversions=*/false);
5289      }
5290    }
5291
5292    DeclarationName DeclName = UnresExpr->getMemberName();
5293
5294    OverloadCandidateSet::iterator Best;
5295    switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
5296    case OR_Success:
5297      Method = cast<CXXMethodDecl>(Best->Function);
5298      break;
5299
5300    case OR_No_Viable_Function:
5301      Diag(UnresExpr->getMemberLoc(),
5302           diag::err_ovl_no_viable_member_function_in_call)
5303        << DeclName << MemExprE->getSourceRange();
5304      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5305      // FIXME: Leaking incoming expressions!
5306      return ExprError();
5307
5308    case OR_Ambiguous:
5309      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
5310        << DeclName << MemExprE->getSourceRange();
5311      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5312      // FIXME: Leaking incoming expressions!
5313      return ExprError();
5314
5315    case OR_Deleted:
5316      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
5317        << Best->Function->isDeleted()
5318        << DeclName << MemExprE->getSourceRange();
5319      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5320      // FIXME: Leaking incoming expressions!
5321      return ExprError();
5322    }
5323
5324    MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
5325
5326    // If overload resolution picked a static member, build a
5327    // non-member call based on that function.
5328    if (Method->isStatic()) {
5329      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5330                                   Args, NumArgs, RParenLoc);
5331    }
5332
5333    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
5334  }
5335
5336  assert(Method && "Member call to something that isn't a method?");
5337  ExprOwningPtr<CXXMemberCallExpr>
5338    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
5339                                                  NumArgs,
5340                                  Method->getResultType().getNonReferenceType(),
5341                                  RParenLoc));
5342
5343  // Check for a valid return type.
5344  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5345                          TheCall.get(), Method))
5346    return ExprError();
5347
5348  // Convert the object argument (for a non-static member function call).
5349  Expr *ObjectArg = MemExpr->getBase();
5350  if (!Method->isStatic() &&
5351      PerformObjectArgumentInitialization(ObjectArg, Method))
5352    return ExprError();
5353  MemExpr->setBase(ObjectArg);
5354
5355  // Convert the rest of the arguments
5356  const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
5357  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
5358                              RParenLoc))
5359    return ExprError();
5360
5361  if (CheckFunctionCall(Method, TheCall.get()))
5362    return ExprError();
5363
5364  return MaybeBindToTemporary(TheCall.release());
5365}
5366
5367/// BuildCallToObjectOfClassType - Build a call to an object of class
5368/// type (C++ [over.call.object]), which can end up invoking an
5369/// overloaded function call operator (@c operator()) or performing a
5370/// user-defined conversion on the object argument.
5371Sema::ExprResult
5372Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
5373                                   SourceLocation LParenLoc,
5374                                   Expr **Args, unsigned NumArgs,
5375                                   SourceLocation *CommaLocs,
5376                                   SourceLocation RParenLoc) {
5377  assert(Object->getType()->isRecordType() && "Requires object type argument");
5378  const RecordType *Record = Object->getType()->getAs<RecordType>();
5379
5380  // C++ [over.call.object]p1:
5381  //  If the primary-expression E in the function call syntax
5382  //  evaluates to a class object of type "cv T", then the set of
5383  //  candidate functions includes at least the function call
5384  //  operators of T. The function call operators of T are obtained by
5385  //  ordinary lookup of the name operator() in the context of
5386  //  (E).operator().
5387  OverloadCandidateSet CandidateSet;
5388  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
5389
5390  if (RequireCompleteType(LParenLoc, Object->getType(),
5391                          PartialDiagnostic(diag::err_incomplete_object_call)
5392                          << Object->getSourceRange()))
5393    return true;
5394
5395  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5396  LookupQualifiedName(R, Record->getDecl());
5397  R.suppressDiagnostics();
5398
5399  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5400       Oper != OperEnd; ++Oper) {
5401    AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
5402                       /*SuppressUserConversions=*/ false);
5403  }
5404
5405  // C++ [over.call.object]p2:
5406  //   In addition, for each conversion function declared in T of the
5407  //   form
5408  //
5409  //        operator conversion-type-id () cv-qualifier;
5410  //
5411  //   where cv-qualifier is the same cv-qualification as, or a
5412  //   greater cv-qualification than, cv, and where conversion-type-id
5413  //   denotes the type "pointer to function of (P1,...,Pn) returning
5414  //   R", or the type "reference to pointer to function of
5415  //   (P1,...,Pn) returning R", or the type "reference to function
5416  //   of (P1,...,Pn) returning R", a surrogate call function [...]
5417  //   is also considered as a candidate function. Similarly,
5418  //   surrogate call functions are added to the set of candidate
5419  //   functions for each conversion function declared in an
5420  //   accessible base class provided the function is not hidden
5421  //   within T by another intervening declaration.
5422  // FIXME: Look in base classes for more conversion operators!
5423  const UnresolvedSet *Conversions
5424    = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5425  for (UnresolvedSet::iterator I = Conversions->begin(),
5426         E = Conversions->end(); I != E; ++I) {
5427    NamedDecl *D = *I;
5428    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5429    if (isa<UsingShadowDecl>(D))
5430      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5431
5432    // Skip over templated conversion functions; they aren't
5433    // surrogates.
5434    if (isa<FunctionTemplateDecl>(D))
5435      continue;
5436
5437    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5438
5439    // Strip the reference type (if any) and then the pointer type (if
5440    // any) to get down to what might be a function type.
5441    QualType ConvType = Conv->getConversionType().getNonReferenceType();
5442    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5443      ConvType = ConvPtrType->getPointeeType();
5444
5445    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5446      AddSurrogateCandidate(Conv, ActingContext, Proto,
5447                            Object->getType(), Args, NumArgs,
5448                            CandidateSet);
5449  }
5450
5451  // Perform overload resolution.
5452  OverloadCandidateSet::iterator Best;
5453  switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
5454  case OR_Success:
5455    // Overload resolution succeeded; we'll build the appropriate call
5456    // below.
5457    break;
5458
5459  case OR_No_Viable_Function:
5460    Diag(Object->getSourceRange().getBegin(),
5461         diag::err_ovl_no_viable_object_call)
5462      << Object->getType() << Object->getSourceRange();
5463    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5464    break;
5465
5466  case OR_Ambiguous:
5467    Diag(Object->getSourceRange().getBegin(),
5468         diag::err_ovl_ambiguous_object_call)
5469      << Object->getType() << Object->getSourceRange();
5470    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5471    break;
5472
5473  case OR_Deleted:
5474    Diag(Object->getSourceRange().getBegin(),
5475         diag::err_ovl_deleted_object_call)
5476      << Best->Function->isDeleted()
5477      << Object->getType() << Object->getSourceRange();
5478    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5479    break;
5480  }
5481
5482  if (Best == CandidateSet.end()) {
5483    // We had an error; delete all of the subexpressions and return
5484    // the error.
5485    Object->Destroy(Context);
5486    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5487      Args[ArgIdx]->Destroy(Context);
5488    return true;
5489  }
5490
5491  if (Best->Function == 0) {
5492    // Since there is no function declaration, this is one of the
5493    // surrogate candidates. Dig out the conversion function.
5494    CXXConversionDecl *Conv
5495      = cast<CXXConversionDecl>(
5496                         Best->Conversions[0].UserDefined.ConversionFunction);
5497
5498    // We selected one of the surrogate functions that converts the
5499    // object parameter to a function pointer. Perform the conversion
5500    // on the object argument, then let ActOnCallExpr finish the job.
5501
5502    // Create an implicit member expr to refer to the conversion operator.
5503    // and then call it.
5504    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
5505
5506    return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
5507                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5508                         CommaLocs, RParenLoc).release();
5509  }
5510
5511  // We found an overloaded operator(). Build a CXXOperatorCallExpr
5512  // that calls this method, using Object for the implicit object
5513  // parameter and passing along the remaining arguments.
5514  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5515  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
5516
5517  unsigned NumArgsInProto = Proto->getNumArgs();
5518  unsigned NumArgsToCheck = NumArgs;
5519
5520  // Build the full argument list for the method call (the
5521  // implicit object parameter is placed at the beginning of the
5522  // list).
5523  Expr **MethodArgs;
5524  if (NumArgs < NumArgsInProto) {
5525    NumArgsToCheck = NumArgsInProto;
5526    MethodArgs = new Expr*[NumArgsInProto + 1];
5527  } else {
5528    MethodArgs = new Expr*[NumArgs + 1];
5529  }
5530  MethodArgs[0] = Object;
5531  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5532    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
5533
5534  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
5535                                          SourceLocation());
5536  UsualUnaryConversions(NewFn);
5537
5538  // Once we've built TheCall, all of the expressions are properly
5539  // owned.
5540  QualType ResultTy = Method->getResultType().getNonReferenceType();
5541  ExprOwningPtr<CXXOperatorCallExpr>
5542    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
5543                                                    MethodArgs, NumArgs + 1,
5544                                                    ResultTy, RParenLoc));
5545  delete [] MethodArgs;
5546
5547  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5548                          Method))
5549    return true;
5550
5551  // We may have default arguments. If so, we need to allocate more
5552  // slots in the call for them.
5553  if (NumArgs < NumArgsInProto)
5554    TheCall->setNumArgs(Context, NumArgsInProto + 1);
5555  else if (NumArgs > NumArgsInProto)
5556    NumArgsToCheck = NumArgsInProto;
5557
5558  bool IsError = false;
5559
5560  // Initialize the implicit object parameter.
5561  IsError |= PerformObjectArgumentInitialization(Object, Method);
5562  TheCall->setArg(0, Object);
5563
5564
5565  // Check the argument types.
5566  for (unsigned i = 0; i != NumArgsToCheck; i++) {
5567    Expr *Arg;
5568    if (i < NumArgs) {
5569      Arg = Args[i];
5570
5571      // Pass the argument.
5572      QualType ProtoArgType = Proto->getArgType(i);
5573      IsError |= PerformCopyInitialization(Arg, ProtoArgType, AA_Passing);
5574    } else {
5575      OwningExprResult DefArg
5576        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5577      if (DefArg.isInvalid()) {
5578        IsError = true;
5579        break;
5580      }
5581
5582      Arg = DefArg.takeAs<Expr>();
5583    }
5584
5585    TheCall->setArg(i + 1, Arg);
5586  }
5587
5588  // If this is a variadic call, handle args passed through "...".
5589  if (Proto->isVariadic()) {
5590    // Promote the arguments (C99 6.5.2.2p7).
5591    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5592      Expr *Arg = Args[i];
5593      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
5594      TheCall->setArg(i + 1, Arg);
5595    }
5596  }
5597
5598  if (IsError) return true;
5599
5600  if (CheckFunctionCall(Method, TheCall.get()))
5601    return true;
5602
5603  return MaybeBindToTemporary(TheCall.release()).release();
5604}
5605
5606/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
5607///  (if one exists), where @c Base is an expression of class type and
5608/// @c Member is the name of the member we're trying to find.
5609Sema::OwningExprResult
5610Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5611  Expr *Base = static_cast<Expr *>(BaseIn.get());
5612  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
5613
5614  // C++ [over.ref]p1:
5615  //
5616  //   [...] An expression x->m is interpreted as (x.operator->())->m
5617  //   for a class object x of type T if T::operator->() exists and if
5618  //   the operator is selected as the best match function by the
5619  //   overload resolution mechanism (13.3).
5620  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5621  OverloadCandidateSet CandidateSet;
5622  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
5623
5624  if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5625                          PDiag(diag::err_typecheck_incomplete_tag)
5626                            << Base->getSourceRange()))
5627    return ExprError();
5628
5629  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5630  LookupQualifiedName(R, BaseRecord->getDecl());
5631  R.suppressDiagnostics();
5632
5633  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5634       Oper != OperEnd; ++Oper) {
5635    NamedDecl *D = *Oper;
5636    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5637    if (isa<UsingShadowDecl>(D))
5638      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5639
5640    AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5641                       Base->getType(), 0, 0, CandidateSet,
5642                       /*SuppressUserConversions=*/false);
5643  }
5644
5645  // Perform overload resolution.
5646  OverloadCandidateSet::iterator Best;
5647  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5648  case OR_Success:
5649    // Overload resolution succeeded; we'll build the call below.
5650    break;
5651
5652  case OR_No_Viable_Function:
5653    if (CandidateSet.empty())
5654      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5655        << Base->getType() << Base->getSourceRange();
5656    else
5657      Diag(OpLoc, diag::err_ovl_no_viable_oper)
5658        << "operator->" << Base->getSourceRange();
5659    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5660    return ExprError();
5661
5662  case OR_Ambiguous:
5663    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5664      << "->" << Base->getSourceRange();
5665    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5666    return ExprError();
5667
5668  case OR_Deleted:
5669    Diag(OpLoc,  diag::err_ovl_deleted_oper)
5670      << Best->Function->isDeleted()
5671      << "->" << Base->getSourceRange();
5672    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5673    return ExprError();
5674  }
5675
5676  // Convert the object parameter.
5677  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5678  if (PerformObjectArgumentInitialization(Base, Method))
5679    return ExprError();
5680
5681  // No concerns about early exits now.
5682  BaseIn.release();
5683
5684  // Build the operator call.
5685  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5686                                           SourceLocation());
5687  UsualUnaryConversions(FnExpr);
5688
5689  QualType ResultTy = Method->getResultType().getNonReferenceType();
5690  ExprOwningPtr<CXXOperatorCallExpr>
5691    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5692                                                    &Base, 1, ResultTy, OpLoc));
5693
5694  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5695                          Method))
5696          return ExprError();
5697  return move(TheCall);
5698}
5699
5700/// FixOverloadedFunctionReference - E is an expression that refers to
5701/// a C++ overloaded function (possibly with some parentheses and
5702/// perhaps a '&' around it). We have resolved the overloaded function
5703/// to the function declaration Fn, so patch up the expression E to
5704/// refer (possibly indirectly) to Fn. Returns the new expr.
5705Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5706  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5707    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5708    if (SubExpr == PE->getSubExpr())
5709      return PE->Retain();
5710
5711    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5712  }
5713
5714  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5715    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5716    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5717                               SubExpr->getType()) &&
5718           "Implicit cast type cannot be determined from overload");
5719    if (SubExpr == ICE->getSubExpr())
5720      return ICE->Retain();
5721
5722    return new (Context) ImplicitCastExpr(ICE->getType(),
5723                                          ICE->getCastKind(),
5724                                          SubExpr,
5725                                          ICE->isLvalueCast());
5726  }
5727
5728  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
5729    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
5730           "Can only take the address of an overloaded function");
5731    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5732      if (Method->isStatic()) {
5733        // Do nothing: static member functions aren't any different
5734        // from non-member functions.
5735      } else {
5736        // Fix the sub expression, which really has to be an
5737        // UnresolvedLookupExpr holding an overloaded member function
5738        // or template.
5739        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5740        if (SubExpr == UnOp->getSubExpr())
5741          return UnOp->Retain();
5742
5743        assert(isa<DeclRefExpr>(SubExpr)
5744               && "fixed to something other than a decl ref");
5745        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5746               && "fixed to a member ref with no nested name qualifier");
5747
5748        // We have taken the address of a pointer to member
5749        // function. Perform the computation here so that we get the
5750        // appropriate pointer to member type.
5751        QualType ClassType
5752          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5753        QualType MemPtrType
5754          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5755
5756        return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5757                                           MemPtrType, UnOp->getOperatorLoc());
5758      }
5759    }
5760    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5761    if (SubExpr == UnOp->getSubExpr())
5762      return UnOp->Retain();
5763
5764    return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5765                                     Context.getPointerType(SubExpr->getType()),
5766                                       UnOp->getOperatorLoc());
5767  }
5768
5769  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
5770    // FIXME: avoid copy.
5771    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5772    if (ULE->hasExplicitTemplateArgs()) {
5773      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5774      TemplateArgs = &TemplateArgsBuffer;
5775    }
5776
5777    return DeclRefExpr::Create(Context,
5778                               ULE->getQualifier(),
5779                               ULE->getQualifierRange(),
5780                               Fn,
5781                               ULE->getNameLoc(),
5782                               Fn->getType(),
5783                               TemplateArgs);
5784  }
5785
5786  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
5787    // FIXME: avoid copy.
5788    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5789    if (MemExpr->hasExplicitTemplateArgs()) {
5790      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5791      TemplateArgs = &TemplateArgsBuffer;
5792    }
5793
5794    Expr *Base;
5795
5796    // If we're filling in
5797    if (MemExpr->isImplicitAccess()) {
5798      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5799        return DeclRefExpr::Create(Context,
5800                                   MemExpr->getQualifier(),
5801                                   MemExpr->getQualifierRange(),
5802                                   Fn,
5803                                   MemExpr->getMemberLoc(),
5804                                   Fn->getType(),
5805                                   TemplateArgs);
5806      } else
5807        Base = new (Context) CXXThisExpr(SourceLocation(),
5808                                         MemExpr->getBaseType());
5809    } else
5810      Base = MemExpr->getBase()->Retain();
5811
5812    return MemberExpr::Create(Context, Base,
5813                              MemExpr->isArrow(),
5814                              MemExpr->getQualifier(),
5815                              MemExpr->getQualifierRange(),
5816                              Fn,
5817                              MemExpr->getMemberLoc(),
5818                              TemplateArgs,
5819                              Fn->getType());
5820  }
5821
5822  assert(false && "Invalid reference to overloaded function");
5823  return E->Retain();
5824}
5825
5826Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
5827                                                            FunctionDecl *Fn) {
5828  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
5829}
5830
5831} // end namespace clang
5832