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