SemaOverload.cpp revision f6b89691d2fdb88b97edabbe5f390fb2919c8f0a
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 "SemaInherit.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/TypeOrdering.h"
22#include "llvm/ADT/SmallPtrSet.h"
23#include "llvm/Support/Compiler.h"
24#include <algorithm>
25
26namespace clang {
27
28/// GetConversionCategory - Retrieve the implicit conversion
29/// category corresponding to the given implicit conversion kind.
30ImplicitConversionCategory
31GetConversionCategory(ImplicitConversionKind Kind) {
32  static const ImplicitConversionCategory
33    Category[(int)ICK_Num_Conversion_Kinds] = {
34    ICC_Identity,
35    ICC_Lvalue_Transformation,
36    ICC_Lvalue_Transformation,
37    ICC_Lvalue_Transformation,
38    ICC_Qualification_Adjustment,
39    ICC_Promotion,
40    ICC_Promotion,
41    ICC_Conversion,
42    ICC_Conversion,
43    ICC_Conversion,
44    ICC_Conversion,
45    ICC_Conversion,
46    ICC_Conversion,
47    ICC_Conversion
48  };
49  return Category[(int)Kind];
50}
51
52/// GetConversionRank - Retrieve the implicit conversion rank
53/// corresponding to the given implicit conversion kind.
54ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
55  static const ImplicitConversionRank
56    Rank[(int)ICK_Num_Conversion_Kinds] = {
57    ICR_Exact_Match,
58    ICR_Exact_Match,
59    ICR_Exact_Match,
60    ICR_Exact_Match,
61    ICR_Exact_Match,
62    ICR_Promotion,
63    ICR_Promotion,
64    ICR_Conversion,
65    ICR_Conversion,
66    ICR_Conversion,
67    ICR_Conversion,
68    ICR_Conversion,
69    ICR_Conversion,
70    ICR_Conversion
71  };
72  return Rank[(int)Kind];
73}
74
75/// GetImplicitConversionName - Return the name of this kind of
76/// implicit conversion.
77const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
78  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
79    "No conversion",
80    "Lvalue-to-rvalue",
81    "Array-to-pointer",
82    "Function-to-pointer",
83    "Qualification",
84    "Integral promotion",
85    "Floating point promotion",
86    "Integral conversion",
87    "Floating conversion",
88    "Floating-integral conversion",
89    "Pointer conversion",
90    "Pointer-to-member conversion",
91    "Boolean conversion",
92    "Derived-to-base conversion"
93  };
94  return Name[Kind];
95}
96
97/// StandardConversionSequence - Set the standard conversion
98/// sequence to the identity conversion.
99void StandardConversionSequence::setAsIdentityConversion() {
100  First = ICK_Identity;
101  Second = ICK_Identity;
102  Third = ICK_Identity;
103  Deprecated = false;
104  ReferenceBinding = false;
105  DirectBinding = false;
106  CopyConstructor = 0;
107}
108
109/// getRank - Retrieve the rank of this standard conversion sequence
110/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
111/// implicit conversions.
112ImplicitConversionRank StandardConversionSequence::getRank() const {
113  ImplicitConversionRank Rank = ICR_Exact_Match;
114  if  (GetConversionRank(First) > Rank)
115    Rank = GetConversionRank(First);
116  if  (GetConversionRank(Second) > Rank)
117    Rank = GetConversionRank(Second);
118  if  (GetConversionRank(Third) > Rank)
119    Rank = GetConversionRank(Third);
120  return Rank;
121}
122
123/// isPointerConversionToBool - Determines whether this conversion is
124/// a conversion of a pointer or pointer-to-member to bool. This is
125/// used as part of the ranking of standard conversion sequences
126/// (C++ 13.3.3.2p4).
127bool StandardConversionSequence::isPointerConversionToBool() const
128{
129  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
130  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
131
132  // Note that FromType has not necessarily been transformed by the
133  // array-to-pointer or function-to-pointer implicit conversions, so
134  // check for their presence as well as checking whether FromType is
135  // a pointer.
136  if (ToType->isBooleanType() &&
137      (FromType->isPointerType() ||
138       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
139    return true;
140
141  return false;
142}
143
144/// isPointerConversionToVoidPointer - Determines whether this
145/// conversion is a conversion of a pointer to a void pointer. This is
146/// used as part of the ranking of standard conversion sequences (C++
147/// 13.3.3.2p4).
148bool
149StandardConversionSequence::
150isPointerConversionToVoidPointer(ASTContext& Context) const
151{
152  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
153  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
154
155  // Note that FromType has not necessarily been transformed by the
156  // array-to-pointer implicit conversion, so check for its presence
157  // and redo the conversion to get a pointer.
158  if (First == ICK_Array_To_Pointer)
159    FromType = Context.getArrayDecayedType(FromType);
160
161  if (Second == ICK_Pointer_Conversion)
162    if (const PointerType* ToPtrType = ToType->getAsPointerType())
163      return ToPtrType->getPointeeType()->isVoidType();
164
165  return false;
166}
167
168/// DebugPrint - Print this standard conversion sequence to standard
169/// error. Useful for debugging overloading issues.
170void StandardConversionSequence::DebugPrint() const {
171  bool PrintedSomething = false;
172  if (First != ICK_Identity) {
173    fprintf(stderr, "%s", GetImplicitConversionName(First));
174    PrintedSomething = true;
175  }
176
177  if (Second != ICK_Identity) {
178    if (PrintedSomething) {
179      fprintf(stderr, " -> ");
180    }
181    fprintf(stderr, "%s", GetImplicitConversionName(Second));
182
183    if (CopyConstructor) {
184      fprintf(stderr, " (by copy constructor)");
185    } else if (DirectBinding) {
186      fprintf(stderr, " (direct reference binding)");
187    } else if (ReferenceBinding) {
188      fprintf(stderr, " (reference binding)");
189    }
190    PrintedSomething = true;
191  }
192
193  if (Third != ICK_Identity) {
194    if (PrintedSomething) {
195      fprintf(stderr, " -> ");
196    }
197    fprintf(stderr, "%s", GetImplicitConversionName(Third));
198    PrintedSomething = true;
199  }
200
201  if (!PrintedSomething) {
202    fprintf(stderr, "No conversions required");
203  }
204}
205
206/// DebugPrint - Print this user-defined conversion sequence to standard
207/// error. Useful for debugging overloading issues.
208void UserDefinedConversionSequence::DebugPrint() const {
209  if (Before.First || Before.Second || Before.Third) {
210    Before.DebugPrint();
211    fprintf(stderr, " -> ");
212  }
213  fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
214  if (After.First || After.Second || After.Third) {
215    fprintf(stderr, " -> ");
216    After.DebugPrint();
217  }
218}
219
220/// DebugPrint - Print this implicit conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void ImplicitConversionSequence::DebugPrint() const {
223  switch (ConversionKind) {
224  case StandardConversion:
225    fprintf(stderr, "Standard conversion: ");
226    Standard.DebugPrint();
227    break;
228  case UserDefinedConversion:
229    fprintf(stderr, "User-defined conversion: ");
230    UserDefined.DebugPrint();
231    break;
232  case EllipsisConversion:
233    fprintf(stderr, "Ellipsis conversion");
234    break;
235  case BadConversion:
236    fprintf(stderr, "Bad conversion");
237    break;
238  }
239
240  fprintf(stderr, "\n");
241}
242
243// IsOverload - Determine whether the given New declaration is an
244// overload of the Old declaration. This routine returns false if New
245// and Old cannot be overloaded, e.g., if they are functions with the
246// same signature (C++ 1.3.10) or if the Old declaration isn't a
247// function (or overload set). When it does return false and Old is an
248// OverloadedFunctionDecl, MatchedDecl will be set to point to the
249// FunctionDecl that New cannot be overloaded with.
250//
251// Example: Given the following input:
252//
253//   void f(int, float); // #1
254//   void f(int, int); // #2
255//   int f(int, int); // #3
256//
257// When we process #1, there is no previous declaration of "f",
258// so IsOverload will not be used.
259//
260// When we process #2, Old is a FunctionDecl for #1.  By comparing the
261// parameter types, we see that #1 and #2 are overloaded (since they
262// have different signatures), so this routine returns false;
263// MatchedDecl is unchanged.
264//
265// When we process #3, Old is an OverloadedFunctionDecl containing #1
266// and #2. We compare the signatures of #3 to #1 (they're overloaded,
267// so we do nothing) and then #3 to #2. Since the signatures of #3 and
268// #2 are identical (return types of functions are not part of the
269// signature), IsOverload returns false and MatchedDecl will be set to
270// point to the FunctionDecl for #2.
271bool
272Sema::IsOverload(FunctionDecl *New, Decl* OldD,
273                 OverloadedFunctionDecl::function_iterator& MatchedDecl)
274{
275  if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
276    // Is this new function an overload of every function in the
277    // overload set?
278    OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
279                                           FuncEnd = Ovl->function_end();
280    for (; Func != FuncEnd; ++Func) {
281      if (!IsOverload(New, *Func, MatchedDecl)) {
282        MatchedDecl = Func;
283        return false;
284      }
285    }
286
287    // This function overloads every function in the overload set.
288    return true;
289  } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
290    // Is the function New an overload of the function Old?
291    QualType OldQType = Context.getCanonicalType(Old->getType());
292    QualType NewQType = Context.getCanonicalType(New->getType());
293
294    // Compare the signatures (C++ 1.3.10) of the two functions to
295    // determine whether they are overloads. If we find any mismatch
296    // in the signature, they are overloads.
297
298    // If either of these functions is a K&R-style function (no
299    // prototype), then we consider them to have matching signatures.
300    if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) ||
301        isa<FunctionTypeNoProto>(NewQType.getTypePtr()))
302      return false;
303
304    FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr());
305    FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr());
306
307    // The signature of a function includes the types of its
308    // parameters (C++ 1.3.10), which includes the presence or absence
309    // of the ellipsis; see C++ DR 357).
310    if (OldQType != NewQType &&
311        (OldType->getNumArgs() != NewType->getNumArgs() ||
312         OldType->isVariadic() != NewType->isVariadic() ||
313         !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
314                     NewType->arg_type_begin())))
315      return true;
316
317    // If the function is a class member, its signature includes the
318    // cv-qualifiers (if any) on the function itself.
319    //
320    // As part of this, also check whether one of the member functions
321    // is static, in which case they are not overloads (C++
322    // 13.1p2). While not part of the definition of the signature,
323    // this check is important to determine whether these functions
324    // can be overloaded.
325    CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
326    CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
327    if (OldMethod && NewMethod &&
328        !OldMethod->isStatic() && !NewMethod->isStatic() &&
329        OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
330      return true;
331
332    // The signatures match; this is not an overload.
333    return false;
334  } else {
335    // (C++ 13p1):
336    //   Only function declarations can be overloaded; object and type
337    //   declarations cannot be overloaded.
338    return false;
339  }
340}
341
342/// TryImplicitConversion - Attempt to perform an implicit conversion
343/// from the given expression (Expr) to the given type (ToType). This
344/// function returns an implicit conversion sequence that can be used
345/// to perform the initialization. Given
346///
347///   void f(float f);
348///   void g(int i) { f(i); }
349///
350/// this routine would produce an implicit conversion sequence to
351/// describe the initialization of f from i, which will be a standard
352/// conversion sequence containing an lvalue-to-rvalue conversion (C++
353/// 4.1) followed by a floating-integral conversion (C++ 4.9).
354//
355/// Note that this routine only determines how the conversion can be
356/// performed; it does not actually perform the conversion. As such,
357/// it will not produce any diagnostics if no conversion is available,
358/// but will instead return an implicit conversion sequence of kind
359/// "BadConversion".
360///
361/// If @p SuppressUserConversions, then user-defined conversions are
362/// not permitted.
363ImplicitConversionSequence
364Sema::TryImplicitConversion(Expr* From, QualType ToType,
365                            bool SuppressUserConversions)
366{
367  ImplicitConversionSequence ICS;
368  if (IsStandardConversion(From, ToType, ICS.Standard))
369    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
370  else if (!SuppressUserConversions &&
371           IsUserDefinedConversion(From, ToType, ICS.UserDefined)) {
372    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
373    // C++ [over.ics.user]p4:
374    //   A conversion of an expression of class type to the same class
375    //   type is given Exact Match rank, and a conversion of an
376    //   expression of class type to a base class of that type is
377    //   given Conversion rank, in spite of the fact that a copy
378    //   constructor (i.e., a user-defined conversion function) is
379    //   called for those cases.
380    if (CXXConstructorDecl *Constructor
381          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
382      if (Constructor->isCopyConstructor(Context)) {
383        // Turn this into a "standard" conversion sequence, so that it
384        // gets ranked with standard conversion sequences.
385        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
386        ICS.Standard.setAsIdentityConversion();
387        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
388        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
389        ICS.Standard.CopyConstructor = Constructor;
390        if (IsDerivedFrom(From->getType().getUnqualifiedType(),
391                          ToType.getUnqualifiedType()))
392          ICS.Standard.Second = ICK_Derived_To_Base;
393      }
394    }
395  } else
396    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
397
398  return ICS;
399}
400
401/// IsStandardConversion - Determines whether there is a standard
402/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
403/// expression From to the type ToType. Standard conversion sequences
404/// only consider non-class types; for conversions that involve class
405/// types, use TryImplicitConversion. If a conversion exists, SCS will
406/// contain the standard conversion sequence required to perform this
407/// conversion and this routine will return true. Otherwise, this
408/// routine will return false and the value of SCS is unspecified.
409bool
410Sema::IsStandardConversion(Expr* From, QualType ToType,
411                           StandardConversionSequence &SCS)
412{
413  QualType FromType = From->getType();
414
415  // There are no standard conversions for class types, so abort early.
416  if (FromType->isRecordType() || ToType->isRecordType())
417    return false;
418
419  // Standard conversions (C++ [conv])
420  SCS.setAsIdentityConversion();
421  SCS.Deprecated = false;
422  SCS.FromTypePtr = FromType.getAsOpaquePtr();
423  SCS.CopyConstructor = 0;
424
425  // The first conversion can be an lvalue-to-rvalue conversion,
426  // array-to-pointer conversion, or function-to-pointer conversion
427  // (C++ 4p1).
428
429  // Lvalue-to-rvalue conversion (C++ 4.1):
430  //   An lvalue (3.10) of a non-function, non-array type T can be
431  //   converted to an rvalue.
432  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
433  if (argIsLvalue == Expr::LV_Valid &&
434      !FromType->isFunctionType() && !FromType->isArrayType() &&
435      !FromType->isOverloadType()) {
436    SCS.First = ICK_Lvalue_To_Rvalue;
437
438    // If T is a non-class type, the type of the rvalue is the
439    // cv-unqualified version of T. Otherwise, the type of the rvalue
440    // is T (C++ 4.1p1).
441    FromType = FromType.getUnqualifiedType();
442  }
443  // Array-to-pointer conversion (C++ 4.2)
444  else if (FromType->isArrayType()) {
445    SCS.First = ICK_Array_To_Pointer;
446
447    // An lvalue or rvalue of type "array of N T" or "array of unknown
448    // bound of T" can be converted to an rvalue of type "pointer to
449    // T" (C++ 4.2p1).
450    FromType = Context.getArrayDecayedType(FromType);
451
452    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
453      // This conversion is deprecated. (C++ D.4).
454      SCS.Deprecated = true;
455
456      // For the purpose of ranking in overload resolution
457      // (13.3.3.1.1), this conversion is considered an
458      // array-to-pointer conversion followed by a qualification
459      // conversion (4.4). (C++ 4.2p2)
460      SCS.Second = ICK_Identity;
461      SCS.Third = ICK_Qualification;
462      SCS.ToTypePtr = ToType.getAsOpaquePtr();
463      return true;
464    }
465  }
466  // Function-to-pointer conversion (C++ 4.3).
467  else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
468    SCS.First = ICK_Function_To_Pointer;
469
470    // An lvalue of function type T can be converted to an rvalue of
471    // type "pointer to T." The result is a pointer to the
472    // function. (C++ 4.3p1).
473    FromType = Context.getPointerType(FromType);
474  }
475  // Address of overloaded function (C++ [over.over]).
476  else if (FunctionDecl *Fn
477             = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
478    SCS.First = ICK_Function_To_Pointer;
479
480    // We were able to resolve the address of the overloaded function,
481    // so we can convert to the type of that function.
482    FromType = Fn->getType();
483    if (ToType->isReferenceType())
484      FromType = Context.getReferenceType(FromType);
485    else
486      FromType = Context.getPointerType(FromType);
487  }
488  // We don't require any conversions for the first step.
489  else {
490    SCS.First = ICK_Identity;
491  }
492
493  // The second conversion can be an integral promotion, floating
494  // point promotion, integral conversion, floating point conversion,
495  // floating-integral conversion, pointer conversion,
496  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
497  if (Context.getCanonicalType(FromType).getUnqualifiedType() ==
498      Context.getCanonicalType(ToType).getUnqualifiedType()) {
499    // The unqualified versions of the types are the same: there's no
500    // conversion to do.
501    SCS.Second = ICK_Identity;
502  }
503  // Integral promotion (C++ 4.5).
504  else if (IsIntegralPromotion(From, FromType, ToType)) {
505    SCS.Second = ICK_Integral_Promotion;
506    FromType = ToType.getUnqualifiedType();
507  }
508  // Floating point promotion (C++ 4.6).
509  else if (IsFloatingPointPromotion(FromType, ToType)) {
510    SCS.Second = ICK_Floating_Promotion;
511    FromType = ToType.getUnqualifiedType();
512  }
513  // Integral conversions (C++ 4.7).
514  // FIXME: isIntegralType shouldn't be true for enums in C++.
515  else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
516           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
517    SCS.Second = ICK_Integral_Conversion;
518    FromType = ToType.getUnqualifiedType();
519  }
520  // Floating point conversions (C++ 4.8).
521  else if (FromType->isFloatingType() && ToType->isFloatingType()) {
522    SCS.Second = ICK_Floating_Conversion;
523    FromType = ToType.getUnqualifiedType();
524  }
525  // Floating-integral conversions (C++ 4.9).
526  // FIXME: isIntegralType shouldn't be true for enums in C++.
527  else if ((FromType->isFloatingType() &&
528            ToType->isIntegralType() && !ToType->isBooleanType() &&
529                                        !ToType->isEnumeralType()) ||
530           ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
531            ToType->isFloatingType())) {
532    SCS.Second = ICK_Floating_Integral;
533    FromType = ToType.getUnqualifiedType();
534  }
535  // Pointer conversions (C++ 4.10).
536  else if (IsPointerConversion(From, FromType, ToType, FromType)) {
537    SCS.Second = ICK_Pointer_Conversion;
538  }
539  // FIXME: Pointer to member conversions (4.11).
540  // Boolean conversions (C++ 4.12).
541  // FIXME: pointer-to-member type
542  else if (ToType->isBooleanType() &&
543           (FromType->isArithmeticType() ||
544            FromType->isEnumeralType() ||
545            FromType->isPointerType())) {
546    SCS.Second = ICK_Boolean_Conversion;
547    FromType = Context.BoolTy;
548  } else {
549    // No second conversion required.
550    SCS.Second = ICK_Identity;
551  }
552
553  QualType CanonFrom;
554  QualType CanonTo;
555  // The third conversion can be a qualification conversion (C++ 4p1).
556  if (IsQualificationConversion(FromType, ToType)) {
557    SCS.Third = ICK_Qualification;
558    FromType = ToType;
559    CanonFrom = Context.getCanonicalType(FromType);
560    CanonTo = Context.getCanonicalType(ToType);
561  } else {
562    // No conversion required
563    SCS.Third = ICK_Identity;
564
565    // C++ [over.best.ics]p6:
566    //   [...] Any difference in top-level cv-qualification is
567    //   subsumed by the initialization itself and does not constitute
568    //   a conversion. [...]
569    CanonFrom = Context.getCanonicalType(FromType);
570    CanonTo = Context.getCanonicalType(ToType);
571    if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
572        CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
573      FromType = ToType;
574      CanonFrom = CanonTo;
575    }
576  }
577
578  // If we have not converted the argument type to the parameter type,
579  // this is a bad conversion sequence.
580  if (CanonFrom != CanonTo)
581    return false;
582
583  SCS.ToTypePtr = FromType.getAsOpaquePtr();
584  return true;
585}
586
587/// IsIntegralPromotion - Determines whether the conversion from the
588/// expression From (whose potentially-adjusted type is FromType) to
589/// ToType is an integral promotion (C++ 4.5). If so, returns true and
590/// sets PromotedType to the promoted type.
591bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
592{
593  const BuiltinType *To = ToType->getAsBuiltinType();
594  // All integers are built-in.
595  if (!To) {
596    return false;
597  }
598
599  // An rvalue of type char, signed char, unsigned char, short int, or
600  // unsigned short int can be converted to an rvalue of type int if
601  // int can represent all the values of the source type; otherwise,
602  // the source rvalue can be converted to an rvalue of type unsigned
603  // int (C++ 4.5p1).
604  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
605    if (// We can promote any signed, promotable integer type to an int
606        (FromType->isSignedIntegerType() ||
607         // We can promote any unsigned integer type whose size is
608         // less than int to an int.
609         (!FromType->isSignedIntegerType() &&
610          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
611      return To->getKind() == BuiltinType::Int;
612    }
613
614    return To->getKind() == BuiltinType::UInt;
615  }
616
617  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
618  // can be converted to an rvalue of the first of the following types
619  // that can represent all the values of its underlying type: int,
620  // unsigned int, long, or unsigned long (C++ 4.5p2).
621  if ((FromType->isEnumeralType() || FromType->isWideCharType())
622      && ToType->isIntegerType()) {
623    // Determine whether the type we're converting from is signed or
624    // unsigned.
625    bool FromIsSigned;
626    uint64_t FromSize = Context.getTypeSize(FromType);
627    if (const EnumType *FromEnumType = FromType->getAsEnumType()) {
628      QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
629      FromIsSigned = UnderlyingType->isSignedIntegerType();
630    } else {
631      // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
632      FromIsSigned = true;
633    }
634
635    // The types we'll try to promote to, in the appropriate
636    // order. Try each of these types.
637    QualType PromoteTypes[4] = {
638      Context.IntTy, Context.UnsignedIntTy,
639      Context.LongTy, Context.UnsignedLongTy
640    };
641    for (int Idx = 0; Idx < 4; ++Idx) {
642      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
643      if (FromSize < ToSize ||
644          (FromSize == ToSize &&
645           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
646        // We found the type that we can promote to. If this is the
647        // type we wanted, we have a promotion. Otherwise, no
648        // promotion.
649        return Context.getCanonicalType(ToType).getUnqualifiedType()
650          == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
651      }
652    }
653  }
654
655  // An rvalue for an integral bit-field (9.6) can be converted to an
656  // rvalue of type int if int can represent all the values of the
657  // bit-field; otherwise, it can be converted to unsigned int if
658  // unsigned int can represent all the values of the bit-field. If
659  // the bit-field is larger yet, no integral promotion applies to
660  // it. If the bit-field has an enumerated type, it is treated as any
661  // other value of that type for promotion purposes (C++ 4.5p3).
662  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) {
663    using llvm::APSInt;
664    FieldDecl *MemberDecl = MemRef->getMemberDecl();
665    APSInt BitWidth;
666    if (MemberDecl->isBitField() &&
667        FromType->isIntegralType() && !FromType->isEnumeralType() &&
668        From->isIntegerConstantExpr(BitWidth, Context)) {
669      APSInt ToSize(Context.getTypeSize(ToType));
670
671      // Are we promoting to an int from a bitfield that fits in an int?
672      if (BitWidth < ToSize ||
673          (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
674        return To->getKind() == BuiltinType::Int;
675      }
676
677      // Are we promoting to an unsigned int from an unsigned bitfield
678      // that fits into an unsigned int?
679      if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
680        return To->getKind() == BuiltinType::UInt;
681      }
682
683      return false;
684    }
685  }
686
687  // An rvalue of type bool can be converted to an rvalue of type int,
688  // with false becoming zero and true becoming one (C++ 4.5p4).
689  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
690    return true;
691  }
692
693  return false;
694}
695
696/// IsFloatingPointPromotion - Determines whether the conversion from
697/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
698/// returns true and sets PromotedType to the promoted type.
699bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType)
700{
701  /// An rvalue of type float can be converted to an rvalue of type
702  /// double. (C++ 4.6p1).
703  if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType())
704    if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType())
705      if (FromBuiltin->getKind() == BuiltinType::Float &&
706          ToBuiltin->getKind() == BuiltinType::Double)
707        return true;
708
709  return false;
710}
711
712/// IsPointerConversion - Determines whether the conversion of the
713/// expression From, which has the (possibly adjusted) type FromType,
714/// can be converted to the type ToType via a pointer conversion (C++
715/// 4.10). If so, returns true and places the converted type (that
716/// might differ from ToType in its cv-qualifiers at some level) into
717/// ConvertedType.
718bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
719                               QualType& ConvertedType)
720{
721  const PointerType* ToTypePtr = ToType->getAsPointerType();
722  if (!ToTypePtr)
723    return false;
724
725  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
726  if (From->isNullPointerConstant(Context)) {
727    ConvertedType = ToType;
728    return true;
729  }
730
731  // An rvalue of type "pointer to cv T," where T is an object type,
732  // can be converted to an rvalue of type "pointer to cv void" (C++
733  // 4.10p2).
734  if (FromType->isPointerType() &&
735      FromType->getAsPointerType()->getPointeeType()->isObjectType() &&
736      ToTypePtr->getPointeeType()->isVoidType()) {
737    // We need to produce a pointer to cv void, where cv is the same
738    // set of cv-qualifiers as we had on the incoming pointee type.
739    QualType toPointee = ToTypePtr->getPointeeType();
740    unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType()
741                   ->getPointeeType().getCVRQualifiers();
742
743    if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers()
744	  == Quals) {
745      // ToType is exactly the type we want. Use it.
746      ConvertedType = ToType;
747    } else {
748      // Build a new type with the right qualifiers.
749      ConvertedType
750	= Context.getPointerType(Context.VoidTy.getQualifiedType(Quals));
751    }
752    return true;
753  }
754
755  // C++ [conv.ptr]p3:
756  //
757  //   An rvalue of type "pointer to cv D," where D is a class type,
758  //   can be converted to an rvalue of type "pointer to cv B," where
759  //   B is a base class (clause 10) of D. If B is an inaccessible
760  //   (clause 11) or ambiguous (10.2) base class of D, a program that
761  //   necessitates this conversion is ill-formed. The result of the
762  //   conversion is a pointer to the base class sub-object of the
763  //   derived class object. The null pointer value is converted to
764  //   the null pointer value of the destination type.
765  //
766  // Note that we do not check for ambiguity or inaccessibility
767  // here. That is handled by CheckPointerConversion.
768  if (const PointerType *FromPtrType = FromType->getAsPointerType())
769    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
770      if (FromPtrType->getPointeeType()->isRecordType() &&
771          ToPtrType->getPointeeType()->isRecordType() &&
772          IsDerivedFrom(FromPtrType->getPointeeType(),
773                        ToPtrType->getPointeeType())) {
774        // The conversion is okay. Now, we need to produce the type
775        // that results from this conversion, which will have the same
776        // qualifiers as the incoming type.
777        QualType CanonFromPointee
778          = Context.getCanonicalType(FromPtrType->getPointeeType());
779        QualType ToPointee = ToPtrType->getPointeeType();
780        QualType CanonToPointee = Context.getCanonicalType(ToPointee);
781        unsigned Quals = CanonFromPointee.getCVRQualifiers();
782
783        if (CanonToPointee.getCVRQualifiers() == Quals) {
784          // ToType is exactly the type we want. Use it.
785          ConvertedType = ToType;
786        } else {
787          // Build a new type with the right qualifiers.
788          ConvertedType
789            = Context.getPointerType(CanonToPointee.getQualifiedType(Quals));
790        }
791        return true;
792      }
793    }
794
795  return false;
796}
797
798/// CheckPointerConversion - Check the pointer conversion from the
799/// expression From to the type ToType. This routine checks for
800/// ambiguous (FIXME: or inaccessible) derived-to-base pointer
801/// conversions for which IsPointerConversion has already returned
802/// true. It returns true and produces a diagnostic if there was an
803/// error, or returns false otherwise.
804bool Sema::CheckPointerConversion(Expr *From, QualType ToType) {
805  QualType FromType = From->getType();
806
807  if (const PointerType *FromPtrType = FromType->getAsPointerType())
808    if (const PointerType *ToPtrType = ToType->getAsPointerType()) {
809      BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
810                      /*DetectVirtual=*/false);
811      QualType FromPointeeType = FromPtrType->getPointeeType(),
812               ToPointeeType   = ToPtrType->getPointeeType();
813      if (FromPointeeType->isRecordType() &&
814          ToPointeeType->isRecordType()) {
815        // We must have a derived-to-base conversion. Check an
816        // ambiguous or inaccessible conversion.
817        return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
818                                            From->getExprLoc(),
819                                            From->getSourceRange());
820      }
821    }
822
823  return false;
824}
825
826/// IsQualificationConversion - Determines whether the conversion from
827/// an rvalue of type FromType to ToType is a qualification conversion
828/// (C++ 4.4).
829bool
830Sema::IsQualificationConversion(QualType FromType, QualType ToType)
831{
832  FromType = Context.getCanonicalType(FromType);
833  ToType = Context.getCanonicalType(ToType);
834
835  // If FromType and ToType are the same type, this is not a
836  // qualification conversion.
837  if (FromType == ToType)
838    return false;
839
840  // (C++ 4.4p4):
841  //   A conversion can add cv-qualifiers at levels other than the first
842  //   in multi-level pointers, subject to the following rules: [...]
843  bool PreviousToQualsIncludeConst = true;
844  bool UnwrappedAnyPointer = false;
845  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
846    // Within each iteration of the loop, we check the qualifiers to
847    // determine if this still looks like a qualification
848    // conversion. Then, if all is well, we unwrap one more level of
849    // pointers or pointers-to-members and do it all again
850    // until there are no more pointers or pointers-to-members left to
851    // unwrap.
852    UnwrappedAnyPointer = true;
853
854    //   -- for every j > 0, if const is in cv 1,j then const is in cv
855    //      2,j, and similarly for volatile.
856    if (!ToType.isAtLeastAsQualifiedAs(FromType))
857      return false;
858
859    //   -- if the cv 1,j and cv 2,j are different, then const is in
860    //      every cv for 0 < k < j.
861    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
862        && !PreviousToQualsIncludeConst)
863      return false;
864
865    // Keep track of whether all prior cv-qualifiers in the "to" type
866    // include const.
867    PreviousToQualsIncludeConst
868      = PreviousToQualsIncludeConst && ToType.isConstQualified();
869  }
870
871  // We are left with FromType and ToType being the pointee types
872  // after unwrapping the original FromType and ToType the same number
873  // of types. If we unwrapped any pointers, and if FromType and
874  // ToType have the same unqualified type (since we checked
875  // qualifiers above), then this is a qualification conversion.
876  return UnwrappedAnyPointer &&
877    FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
878}
879
880/// IsUserDefinedConversion - Determines whether there is a
881/// user-defined conversion sequence (C++ [over.ics.user]) that
882/// converts expression From to the type ToType. If such a conversion
883/// exists, User will contain the user-defined conversion sequence
884/// that performs such a conversion and this routine will return
885/// true. Otherwise, this routine returns false and User is
886/// unspecified.
887bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
888                                   UserDefinedConversionSequence& User)
889{
890  OverloadCandidateSet CandidateSet;
891  if (const CXXRecordType *ToRecordType
892        = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) {
893    // C++ [over.match.ctor]p1:
894    //   When objects of class type are direct-initialized (8.5), or
895    //   copy-initialized from an expression of the same or a
896    //   derived class type (8.5), overload resolution selects the
897    //   constructor. [...] For copy-initialization, the candidate
898    //   functions are all the converting constructors (12.3.1) of
899    //   that class. The argument list is the expression-list within
900    //   the parentheses of the initializer.
901    CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl();
902    const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors();
903    for (OverloadedFunctionDecl::function_const_iterator func
904           = Constructors->function_begin();
905         func != Constructors->function_end(); ++func) {
906      CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func);
907      if (Constructor->isConvertingConstructor())
908        AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
909                             /*SuppressUserConversions=*/true);
910    }
911  }
912
913  if (const CXXRecordType *FromRecordType
914        = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) {
915    // Add all of the conversion functions as candidates.
916    // FIXME: Look for conversions in base classes!
917    CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl();
918    OverloadedFunctionDecl *Conversions
919      = FromRecordDecl->getConversionFunctions();
920    for (OverloadedFunctionDecl::function_iterator Func
921           = Conversions->function_begin();
922         Func != Conversions->function_end(); ++Func) {
923      CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
924      AddConversionCandidate(Conv, From, ToType, CandidateSet);
925    }
926  }
927
928  OverloadCandidateSet::iterator Best;
929  switch (BestViableFunction(CandidateSet, Best)) {
930    case OR_Success:
931      // Record the standard conversion we used and the conversion function.
932      if (CXXConstructorDecl *Constructor
933            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
934        // C++ [over.ics.user]p1:
935        //   If the user-defined conversion is specified by a
936        //   constructor (12.3.1), the initial standard conversion
937        //   sequence converts the source type to the type required by
938        //   the argument of the constructor.
939        //
940        // FIXME: What about ellipsis conversions?
941        QualType ThisType = Constructor->getThisType(Context);
942        User.Before = Best->Conversions[0].Standard;
943        User.ConversionFunction = Constructor;
944        User.After.setAsIdentityConversion();
945        User.After.FromTypePtr
946          = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr();
947        User.After.ToTypePtr = ToType.getAsOpaquePtr();
948        return true;
949      } else if (CXXConversionDecl *Conversion
950                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
951        // C++ [over.ics.user]p1:
952        //
953        //   [...] If the user-defined conversion is specified by a
954        //   conversion function (12.3.2), the initial standard
955        //   conversion sequence converts the source type to the
956        //   implicit object parameter of the conversion function.
957        User.Before = Best->Conversions[0].Standard;
958        User.ConversionFunction = Conversion;
959
960        // C++ [over.ics.user]p2:
961        //   The second standard conversion sequence converts the
962        //   result of the user-defined conversion to the target type
963        //   for the sequence. Since an implicit conversion sequence
964        //   is an initialization, the special rules for
965        //   initialization by user-defined conversion apply when
966        //   selecting the best user-defined conversion for a
967        //   user-defined conversion sequence (see 13.3.3 and
968        //   13.3.3.1).
969        User.After = Best->FinalConversion;
970        return true;
971      } else {
972        assert(false && "Not a constructor or conversion function?");
973        return false;
974      }
975
976    case OR_No_Viable_Function:
977      // No conversion here! We're done.
978      return false;
979
980    case OR_Ambiguous:
981      // FIXME: See C++ [over.best.ics]p10 for the handling of
982      // ambiguous conversion sequences.
983      return false;
984    }
985
986  return false;
987}
988
989/// CompareImplicitConversionSequences - Compare two implicit
990/// conversion sequences to determine whether one is better than the
991/// other or if they are indistinguishable (C++ 13.3.3.2).
992ImplicitConversionSequence::CompareKind
993Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
994                                         const ImplicitConversionSequence& ICS2)
995{
996  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
997  // conversion sequences (as defined in 13.3.3.1)
998  //   -- a standard conversion sequence (13.3.3.1.1) is a better
999  //      conversion sequence than a user-defined conversion sequence or
1000  //      an ellipsis conversion sequence, and
1001  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1002  //      conversion sequence than an ellipsis conversion sequence
1003  //      (13.3.3.1.3).
1004  //
1005  if (ICS1.ConversionKind < ICS2.ConversionKind)
1006    return ImplicitConversionSequence::Better;
1007  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1008    return ImplicitConversionSequence::Worse;
1009
1010  // Two implicit conversion sequences of the same form are
1011  // indistinguishable conversion sequences unless one of the
1012  // following rules apply: (C++ 13.3.3.2p3):
1013  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1014    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1015  else if (ICS1.ConversionKind ==
1016             ImplicitConversionSequence::UserDefinedConversion) {
1017    // User-defined conversion sequence U1 is a better conversion
1018    // sequence than another user-defined conversion sequence U2 if
1019    // they contain the same user-defined conversion function or
1020    // constructor and if the second standard conversion sequence of
1021    // U1 is better than the second standard conversion sequence of
1022    // U2 (C++ 13.3.3.2p3).
1023    if (ICS1.UserDefined.ConversionFunction ==
1024          ICS2.UserDefined.ConversionFunction)
1025      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1026                                                ICS2.UserDefined.After);
1027  }
1028
1029  return ImplicitConversionSequence::Indistinguishable;
1030}
1031
1032/// CompareStandardConversionSequences - Compare two standard
1033/// conversion sequences to determine whether one is better than the
1034/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1035ImplicitConversionSequence::CompareKind
1036Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1037                                         const StandardConversionSequence& SCS2)
1038{
1039  // Standard conversion sequence S1 is a better conversion sequence
1040  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1041
1042  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1043  //     sequences in the canonical form defined by 13.3.3.1.1,
1044  //     excluding any Lvalue Transformation; the identity conversion
1045  //     sequence is considered to be a subsequence of any
1046  //     non-identity conversion sequence) or, if not that,
1047  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1048    // Neither is a proper subsequence of the other. Do nothing.
1049    ;
1050  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1051           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1052           (SCS1.Second == ICK_Identity &&
1053            SCS1.Third == ICK_Identity))
1054    // SCS1 is a proper subsequence of SCS2.
1055    return ImplicitConversionSequence::Better;
1056  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1057           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1058           (SCS2.Second == ICK_Identity &&
1059            SCS2.Third == ICK_Identity))
1060    // SCS2 is a proper subsequence of SCS1.
1061    return ImplicitConversionSequence::Worse;
1062
1063  //  -- the rank of S1 is better than the rank of S2 (by the rules
1064  //     defined below), or, if not that,
1065  ImplicitConversionRank Rank1 = SCS1.getRank();
1066  ImplicitConversionRank Rank2 = SCS2.getRank();
1067  if (Rank1 < Rank2)
1068    return ImplicitConversionSequence::Better;
1069  else if (Rank2 < Rank1)
1070    return ImplicitConversionSequence::Worse;
1071
1072  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1073  // are indistinguishable unless one of the following rules
1074  // applies:
1075
1076  //   A conversion that is not a conversion of a pointer, or
1077  //   pointer to member, to bool is better than another conversion
1078  //   that is such a conversion.
1079  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1080    return SCS2.isPointerConversionToBool()
1081             ? ImplicitConversionSequence::Better
1082             : ImplicitConversionSequence::Worse;
1083
1084  // C++ [over.ics.rank]p4b2:
1085  //
1086  //   If class B is derived directly or indirectly from class A,
1087  //   conversion of B* to A* is better than conversion of B* to
1088  //   void*, and conversion of A* to void* is better than conversion
1089  //   of B* to void*.
1090  bool SCS1ConvertsToVoid
1091    = SCS1.isPointerConversionToVoidPointer(Context);
1092  bool SCS2ConvertsToVoid
1093    = SCS2.isPointerConversionToVoidPointer(Context);
1094  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1095    // Exactly one of the conversion sequences is a conversion to
1096    // a void pointer; it's the worse conversion.
1097    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1098                              : ImplicitConversionSequence::Worse;
1099  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1100    // Neither conversion sequence converts to a void pointer; compare
1101    // their derived-to-base conversions.
1102    if (ImplicitConversionSequence::CompareKind DerivedCK
1103          = CompareDerivedToBaseConversions(SCS1, SCS2))
1104      return DerivedCK;
1105  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1106    // Both conversion sequences are conversions to void
1107    // pointers. Compare the source types to determine if there's an
1108    // inheritance relationship in their sources.
1109    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1110    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1111
1112    // Adjust the types we're converting from via the array-to-pointer
1113    // conversion, if we need to.
1114    if (SCS1.First == ICK_Array_To_Pointer)
1115      FromType1 = Context.getArrayDecayedType(FromType1);
1116    if (SCS2.First == ICK_Array_To_Pointer)
1117      FromType2 = Context.getArrayDecayedType(FromType2);
1118
1119    QualType FromPointee1
1120      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1121    QualType FromPointee2
1122      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1123
1124    if (IsDerivedFrom(FromPointee2, FromPointee1))
1125      return ImplicitConversionSequence::Better;
1126    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1127      return ImplicitConversionSequence::Worse;
1128  }
1129
1130  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1131  // bullet 3).
1132  if (ImplicitConversionSequence::CompareKind QualCK
1133        = CompareQualificationConversions(SCS1, SCS2))
1134    return QualCK;
1135
1136  // C++ [over.ics.rank]p3b4:
1137  //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1138  //      which the references refer are the same type except for
1139  //      top-level cv-qualifiers, and the type to which the reference
1140  //      initialized by S2 refers is more cv-qualified than the type
1141  //      to which the reference initialized by S1 refers.
1142  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1143    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1144    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1145    T1 = Context.getCanonicalType(T1);
1146    T2 = Context.getCanonicalType(T2);
1147    if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1148      if (T2.isMoreQualifiedThan(T1))
1149        return ImplicitConversionSequence::Better;
1150      else if (T1.isMoreQualifiedThan(T2))
1151        return ImplicitConversionSequence::Worse;
1152    }
1153  }
1154
1155  return ImplicitConversionSequence::Indistinguishable;
1156}
1157
1158/// CompareQualificationConversions - Compares two standard conversion
1159/// sequences to determine whether they can be ranked based on their
1160/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1161ImplicitConversionSequence::CompareKind
1162Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1163                                      const StandardConversionSequence& SCS2)
1164{
1165  // C++ 13.3.3.2p3:
1166  //  -- S1 and S2 differ only in their qualification conversion and
1167  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1168  //     cv-qualification signature of type T1 is a proper subset of
1169  //     the cv-qualification signature of type T2, and S1 is not the
1170  //     deprecated string literal array-to-pointer conversion (4.2).
1171  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1172      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1173    return ImplicitConversionSequence::Indistinguishable;
1174
1175  // FIXME: the example in the standard doesn't use a qualification
1176  // conversion (!)
1177  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1178  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1179  T1 = Context.getCanonicalType(T1);
1180  T2 = Context.getCanonicalType(T2);
1181
1182  // If the types are the same, we won't learn anything by unwrapped
1183  // them.
1184  if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1185    return ImplicitConversionSequence::Indistinguishable;
1186
1187  ImplicitConversionSequence::CompareKind Result
1188    = ImplicitConversionSequence::Indistinguishable;
1189  while (UnwrapSimilarPointerTypes(T1, T2)) {
1190    // Within each iteration of the loop, we check the qualifiers to
1191    // determine if this still looks like a qualification
1192    // conversion. Then, if all is well, we unwrap one more level of
1193    // pointers or pointers-to-members and do it all again
1194    // until there are no more pointers or pointers-to-members left
1195    // to unwrap. This essentially mimics what
1196    // IsQualificationConversion does, but here we're checking for a
1197    // strict subset of qualifiers.
1198    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1199      // The qualifiers are the same, so this doesn't tell us anything
1200      // about how the sequences rank.
1201      ;
1202    else if (T2.isMoreQualifiedThan(T1)) {
1203      // T1 has fewer qualifiers, so it could be the better sequence.
1204      if (Result == ImplicitConversionSequence::Worse)
1205        // Neither has qualifiers that are a subset of the other's
1206        // qualifiers.
1207        return ImplicitConversionSequence::Indistinguishable;
1208
1209      Result = ImplicitConversionSequence::Better;
1210    } else if (T1.isMoreQualifiedThan(T2)) {
1211      // T2 has fewer qualifiers, so it could be the better sequence.
1212      if (Result == ImplicitConversionSequence::Better)
1213        // Neither has qualifiers that are a subset of the other's
1214        // qualifiers.
1215        return ImplicitConversionSequence::Indistinguishable;
1216
1217      Result = ImplicitConversionSequence::Worse;
1218    } else {
1219      // Qualifiers are disjoint.
1220      return ImplicitConversionSequence::Indistinguishable;
1221    }
1222
1223    // If the types after this point are equivalent, we're done.
1224    if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1225      break;
1226  }
1227
1228  // Check that the winning standard conversion sequence isn't using
1229  // the deprecated string literal array to pointer conversion.
1230  switch (Result) {
1231  case ImplicitConversionSequence::Better:
1232    if (SCS1.Deprecated)
1233      Result = ImplicitConversionSequence::Indistinguishable;
1234    break;
1235
1236  case ImplicitConversionSequence::Indistinguishable:
1237    break;
1238
1239  case ImplicitConversionSequence::Worse:
1240    if (SCS2.Deprecated)
1241      Result = ImplicitConversionSequence::Indistinguishable;
1242    break;
1243  }
1244
1245  return Result;
1246}
1247
1248/// CompareDerivedToBaseConversions - Compares two standard conversion
1249/// sequences to determine whether they can be ranked based on their
1250/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3).
1251ImplicitConversionSequence::CompareKind
1252Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1253                                      const StandardConversionSequence& SCS2) {
1254  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1255  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1256  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1257  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1258
1259  // Adjust the types we're converting from via the array-to-pointer
1260  // conversion, if we need to.
1261  if (SCS1.First == ICK_Array_To_Pointer)
1262    FromType1 = Context.getArrayDecayedType(FromType1);
1263  if (SCS2.First == ICK_Array_To_Pointer)
1264    FromType2 = Context.getArrayDecayedType(FromType2);
1265
1266  // Canonicalize all of the types.
1267  FromType1 = Context.getCanonicalType(FromType1);
1268  ToType1 = Context.getCanonicalType(ToType1);
1269  FromType2 = Context.getCanonicalType(FromType2);
1270  ToType2 = Context.getCanonicalType(ToType2);
1271
1272  // C++ [over.ics.rank]p4b3:
1273  //
1274  //   If class B is derived directly or indirectly from class A and
1275  //   class C is derived directly or indirectly from B,
1276
1277  // Compare based on pointer conversions.
1278  if (SCS1.Second == ICK_Pointer_Conversion &&
1279      SCS2.Second == ICK_Pointer_Conversion) {
1280    QualType FromPointee1
1281      = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1282    QualType ToPointee1
1283      = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType();
1284    QualType FromPointee2
1285      = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1286    QualType ToPointee2
1287      = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType();
1288    //   -- conversion of C* to B* is better than conversion of C* to A*,
1289    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1290      if (IsDerivedFrom(ToPointee1, ToPointee2))
1291        return ImplicitConversionSequence::Better;
1292      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1293        return ImplicitConversionSequence::Worse;
1294    }
1295
1296    //   -- conversion of B* to A* is better than conversion of C* to A*,
1297    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1298      if (IsDerivedFrom(FromPointee2, FromPointee1))
1299        return ImplicitConversionSequence::Better;
1300      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1301        return ImplicitConversionSequence::Worse;
1302    }
1303  }
1304
1305  // Compare based on reference bindings.
1306  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1307      SCS1.Second == ICK_Derived_To_Base) {
1308    //   -- binding of an expression of type C to a reference of type
1309    //      B& is better than binding an expression of type C to a
1310    //      reference of type A&,
1311    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1312        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1313      if (IsDerivedFrom(ToType1, ToType2))
1314        return ImplicitConversionSequence::Better;
1315      else if (IsDerivedFrom(ToType2, ToType1))
1316        return ImplicitConversionSequence::Worse;
1317    }
1318
1319    //   -- binding of an expression of type B to a reference of type
1320    //      A& is better than binding an expression of type C to a
1321    //      reference of type A&,
1322    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1323        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1324      if (IsDerivedFrom(FromType2, FromType1))
1325        return ImplicitConversionSequence::Better;
1326      else if (IsDerivedFrom(FromType1, FromType2))
1327        return ImplicitConversionSequence::Worse;
1328    }
1329  }
1330
1331
1332  // FIXME: conversion of A::* to B::* is better than conversion of
1333  // A::* to C::*,
1334
1335  // FIXME: conversion of B::* to C::* is better than conversion of
1336  // A::* to C::*, and
1337
1338  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1339      SCS1.Second == ICK_Derived_To_Base) {
1340    //   -- conversion of C to B is better than conversion of C to A,
1341    if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1342        ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1343      if (IsDerivedFrom(ToType1, ToType2))
1344        return ImplicitConversionSequence::Better;
1345      else if (IsDerivedFrom(ToType2, ToType1))
1346        return ImplicitConversionSequence::Worse;
1347    }
1348
1349    //   -- conversion of B to A is better than conversion of C to A.
1350    if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1351        ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1352      if (IsDerivedFrom(FromType2, FromType1))
1353        return ImplicitConversionSequence::Better;
1354      else if (IsDerivedFrom(FromType1, FromType2))
1355        return ImplicitConversionSequence::Worse;
1356    }
1357  }
1358
1359  return ImplicitConversionSequence::Indistinguishable;
1360}
1361
1362/// TryCopyInitialization - Try to copy-initialize a value of type
1363/// ToType from the expression From. Return the implicit conversion
1364/// sequence required to pass this argument, which may be a bad
1365/// conversion sequence (meaning that the argument cannot be passed to
1366/// a parameter of this type). If @p SuppressUserConversions, then we
1367/// do not permit any user-defined conversion sequences.
1368ImplicitConversionSequence
1369Sema::TryCopyInitialization(Expr *From, QualType ToType,
1370                            bool SuppressUserConversions) {
1371  if (!getLangOptions().CPlusPlus) {
1372    // In C, copy initialization is the same as performing an assignment.
1373    AssignConvertType ConvTy =
1374      CheckSingleAssignmentConstraints(ToType, From);
1375    ImplicitConversionSequence ICS;
1376    if (getLangOptions().NoExtensions? ConvTy != Compatible
1377                                     : ConvTy == Incompatible)
1378      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1379    else
1380      ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1381    return ICS;
1382  } else if (ToType->isReferenceType()) {
1383    ImplicitConversionSequence ICS;
1384    CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions);
1385    return ICS;
1386  } else {
1387    return TryImplicitConversion(From, ToType, SuppressUserConversions);
1388  }
1389}
1390
1391/// PerformArgumentPassing - Pass the argument Arg into a parameter of
1392/// type ToType. Returns true (and emits a diagnostic) if there was
1393/// an error, returns false if the initialization succeeded.
1394bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
1395                                     const char* Flavor) {
1396  if (!getLangOptions().CPlusPlus) {
1397    // In C, argument passing is the same as performing an assignment.
1398    QualType FromType = From->getType();
1399    AssignConvertType ConvTy =
1400      CheckSingleAssignmentConstraints(ToType, From);
1401
1402    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
1403                                    FromType, From, Flavor);
1404  }
1405
1406  if (ToType->isReferenceType())
1407    return CheckReferenceInit(From, ToType);
1408
1409  if (!PerformImplicitConversion(From, ToType))
1410    return false;
1411
1412  return Diag(From->getSourceRange().getBegin(),
1413              diag::err_typecheck_convert_incompatible)
1414    << ToType << From->getType() << Flavor << From->getSourceRange();
1415}
1416
1417/// TryObjectArgumentInitialization - Try to initialize the object
1418/// parameter of the given member function (@c Method) from the
1419/// expression @p From.
1420ImplicitConversionSequence
1421Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
1422  QualType ClassType = Context.getTypeDeclType(Method->getParent());
1423  unsigned MethodQuals = Method->getTypeQualifiers();
1424  QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals);
1425
1426  // Set up the conversion sequence as a "bad" conversion, to allow us
1427  // to exit early.
1428  ImplicitConversionSequence ICS;
1429  ICS.Standard.setAsIdentityConversion();
1430  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
1431
1432  // We need to have an object of class type.
1433  QualType FromType = From->getType();
1434  if (!FromType->isRecordType())
1435    return ICS;
1436
1437  // The implicit object parmeter is has the type "reference to cv X",
1438  // where X is the class of which the function is a member
1439  // (C++ [over.match.funcs]p4). However, when finding an implicit
1440  // conversion sequence for the argument, we are not allowed to
1441  // create temporaries or perform user-defined conversions
1442  // (C++ [over.match.funcs]p5). We perform a simplified version of
1443  // reference binding here, that allows class rvalues to bind to
1444  // non-constant references.
1445
1446  // First check the qualifiers. We don't care about lvalue-vs-rvalue
1447  // with the implicit object parameter (C++ [over.match.funcs]p5).
1448  QualType FromTypeCanon = Context.getCanonicalType(FromType);
1449  if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
1450      !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
1451    return ICS;
1452
1453  // Check that we have either the same type or a derived type. It
1454  // affects the conversion rank.
1455  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
1456  if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
1457    ICS.Standard.Second = ICK_Identity;
1458  else if (IsDerivedFrom(FromType, ClassType))
1459    ICS.Standard.Second = ICK_Derived_To_Base;
1460  else
1461    return ICS;
1462
1463  // Success. Mark this as a reference binding.
1464  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
1465  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
1466  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
1467  ICS.Standard.ReferenceBinding = true;
1468  ICS.Standard.DirectBinding = true;
1469  return ICS;
1470}
1471
1472/// PerformObjectArgumentInitialization - Perform initialization of
1473/// the implicit object parameter for the given Method with the given
1474/// expression.
1475bool
1476Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
1477  QualType ImplicitParamType
1478    = Method->getThisType(Context)->getAsPointerType()->getPointeeType();
1479  ImplicitConversionSequence ICS
1480    = TryObjectArgumentInitialization(From, Method);
1481  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
1482    return Diag(From->getSourceRange().getBegin(),
1483                diag::err_implicit_object_parameter_init)
1484       << ImplicitParamType << From->getType() << From->getSourceRange();
1485
1486  if (ICS.Standard.Second == ICK_Derived_To_Base &&
1487      CheckDerivedToBaseConversion(From->getType(), ImplicitParamType,
1488                                   From->getSourceRange().getBegin(),
1489                                   From->getSourceRange()))
1490    return true;
1491
1492  ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true);
1493  return false;
1494}
1495
1496/// AddOverloadCandidate - Adds the given function to the set of
1497/// candidate functions, using the given function call arguments.  If
1498/// @p SuppressUserConversions, then don't allow user-defined
1499/// conversions via constructors or conversion operators.
1500void
1501Sema::AddOverloadCandidate(FunctionDecl *Function,
1502                           Expr **Args, unsigned NumArgs,
1503                           OverloadCandidateSet& CandidateSet,
1504                           bool SuppressUserConversions)
1505{
1506  const FunctionTypeProto* Proto
1507    = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType());
1508  assert(Proto && "Functions without a prototype cannot be overloaded");
1509  assert(!isa<CXXConversionDecl>(Function) &&
1510         "Use AddConversionCandidate for conversion functions");
1511
1512  // Add this candidate
1513  CandidateSet.push_back(OverloadCandidate());
1514  OverloadCandidate& Candidate = CandidateSet.back();
1515  Candidate.Function = Function;
1516  Candidate.IsSurrogate = false;
1517
1518  unsigned NumArgsInProto = Proto->getNumArgs();
1519
1520  // (C++ 13.3.2p2): A candidate function having fewer than m
1521  // parameters is viable only if it has an ellipsis in its parameter
1522  // list (8.3.5).
1523  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1524    Candidate.Viable = false;
1525    return;
1526  }
1527
1528  // (C++ 13.3.2p2): A candidate function having more than m parameters
1529  // is viable only if the (m+1)st parameter has a default argument
1530  // (8.3.6). For the purposes of overload resolution, the
1531  // parameter list is truncated on the right, so that there are
1532  // exactly m parameters.
1533  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
1534  if (NumArgs < MinRequiredArgs) {
1535    // Not enough arguments.
1536    Candidate.Viable = false;
1537    return;
1538  }
1539
1540  // Determine the implicit conversion sequences for each of the
1541  // arguments.
1542  Candidate.Viable = true;
1543  Candidate.Conversions.resize(NumArgs);
1544  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1545    if (ArgIdx < NumArgsInProto) {
1546      // (C++ 13.3.2p3): for F to be a viable function, there shall
1547      // exist for each argument an implicit conversion sequence
1548      // (13.3.3.1) that converts that argument to the corresponding
1549      // parameter of F.
1550      QualType ParamType = Proto->getArgType(ArgIdx);
1551      Candidate.Conversions[ArgIdx]
1552        = TryCopyInitialization(Args[ArgIdx], ParamType,
1553                                SuppressUserConversions);
1554      if (Candidate.Conversions[ArgIdx].ConversionKind
1555            == ImplicitConversionSequence::BadConversion) {
1556        Candidate.Viable = false;
1557        break;
1558      }
1559    } else {
1560      // (C++ 13.3.2p2): For the purposes of overload resolution, any
1561      // argument for which there is no corresponding parameter is
1562      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1563      Candidate.Conversions[ArgIdx].ConversionKind
1564        = ImplicitConversionSequence::EllipsisConversion;
1565    }
1566  }
1567}
1568
1569/// AddMethodCandidate - Adds the given C++ member function to the set
1570/// of candidate functions, using the given function call arguments
1571/// and the object argument (@c Object). For example, in a call
1572/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
1573/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
1574/// allow user-defined conversions via constructors or conversion
1575/// operators.
1576void
1577Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
1578                         Expr **Args, unsigned NumArgs,
1579                         OverloadCandidateSet& CandidateSet,
1580                         bool SuppressUserConversions)
1581{
1582  const FunctionTypeProto* Proto
1583    = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType());
1584  assert(Proto && "Methods without a prototype cannot be overloaded");
1585  assert(!isa<CXXConversionDecl>(Method) &&
1586         "Use AddConversionCandidate for conversion functions");
1587
1588  // Add this candidate
1589  CandidateSet.push_back(OverloadCandidate());
1590  OverloadCandidate& Candidate = CandidateSet.back();
1591  Candidate.Function = Method;
1592  Candidate.IsSurrogate = false;
1593
1594  unsigned NumArgsInProto = Proto->getNumArgs();
1595
1596  // (C++ 13.3.2p2): A candidate function having fewer than m
1597  // parameters is viable only if it has an ellipsis in its parameter
1598  // list (8.3.5).
1599  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1600    Candidate.Viable = false;
1601    return;
1602  }
1603
1604  // (C++ 13.3.2p2): A candidate function having more than m parameters
1605  // is viable only if the (m+1)st parameter has a default argument
1606  // (8.3.6). For the purposes of overload resolution, the
1607  // parameter list is truncated on the right, so that there are
1608  // exactly m parameters.
1609  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
1610  if (NumArgs < MinRequiredArgs) {
1611    // Not enough arguments.
1612    Candidate.Viable = false;
1613    return;
1614  }
1615
1616  Candidate.Viable = true;
1617  Candidate.Conversions.resize(NumArgs + 1);
1618
1619  // Determine the implicit conversion sequence for the object
1620  // parameter.
1621  Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
1622  if (Candidate.Conversions[0].ConversionKind
1623        == ImplicitConversionSequence::BadConversion) {
1624    Candidate.Viable = false;
1625    return;
1626  }
1627
1628  // Determine the implicit conversion sequences for each of the
1629  // arguments.
1630  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1631    if (ArgIdx < NumArgsInProto) {
1632      // (C++ 13.3.2p3): for F to be a viable function, there shall
1633      // exist for each argument an implicit conversion sequence
1634      // (13.3.3.1) that converts that argument to the corresponding
1635      // parameter of F.
1636      QualType ParamType = Proto->getArgType(ArgIdx);
1637      Candidate.Conversions[ArgIdx + 1]
1638        = TryCopyInitialization(Args[ArgIdx], ParamType,
1639                                SuppressUserConversions);
1640      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1641            == ImplicitConversionSequence::BadConversion) {
1642        Candidate.Viable = false;
1643        break;
1644      }
1645    } else {
1646      // (C++ 13.3.2p2): For the purposes of overload resolution, any
1647      // argument for which there is no corresponding parameter is
1648      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1649      Candidate.Conversions[ArgIdx + 1].ConversionKind
1650        = ImplicitConversionSequence::EllipsisConversion;
1651    }
1652  }
1653}
1654
1655/// AddConversionCandidate - Add a C++ conversion function as a
1656/// candidate in the candidate set (C++ [over.match.conv],
1657/// C++ [over.match.copy]). From is the expression we're converting from,
1658/// and ToType is the type that we're eventually trying to convert to
1659/// (which may or may not be the same type as the type that the
1660/// conversion function produces).
1661void
1662Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
1663                             Expr *From, QualType ToType,
1664                             OverloadCandidateSet& CandidateSet) {
1665  // Add this candidate
1666  CandidateSet.push_back(OverloadCandidate());
1667  OverloadCandidate& Candidate = CandidateSet.back();
1668  Candidate.Function = Conversion;
1669  Candidate.IsSurrogate = false;
1670  Candidate.FinalConversion.setAsIdentityConversion();
1671  Candidate.FinalConversion.FromTypePtr
1672    = Conversion->getConversionType().getAsOpaquePtr();
1673  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
1674
1675  // Determine the implicit conversion sequence for the implicit
1676  // object parameter.
1677  Candidate.Viable = true;
1678  Candidate.Conversions.resize(1);
1679  Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
1680
1681  if (Candidate.Conversions[0].ConversionKind
1682      == ImplicitConversionSequence::BadConversion) {
1683    Candidate.Viable = false;
1684    return;
1685  }
1686
1687  // To determine what the conversion from the result of calling the
1688  // conversion function to the type we're eventually trying to
1689  // convert to (ToType), we need to synthesize a call to the
1690  // conversion function and attempt copy initialization from it. This
1691  // makes sure that we get the right semantics with respect to
1692  // lvalues/rvalues and the type. Fortunately, we can allocate this
1693  // call on the stack and we don't need its arguments to be
1694  // well-formed.
1695  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
1696                            SourceLocation());
1697  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
1698                                &ConversionRef, false);
1699  CallExpr Call(&ConversionFn, 0, 0,
1700                Conversion->getConversionType().getNonReferenceType(),
1701                SourceLocation());
1702  ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true);
1703  switch (ICS.ConversionKind) {
1704  case ImplicitConversionSequence::StandardConversion:
1705    Candidate.FinalConversion = ICS.Standard;
1706    break;
1707
1708  case ImplicitConversionSequence::BadConversion:
1709    Candidate.Viable = false;
1710    break;
1711
1712  default:
1713    assert(false &&
1714           "Can only end up with a standard conversion sequence or failure");
1715  }
1716}
1717
1718/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
1719/// converts the given @c Object to a function pointer via the
1720/// conversion function @c Conversion, and then attempts to call it
1721/// with the given arguments (C++ [over.call.object]p2-4). Proto is
1722/// the type of function that we'll eventually be calling.
1723void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
1724                                 const FunctionTypeProto *Proto,
1725                                 Expr *Object, Expr **Args, unsigned NumArgs,
1726                                 OverloadCandidateSet& CandidateSet) {
1727  CandidateSet.push_back(OverloadCandidate());
1728  OverloadCandidate& Candidate = CandidateSet.back();
1729  Candidate.Function = 0;
1730  Candidate.Surrogate = Conversion;
1731  Candidate.Viable = true;
1732  Candidate.IsSurrogate = true;
1733  Candidate.Conversions.resize(NumArgs + 1);
1734
1735  // Determine the implicit conversion sequence for the implicit
1736  // object parameter.
1737  ImplicitConversionSequence ObjectInit
1738    = TryObjectArgumentInitialization(Object, Conversion);
1739  if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
1740    Candidate.Viable = false;
1741    return;
1742  }
1743
1744  // The first conversion is actually a user-defined conversion whose
1745  // first conversion is ObjectInit's standard conversion (which is
1746  // effectively a reference binding). Record it as such.
1747  Candidate.Conversions[0].ConversionKind
1748    = ImplicitConversionSequence::UserDefinedConversion;
1749  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
1750  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
1751  Candidate.Conversions[0].UserDefined.After
1752    = Candidate.Conversions[0].UserDefined.Before;
1753  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
1754
1755  // Find the
1756  unsigned NumArgsInProto = Proto->getNumArgs();
1757
1758  // (C++ 13.3.2p2): A candidate function having fewer than m
1759  // parameters is viable only if it has an ellipsis in its parameter
1760  // list (8.3.5).
1761  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
1762    Candidate.Viable = false;
1763    return;
1764  }
1765
1766  // Function types don't have any default arguments, so just check if
1767  // we have enough arguments.
1768  if (NumArgs < NumArgsInProto) {
1769    // Not enough arguments.
1770    Candidate.Viable = false;
1771    return;
1772  }
1773
1774  // Determine the implicit conversion sequences for each of the
1775  // arguments.
1776  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1777    if (ArgIdx < NumArgsInProto) {
1778      // (C++ 13.3.2p3): for F to be a viable function, there shall
1779      // exist for each argument an implicit conversion sequence
1780      // (13.3.3.1) that converts that argument to the corresponding
1781      // parameter of F.
1782      QualType ParamType = Proto->getArgType(ArgIdx);
1783      Candidate.Conversions[ArgIdx + 1]
1784        = TryCopyInitialization(Args[ArgIdx], ParamType,
1785                                /*SuppressUserConversions=*/false);
1786      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
1787            == ImplicitConversionSequence::BadConversion) {
1788        Candidate.Viable = false;
1789        break;
1790      }
1791    } else {
1792      // (C++ 13.3.2p2): For the purposes of overload resolution, any
1793      // argument for which there is no corresponding parameter is
1794      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
1795      Candidate.Conversions[ArgIdx + 1].ConversionKind
1796        = ImplicitConversionSequence::EllipsisConversion;
1797    }
1798  }
1799}
1800
1801/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1802/// an acceptable non-member overloaded operator for a call whose
1803/// arguments have types T1 (and, if non-empty, T2). This routine
1804/// implements the check in C++ [over.match.oper]p3b2 concerning
1805/// enumeration types.
1806static bool
1807IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1808                                       QualType T1, QualType T2,
1809                                       ASTContext &Context) {
1810  if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1811    return true;
1812
1813  const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto();
1814  if (Proto->getNumArgs() < 1)
1815    return false;
1816
1817  if (T1->isEnumeralType()) {
1818    QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1819    if (Context.getCanonicalType(T1).getUnqualifiedType()
1820          == Context.getCanonicalType(ArgType).getUnqualifiedType())
1821      return true;
1822  }
1823
1824  if (Proto->getNumArgs() < 2)
1825    return false;
1826
1827  if (!T2.isNull() && T2->isEnumeralType()) {
1828    QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1829    if (Context.getCanonicalType(T2).getUnqualifiedType()
1830          == Context.getCanonicalType(ArgType).getUnqualifiedType())
1831      return true;
1832  }
1833
1834  return false;
1835}
1836
1837/// AddOperatorCandidates - Add the overloaded operator candidates for
1838/// the operator Op that was used in an operator expression such as "x
1839/// Op y". S is the scope in which the expression occurred (used for
1840/// name lookup of the operator), Args/NumArgs provides the operator
1841/// arguments, and CandidateSet will store the added overload
1842/// candidates. (C++ [over.match.oper]).
1843void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
1844                                 Expr **Args, unsigned NumArgs,
1845                                 OverloadCandidateSet& CandidateSet) {
1846  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1847
1848  // C++ [over.match.oper]p3:
1849  //   For a unary operator @ with an operand of a type whose
1850  //   cv-unqualified version is T1, and for a binary operator @ with
1851  //   a left operand of a type whose cv-unqualified version is T1 and
1852  //   a right operand of a type whose cv-unqualified version is T2,
1853  //   three sets of candidate functions, designated member
1854  //   candidates, non-member candidates and built-in candidates, are
1855  //   constructed as follows:
1856  QualType T1 = Args[0]->getType();
1857  QualType T2;
1858  if (NumArgs > 1)
1859    T2 = Args[1]->getType();
1860
1861  //     -- If T1 is a class type, the set of member candidates is the
1862  //        result of the qualified lookup of T1::operator@
1863  //        (13.3.1.1.1); otherwise, the set of member candidates is
1864  //        empty.
1865  if (const RecordType *T1Rec = T1->getAsRecordType()) {
1866    IdentifierResolver::iterator I
1867      = IdResolver.begin(OpName, cast<CXXRecordType>(T1Rec)->getDecl(),
1868                         /*LookInParentCtx=*/false);
1869    NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
1870    if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
1871      AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1872                         /*SuppressUserConversions=*/false);
1873    else if (OverloadedFunctionDecl *Ovl
1874               = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
1875      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1876                                                  FEnd = Ovl->function_end();
1877           F != FEnd; ++F) {
1878        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
1879          AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
1880                             /*SuppressUserConversions=*/false);
1881      }
1882    }
1883  }
1884
1885  //     -- The set of non-member candidates is the result of the
1886  //        unqualified lookup of operator@ in the context of the
1887  //        expression according to the usual rules for name lookup in
1888  //        unqualified function calls (3.4.2) except that all member
1889  //        functions are ignored. However, if no operand has a class
1890  //        type, only those non-member functions in the lookup set
1891  //        that have a first parameter of type T1 or “reference to
1892  //        (possibly cv-qualified) T1”, when T1 is an enumeration
1893  //        type, or (if there is a right operand) a second parameter
1894  //        of type T2 or “reference to (possibly cv-qualified) T2”,
1895  //        when T2 is an enumeration type, are candidate functions.
1896  {
1897    NamedDecl *NonMemberOps = 0;
1898    for (IdentifierResolver::iterator I
1899           = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/);
1900         I != IdResolver.end(); ++I) {
1901      // We don't need to check the identifier namespace, because
1902      // operator names can only be ordinary identifiers.
1903
1904      // Ignore member functions.
1905      if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) {
1906        if (SD->getDeclContext()->isCXXRecord())
1907          continue;
1908      }
1909
1910      // We found something with this name. We're done.
1911      NonMemberOps = *I;
1912      break;
1913    }
1914
1915    if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) {
1916      if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1917        AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
1918                             /*SuppressUserConversions=*/false);
1919    } else if (OverloadedFunctionDecl *Ovl
1920                 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) {
1921      for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
1922                                                  FEnd = Ovl->function_end();
1923           F != FEnd; ++F) {
1924        if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context))
1925          AddOverloadCandidate(*F, Args, NumArgs, CandidateSet,
1926                               /*SuppressUserConversions=*/false);
1927      }
1928    }
1929  }
1930
1931  // Add builtin overload candidates (C++ [over.built]).
1932  AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
1933}
1934
1935/// AddBuiltinCandidate - Add a candidate for a built-in
1936/// operator. ResultTy and ParamTys are the result and parameter types
1937/// of the built-in candidate, respectively. Args and NumArgs are the
1938/// arguments being passed to the candidate.
1939void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
1940                               Expr **Args, unsigned NumArgs,
1941                               OverloadCandidateSet& CandidateSet) {
1942  // Add this candidate
1943  CandidateSet.push_back(OverloadCandidate());
1944  OverloadCandidate& Candidate = CandidateSet.back();
1945  Candidate.Function = 0;
1946  Candidate.BuiltinTypes.ResultTy = ResultTy;
1947  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
1948    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
1949
1950  // Determine the implicit conversion sequences for each of the
1951  // arguments.
1952  Candidate.Viable = true;
1953  Candidate.Conversions.resize(NumArgs);
1954  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
1955    Candidate.Conversions[ArgIdx]
1956      = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false);
1957    if (Candidate.Conversions[ArgIdx].ConversionKind
1958        == ImplicitConversionSequence::BadConversion) {
1959      Candidate.Viable = false;
1960      break;
1961    }
1962  }
1963}
1964
1965/// BuiltinCandidateTypeSet - A set of types that will be used for the
1966/// candidate operator functions for built-in operators (C++
1967/// [over.built]). The types are separated into pointer types and
1968/// enumeration types.
1969class BuiltinCandidateTypeSet  {
1970  /// TypeSet - A set of types.
1971  typedef llvm::SmallPtrSet<void*, 8> TypeSet;
1972
1973  /// PointerTypes - The set of pointer types that will be used in the
1974  /// built-in candidates.
1975  TypeSet PointerTypes;
1976
1977  /// EnumerationTypes - The set of enumeration types that will be
1978  /// used in the built-in candidates.
1979  TypeSet EnumerationTypes;
1980
1981  /// Context - The AST context in which we will build the type sets.
1982  ASTContext &Context;
1983
1984  bool AddWithMoreQualifiedTypeVariants(QualType Ty);
1985
1986public:
1987  /// iterator - Iterates through the types that are part of the set.
1988  class iterator {
1989    TypeSet::iterator Base;
1990
1991  public:
1992    typedef QualType                 value_type;
1993    typedef QualType                 reference;
1994    typedef QualType                 pointer;
1995    typedef std::ptrdiff_t           difference_type;
1996    typedef std::input_iterator_tag  iterator_category;
1997
1998    iterator(TypeSet::iterator B) : Base(B) { }
1999
2000    iterator& operator++() {
2001      ++Base;
2002      return *this;
2003    }
2004
2005    iterator operator++(int) {
2006      iterator tmp(*this);
2007      ++(*this);
2008      return tmp;
2009    }
2010
2011    reference operator*() const {
2012      return QualType::getFromOpaquePtr(*Base);
2013    }
2014
2015    pointer operator->() const {
2016      return **this;
2017    }
2018
2019    friend bool operator==(iterator LHS, iterator RHS) {
2020      return LHS.Base == RHS.Base;
2021    }
2022
2023    friend bool operator!=(iterator LHS, iterator RHS) {
2024      return LHS.Base != RHS.Base;
2025    }
2026  };
2027
2028  BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { }
2029
2030  void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true);
2031
2032  /// pointer_begin - First pointer type found;
2033  iterator pointer_begin() { return PointerTypes.begin(); }
2034
2035  /// pointer_end - Last pointer type found;
2036  iterator pointer_end() { return PointerTypes.end(); }
2037
2038  /// enumeration_begin - First enumeration type found;
2039  iterator enumeration_begin() { return EnumerationTypes.begin(); }
2040
2041  /// enumeration_end - Last enumeration type found;
2042  iterator enumeration_end() { return EnumerationTypes.end(); }
2043};
2044
2045/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
2046/// the set of pointer types along with any more-qualified variants of
2047/// that type. For example, if @p Ty is "int const *", this routine
2048/// will add "int const *", "int const volatile *", "int const
2049/// restrict *", and "int const volatile restrict *" to the set of
2050/// pointer types. Returns true if the add of @p Ty itself succeeded,
2051/// false otherwise.
2052bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) {
2053  // Insert this type.
2054  if (!PointerTypes.insert(Ty.getAsOpaquePtr()))
2055    return false;
2056
2057  if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2058    QualType PointeeTy = PointerTy->getPointeeType();
2059    // FIXME: Optimize this so that we don't keep trying to add the same types.
2060
2061    // FIXME: Do we have to add CVR qualifiers at *all* levels to deal
2062    // with all pointer conversions that don't cast away constness?
2063    if (!PointeeTy.isConstQualified())
2064      AddWithMoreQualifiedTypeVariants
2065        (Context.getPointerType(PointeeTy.withConst()));
2066    if (!PointeeTy.isVolatileQualified())
2067      AddWithMoreQualifiedTypeVariants
2068        (Context.getPointerType(PointeeTy.withVolatile()));
2069    if (!PointeeTy.isRestrictQualified())
2070      AddWithMoreQualifiedTypeVariants
2071        (Context.getPointerType(PointeeTy.withRestrict()));
2072  }
2073
2074  return true;
2075}
2076
2077/// AddTypesConvertedFrom - Add each of the types to which the type @p
2078/// Ty can be implicit converted to the given set of @p Types. We're
2079/// primarily interested in pointer types, enumeration types,
2080void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2081                                                    bool AllowUserConversions) {
2082  // Only deal with canonical types.
2083  Ty = Context.getCanonicalType(Ty);
2084
2085  // Look through reference types; they aren't part of the type of an
2086  // expression for the purposes of conversions.
2087  if (const ReferenceType *RefTy = Ty->getAsReferenceType())
2088    Ty = RefTy->getPointeeType();
2089
2090  // We don't care about qualifiers on the type.
2091  Ty = Ty.getUnqualifiedType();
2092
2093  if (const PointerType *PointerTy = Ty->getAsPointerType()) {
2094    QualType PointeeTy = PointerTy->getPointeeType();
2095
2096    // Insert our type, and its more-qualified variants, into the set
2097    // of types.
2098    if (!AddWithMoreQualifiedTypeVariants(Ty))
2099      return;
2100
2101    // Add 'cv void*' to our set of types.
2102    if (!Ty->isVoidType()) {
2103      QualType QualVoid
2104        = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2105      AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
2106    }
2107
2108    // If this is a pointer to a class type, add pointers to its bases
2109    // (with the same level of cv-qualification as the original
2110    // derived class, of course).
2111    if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) {
2112      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
2113      for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
2114           Base != ClassDecl->bases_end(); ++Base) {
2115        QualType BaseTy = Context.getCanonicalType(Base->getType());
2116        BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers());
2117
2118        // Add the pointer type, recursively, so that we get all of
2119        // the indirect base classes, too.
2120        AddTypesConvertedFrom(Context.getPointerType(BaseTy), false);
2121      }
2122    }
2123  } else if (Ty->isEnumeralType()) {
2124    EnumerationTypes.insert(Ty.getAsOpaquePtr());
2125  } else if (AllowUserConversions) {
2126    if (const RecordType *TyRec = Ty->getAsRecordType()) {
2127      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
2128      // FIXME: Visit conversion functions in the base classes, too.
2129      OverloadedFunctionDecl *Conversions
2130        = ClassDecl->getConversionFunctions();
2131      for (OverloadedFunctionDecl::function_iterator Func
2132             = Conversions->function_begin();
2133           Func != Conversions->function_end(); ++Func) {
2134        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
2135        AddTypesConvertedFrom(Conv->getConversionType(), false);
2136      }
2137    }
2138  }
2139}
2140
2141/// AddBuiltinOperatorCandidates - Add the appropriate built-in
2142/// operator overloads to the candidate set (C++ [over.built]), based
2143/// on the operator @p Op and the arguments given. For example, if the
2144/// operator is a binary '+', this routine might add "int
2145/// operator+(int, int)" to cover integer addition.
2146void
2147Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
2148                                   Expr **Args, unsigned NumArgs,
2149                                   OverloadCandidateSet& CandidateSet) {
2150  // The set of "promoted arithmetic types", which are the arithmetic
2151  // types are that preserved by promotion (C++ [over.built]p2). Note
2152  // that the first few of these types are the promoted integral
2153  // types; these types need to be first.
2154  // FIXME: What about complex?
2155  const unsigned FirstIntegralType = 0;
2156  const unsigned LastIntegralType = 13;
2157  const unsigned FirstPromotedIntegralType = 7,
2158                 LastPromotedIntegralType = 13;
2159  const unsigned FirstPromotedArithmeticType = 7,
2160                 LastPromotedArithmeticType = 16;
2161  const unsigned NumArithmeticTypes = 16;
2162  QualType ArithmeticTypes[NumArithmeticTypes] = {
2163    Context.BoolTy, Context.CharTy, Context.WCharTy,
2164    Context.SignedCharTy, Context.ShortTy,
2165    Context.UnsignedCharTy, Context.UnsignedShortTy,
2166    Context.IntTy, Context.LongTy, Context.LongLongTy,
2167    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
2168    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
2169  };
2170
2171  // Find all of the types that the arguments can convert to, but only
2172  // if the operator we're looking at has built-in operator candidates
2173  // that make use of these types.
2174  BuiltinCandidateTypeSet CandidateTypes(Context);
2175  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
2176      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
2177      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
2178      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
2179      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
2180      (Op == OO_Star && NumArgs == 1)) {
2181    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2182      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType());
2183  }
2184
2185  bool isComparison = false;
2186  switch (Op) {
2187  case OO_None:
2188  case NUM_OVERLOADED_OPERATORS:
2189    assert(false && "Expected an overloaded operator");
2190    break;
2191
2192  case OO_Star: // '*' is either unary or binary
2193    if (NumArgs == 1)
2194      goto UnaryStar;
2195    else
2196      goto BinaryStar;
2197    break;
2198
2199  case OO_Plus: // '+' is either unary or binary
2200    if (NumArgs == 1)
2201      goto UnaryPlus;
2202    else
2203      goto BinaryPlus;
2204    break;
2205
2206  case OO_Minus: // '-' is either unary or binary
2207    if (NumArgs == 1)
2208      goto UnaryMinus;
2209    else
2210      goto BinaryMinus;
2211    break;
2212
2213  case OO_Amp: // '&' is either unary or binary
2214    if (NumArgs == 1)
2215      goto UnaryAmp;
2216    else
2217      goto BinaryAmp;
2218
2219  case OO_PlusPlus:
2220  case OO_MinusMinus:
2221    // C++ [over.built]p3:
2222    //
2223    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
2224    //   is either volatile or empty, there exist candidate operator
2225    //   functions of the form
2226    //
2227    //       VQ T&      operator++(VQ T&);
2228    //       T          operator++(VQ T&, int);
2229    //
2230    // C++ [over.built]p4:
2231    //
2232    //   For every pair (T, VQ), where T is an arithmetic type other
2233    //   than bool, and VQ is either volatile or empty, there exist
2234    //   candidate operator functions of the form
2235    //
2236    //       VQ T&      operator--(VQ T&);
2237    //       T          operator--(VQ T&, int);
2238    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
2239         Arith < NumArithmeticTypes; ++Arith) {
2240      QualType ArithTy = ArithmeticTypes[Arith];
2241      QualType ParamTypes[2]
2242        = { Context.getReferenceType(ArithTy), Context.IntTy };
2243
2244      // Non-volatile version.
2245      if (NumArgs == 1)
2246        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2247      else
2248        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2249
2250      // Volatile version
2251      ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile());
2252      if (NumArgs == 1)
2253        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2254      else
2255        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
2256    }
2257
2258    // C++ [over.built]p5:
2259    //
2260    //   For every pair (T, VQ), where T is a cv-qualified or
2261    //   cv-unqualified object type, and VQ is either volatile or
2262    //   empty, there exist candidate operator functions of the form
2263    //
2264    //       T*VQ&      operator++(T*VQ&);
2265    //       T*VQ&      operator--(T*VQ&);
2266    //       T*         operator++(T*VQ&, int);
2267    //       T*         operator--(T*VQ&, int);
2268    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2269         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2270      // Skip pointer types that aren't pointers to object types.
2271      if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType())
2272        continue;
2273
2274      QualType ParamTypes[2] = {
2275        Context.getReferenceType(*Ptr), Context.IntTy
2276      };
2277
2278      // Without volatile
2279      if (NumArgs == 1)
2280        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2281      else
2282        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2283
2284      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2285        // With volatile
2286        ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2287        if (NumArgs == 1)
2288          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
2289        else
2290          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2291      }
2292    }
2293    break;
2294
2295  UnaryStar:
2296    // C++ [over.built]p6:
2297    //   For every cv-qualified or cv-unqualified object type T, there
2298    //   exist candidate operator functions of the form
2299    //
2300    //       T&         operator*(T*);
2301    //
2302    // C++ [over.built]p7:
2303    //   For every function type T, there exist candidate operator
2304    //   functions of the form
2305    //       T&         operator*(T*);
2306    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2307         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2308      QualType ParamTy = *Ptr;
2309      QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType();
2310      AddBuiltinCandidate(Context.getReferenceType(PointeeTy),
2311                          &ParamTy, Args, 1, CandidateSet);
2312    }
2313    break;
2314
2315  UnaryPlus:
2316    // C++ [over.built]p8:
2317    //   For every type T, there exist candidate operator functions of
2318    //   the form
2319    //
2320    //       T*         operator+(T*);
2321    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2322         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2323      QualType ParamTy = *Ptr;
2324      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2325    }
2326
2327    // Fall through
2328
2329  UnaryMinus:
2330    // C++ [over.built]p9:
2331    //  For every promoted arithmetic type T, there exist candidate
2332    //  operator functions of the form
2333    //
2334    //       T         operator+(T);
2335    //       T         operator-(T);
2336    for (unsigned Arith = FirstPromotedArithmeticType;
2337         Arith < LastPromotedArithmeticType; ++Arith) {
2338      QualType ArithTy = ArithmeticTypes[Arith];
2339      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
2340    }
2341    break;
2342
2343  case OO_Tilde:
2344    // C++ [over.built]p10:
2345    //   For every promoted integral type T, there exist candidate
2346    //   operator functions of the form
2347    //
2348    //        T         operator~(T);
2349    for (unsigned Int = FirstPromotedIntegralType;
2350         Int < LastPromotedIntegralType; ++Int) {
2351      QualType IntTy = ArithmeticTypes[Int];
2352      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
2353    }
2354    break;
2355
2356  case OO_New:
2357  case OO_Delete:
2358  case OO_Array_New:
2359  case OO_Array_Delete:
2360  case OO_Call:
2361    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
2362    break;
2363
2364  case OO_Comma:
2365  UnaryAmp:
2366  case OO_Arrow:
2367    // C++ [over.match.oper]p3:
2368    //   -- For the operator ',', the unary operator '&', or the
2369    //      operator '->', the built-in candidates set is empty.
2370    break;
2371
2372  case OO_Less:
2373  case OO_Greater:
2374  case OO_LessEqual:
2375  case OO_GreaterEqual:
2376  case OO_EqualEqual:
2377  case OO_ExclaimEqual:
2378    // C++ [over.built]p15:
2379    //
2380    //   For every pointer or enumeration type T, there exist
2381    //   candidate operator functions of the form
2382    //
2383    //        bool       operator<(T, T);
2384    //        bool       operator>(T, T);
2385    //        bool       operator<=(T, T);
2386    //        bool       operator>=(T, T);
2387    //        bool       operator==(T, T);
2388    //        bool       operator!=(T, T);
2389    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2390         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2391      QualType ParamTypes[2] = { *Ptr, *Ptr };
2392      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2393    }
2394    for (BuiltinCandidateTypeSet::iterator Enum
2395           = CandidateTypes.enumeration_begin();
2396         Enum != CandidateTypes.enumeration_end(); ++Enum) {
2397      QualType ParamTypes[2] = { *Enum, *Enum };
2398      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2399    }
2400
2401    // Fall through.
2402    isComparison = true;
2403
2404  BinaryPlus:
2405  BinaryMinus:
2406    if (!isComparison) {
2407      // We didn't fall through, so we must have OO_Plus or OO_Minus.
2408
2409      // C++ [over.built]p13:
2410      //
2411      //   For every cv-qualified or cv-unqualified object type T
2412      //   there exist candidate operator functions of the form
2413      //
2414      //      T*         operator+(T*, ptrdiff_t);
2415      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
2416      //      T*         operator-(T*, ptrdiff_t);
2417      //      T*         operator+(ptrdiff_t, T*);
2418      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
2419      //
2420      // C++ [over.built]p14:
2421      //
2422      //   For every T, where T is a pointer to object type, there
2423      //   exist candidate operator functions of the form
2424      //
2425      //      ptrdiff_t  operator-(T, T);
2426      for (BuiltinCandidateTypeSet::iterator Ptr
2427             = CandidateTypes.pointer_begin();
2428           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2429        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2430
2431        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
2432        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2433
2434        if (Op == OO_Plus) {
2435          // T* operator+(ptrdiff_t, T*);
2436          ParamTypes[0] = ParamTypes[1];
2437          ParamTypes[1] = *Ptr;
2438          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
2439        } else {
2440          // ptrdiff_t operator-(T, T);
2441          ParamTypes[1] = *Ptr;
2442          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
2443                              Args, 2, CandidateSet);
2444        }
2445      }
2446    }
2447    // Fall through
2448
2449  case OO_Slash:
2450  BinaryStar:
2451    // C++ [over.built]p12:
2452    //
2453    //   For every pair of promoted arithmetic types L and R, there
2454    //   exist candidate operator functions of the form
2455    //
2456    //        LR         operator*(L, R);
2457    //        LR         operator/(L, R);
2458    //        LR         operator+(L, R);
2459    //        LR         operator-(L, R);
2460    //        bool       operator<(L, R);
2461    //        bool       operator>(L, R);
2462    //        bool       operator<=(L, R);
2463    //        bool       operator>=(L, R);
2464    //        bool       operator==(L, R);
2465    //        bool       operator!=(L, R);
2466    //
2467    //   where LR is the result of the usual arithmetic conversions
2468    //   between types L and R.
2469    for (unsigned Left = FirstPromotedArithmeticType;
2470         Left < LastPromotedArithmeticType; ++Left) {
2471      for (unsigned Right = FirstPromotedArithmeticType;
2472           Right < LastPromotedArithmeticType; ++Right) {
2473        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2474        QualType Result
2475          = isComparison? Context.BoolTy
2476                        : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2477        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2478      }
2479    }
2480    break;
2481
2482  case OO_Percent:
2483  BinaryAmp:
2484  case OO_Caret:
2485  case OO_Pipe:
2486  case OO_LessLess:
2487  case OO_GreaterGreater:
2488    // C++ [over.built]p17:
2489    //
2490    //   For every pair of promoted integral types L and R, there
2491    //   exist candidate operator functions of the form
2492    //
2493    //      LR         operator%(L, R);
2494    //      LR         operator&(L, R);
2495    //      LR         operator^(L, R);
2496    //      LR         operator|(L, R);
2497    //      L          operator<<(L, R);
2498    //      L          operator>>(L, R);
2499    //
2500    //   where LR is the result of the usual arithmetic conversions
2501    //   between types L and R.
2502    for (unsigned Left = FirstPromotedIntegralType;
2503         Left < LastPromotedIntegralType; ++Left) {
2504      for (unsigned Right = FirstPromotedIntegralType;
2505           Right < LastPromotedIntegralType; ++Right) {
2506        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
2507        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
2508            ? LandR[0]
2509            : UsualArithmeticConversionsType(LandR[0], LandR[1]);
2510        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
2511      }
2512    }
2513    break;
2514
2515  case OO_Equal:
2516    // C++ [over.built]p20:
2517    //
2518    //   For every pair (T, VQ), where T is an enumeration or
2519    //   (FIXME:) pointer to member type and VQ is either volatile or
2520    //   empty, there exist candidate operator functions of the form
2521    //
2522    //        VQ T&      operator=(VQ T&, T);
2523    for (BuiltinCandidateTypeSet::iterator Enum
2524           = CandidateTypes.enumeration_begin();
2525         Enum != CandidateTypes.enumeration_end(); ++Enum) {
2526      QualType ParamTypes[2];
2527
2528      // T& operator=(T&, T)
2529      ParamTypes[0] = Context.getReferenceType(*Enum);
2530      ParamTypes[1] = *Enum;
2531      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2532
2533      if (!Context.getCanonicalType(*Enum).isVolatileQualified()) {
2534        // volatile T& operator=(volatile T&, T)
2535        ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile());
2536        ParamTypes[1] = *Enum;
2537        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2538      }
2539    }
2540    // Fall through.
2541
2542  case OO_PlusEqual:
2543  case OO_MinusEqual:
2544    // C++ [over.built]p19:
2545    //
2546    //   For every pair (T, VQ), where T is any type and VQ is either
2547    //   volatile or empty, there exist candidate operator functions
2548    //   of the form
2549    //
2550    //        T*VQ&      operator=(T*VQ&, T*);
2551    //
2552    // C++ [over.built]p21:
2553    //
2554    //   For every pair (T, VQ), where T is a cv-qualified or
2555    //   cv-unqualified object type and VQ is either volatile or
2556    //   empty, there exist candidate operator functions of the form
2557    //
2558    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
2559    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
2560    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2561         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2562      QualType ParamTypes[2];
2563      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
2564
2565      // non-volatile version
2566      ParamTypes[0] = Context.getReferenceType(*Ptr);
2567      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2568
2569      if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
2570        // volatile version
2571        ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile());
2572        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2573      }
2574    }
2575    // Fall through.
2576
2577  case OO_StarEqual:
2578  case OO_SlashEqual:
2579    // C++ [over.built]p18:
2580    //
2581    //   For every triple (L, VQ, R), where L is an arithmetic type,
2582    //   VQ is either volatile or empty, and R is a promoted
2583    //   arithmetic type, there exist candidate operator functions of
2584    //   the form
2585    //
2586    //        VQ L&      operator=(VQ L&, R);
2587    //        VQ L&      operator*=(VQ L&, R);
2588    //        VQ L&      operator/=(VQ L&, R);
2589    //        VQ L&      operator+=(VQ L&, R);
2590    //        VQ L&      operator-=(VQ L&, R);
2591    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
2592      for (unsigned Right = FirstPromotedArithmeticType;
2593           Right < LastPromotedArithmeticType; ++Right) {
2594        QualType ParamTypes[2];
2595        ParamTypes[1] = ArithmeticTypes[Right];
2596
2597        // Add this built-in operator as a candidate (VQ is empty).
2598        ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2599        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2600
2601        // Add this built-in operator as a candidate (VQ is 'volatile').
2602        ParamTypes[0] = ArithmeticTypes[Left].withVolatile();
2603        ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2604        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2605      }
2606    }
2607    break;
2608
2609  case OO_PercentEqual:
2610  case OO_LessLessEqual:
2611  case OO_GreaterGreaterEqual:
2612  case OO_AmpEqual:
2613  case OO_CaretEqual:
2614  case OO_PipeEqual:
2615    // C++ [over.built]p22:
2616    //
2617    //   For every triple (L, VQ, R), where L is an integral type, VQ
2618    //   is either volatile or empty, and R is a promoted integral
2619    //   type, there exist candidate operator functions of the form
2620    //
2621    //        VQ L&       operator%=(VQ L&, R);
2622    //        VQ L&       operator<<=(VQ L&, R);
2623    //        VQ L&       operator>>=(VQ L&, R);
2624    //        VQ L&       operator&=(VQ L&, R);
2625    //        VQ L&       operator^=(VQ L&, R);
2626    //        VQ L&       operator|=(VQ L&, R);
2627    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
2628      for (unsigned Right = FirstPromotedIntegralType;
2629           Right < LastPromotedIntegralType; ++Right) {
2630        QualType ParamTypes[2];
2631        ParamTypes[1] = ArithmeticTypes[Right];
2632
2633        // Add this built-in operator as a candidate (VQ is empty).
2634        // FIXME: We should be caching these declarations somewhere,
2635        // rather than re-building them every time.
2636        ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]);
2637        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2638
2639        // Add this built-in operator as a candidate (VQ is 'volatile').
2640        ParamTypes[0] = ArithmeticTypes[Left];
2641        ParamTypes[0].addVolatile();
2642        ParamTypes[0] = Context.getReferenceType(ParamTypes[0]);
2643        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
2644      }
2645    }
2646    break;
2647
2648  case OO_Exclaim: {
2649    // C++ [over.operator]p23:
2650    //
2651    //   There also exist candidate operator functions of the form
2652    //
2653    //        bool        operator!(bool);
2654    //        bool        operator&&(bool, bool);     [BELOW]
2655    //        bool        operator||(bool, bool);     [BELOW]
2656    QualType ParamTy = Context.BoolTy;
2657    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
2658    break;
2659  }
2660
2661  case OO_AmpAmp:
2662  case OO_PipePipe: {
2663    // C++ [over.operator]p23:
2664    //
2665    //   There also exist candidate operator functions of the form
2666    //
2667    //        bool        operator!(bool);            [ABOVE]
2668    //        bool        operator&&(bool, bool);
2669    //        bool        operator||(bool, bool);
2670    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
2671    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
2672    break;
2673  }
2674
2675  case OO_Subscript:
2676    // C++ [over.built]p13:
2677    //
2678    //   For every cv-qualified or cv-unqualified object type T there
2679    //   exist candidate operator functions of the form
2680    //
2681    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
2682    //        T&         operator[](T*, ptrdiff_t);
2683    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
2684    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
2685    //        T&         operator[](ptrdiff_t, T*);
2686    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
2687         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
2688      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
2689      QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType();
2690      QualType ResultTy = Context.getReferenceType(PointeeType);
2691
2692      // T& operator[](T*, ptrdiff_t)
2693      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2694
2695      // T& operator[](ptrdiff_t, T*);
2696      ParamTypes[0] = ParamTypes[1];
2697      ParamTypes[1] = *Ptr;
2698      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
2699    }
2700    break;
2701
2702  case OO_ArrowStar:
2703    // FIXME: No support for pointer-to-members yet.
2704    break;
2705  }
2706}
2707
2708/// AddOverloadCandidates - Add all of the function overloads in Ovl
2709/// to the candidate set.
2710void
2711Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl,
2712                            Expr **Args, unsigned NumArgs,
2713                            OverloadCandidateSet& CandidateSet,
2714                            bool SuppressUserConversions)
2715{
2716  for (OverloadedFunctionDecl::function_const_iterator Func
2717         = Ovl->function_begin();
2718       Func != Ovl->function_end(); ++Func)
2719    AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet,
2720                         SuppressUserConversions);
2721}
2722
2723/// isBetterOverloadCandidate - Determines whether the first overload
2724/// candidate is a better candidate than the second (C++ 13.3.3p1).
2725bool
2726Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
2727                                const OverloadCandidate& Cand2)
2728{
2729  // Define viable functions to be better candidates than non-viable
2730  // functions.
2731  if (!Cand2.Viable)
2732    return Cand1.Viable;
2733  else if (!Cand1.Viable)
2734    return false;
2735
2736  // FIXME: Deal with the implicit object parameter for static member
2737  // functions. (C++ 13.3.3p1).
2738
2739  // (C++ 13.3.3p1): a viable function F1 is defined to be a better
2740  // function than another viable function F2 if for all arguments i,
2741  // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and
2742  // then...
2743  unsigned NumArgs = Cand1.Conversions.size();
2744  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
2745  bool HasBetterConversion = false;
2746  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2747    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
2748                                               Cand2.Conversions[ArgIdx])) {
2749    case ImplicitConversionSequence::Better:
2750      // Cand1 has a better conversion sequence.
2751      HasBetterConversion = true;
2752      break;
2753
2754    case ImplicitConversionSequence::Worse:
2755      // Cand1 can't be better than Cand2.
2756      return false;
2757
2758    case ImplicitConversionSequence::Indistinguishable:
2759      // Do nothing.
2760      break;
2761    }
2762  }
2763
2764  if (HasBetterConversion)
2765    return true;
2766
2767  // FIXME: Several other bullets in (C++ 13.3.3p1) need to be
2768  // implemented, but they require template support.
2769
2770  // C++ [over.match.best]p1b4:
2771  //
2772  //   -- the context is an initialization by user-defined conversion
2773  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
2774  //      from the return type of F1 to the destination type (i.e.,
2775  //      the type of the entity being initialized) is a better
2776  //      conversion sequence than the standard conversion sequence
2777  //      from the return type of F2 to the destination type.
2778  if (Cand1.Function && Cand2.Function &&
2779      isa<CXXConversionDecl>(Cand1.Function) &&
2780      isa<CXXConversionDecl>(Cand2.Function)) {
2781    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
2782                                               Cand2.FinalConversion)) {
2783    case ImplicitConversionSequence::Better:
2784      // Cand1 has a better conversion sequence.
2785      return true;
2786
2787    case ImplicitConversionSequence::Worse:
2788      // Cand1 can't be better than Cand2.
2789      return false;
2790
2791    case ImplicitConversionSequence::Indistinguishable:
2792      // Do nothing
2793      break;
2794    }
2795  }
2796
2797  return false;
2798}
2799
2800/// BestViableFunction - Computes the best viable function (C++ 13.3.3)
2801/// within an overload candidate set. If overloading is successful,
2802/// the result will be OR_Success and Best will be set to point to the
2803/// best viable function within the candidate set. Otherwise, one of
2804/// several kinds of errors will be returned; see
2805/// Sema::OverloadingResult.
2806Sema::OverloadingResult
2807Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
2808                         OverloadCandidateSet::iterator& Best)
2809{
2810  // Find the best viable function.
2811  Best = CandidateSet.end();
2812  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2813       Cand != CandidateSet.end(); ++Cand) {
2814    if (Cand->Viable) {
2815      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
2816        Best = Cand;
2817    }
2818  }
2819
2820  // If we didn't find any viable functions, abort.
2821  if (Best == CandidateSet.end())
2822    return OR_No_Viable_Function;
2823
2824  // Make sure that this function is better than every other viable
2825  // function. If not, we have an ambiguity.
2826  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2827       Cand != CandidateSet.end(); ++Cand) {
2828    if (Cand->Viable &&
2829        Cand != Best &&
2830        !isBetterOverloadCandidate(*Best, *Cand)) {
2831      Best = CandidateSet.end();
2832      return OR_Ambiguous;
2833    }
2834  }
2835
2836  // Best is the best viable function.
2837  return OR_Success;
2838}
2839
2840/// PrintOverloadCandidates - When overload resolution fails, prints
2841/// diagnostic messages containing the candidates in the candidate
2842/// set. If OnlyViable is true, only viable candidates will be printed.
2843void
2844Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
2845                              bool OnlyViable)
2846{
2847  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
2848                             LastCand = CandidateSet.end();
2849  for (; Cand != LastCand; ++Cand) {
2850    if (Cand->Viable || !OnlyViable) {
2851      if (Cand->Function) {
2852        // Normal function
2853        Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
2854      } else if (Cand->IsSurrogate) {
2855        // Desugar the type of the surrogate down to a function type,
2856        // retaining as many typedefs as possible while still showing
2857        // the function type (and, therefore, its parameter types).
2858        QualType FnType = Cand->Surrogate->getConversionType();
2859        bool isReference = false;
2860        bool isPointer = false;
2861        if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) {
2862          FnType = FnTypeRef->getPointeeType();
2863          isReference = true;
2864        }
2865        if (const PointerType *FnTypePtr = FnType->getAsPointerType()) {
2866          FnType = FnTypePtr->getPointeeType();
2867          isPointer = true;
2868        }
2869        // Desugar down to a function type.
2870        FnType = QualType(FnType->getAsFunctionType(), 0);
2871        // Reconstruct the pointer/reference as appropriate.
2872        if (isPointer) FnType = Context.getPointerType(FnType);
2873        if (isReference) FnType = Context.getReferenceType(FnType);
2874
2875        Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
2876          << FnType;
2877      } else {
2878        // FIXME: We need to get the identifier in here
2879        // FIXME: Do we want the error message to point at the
2880        // operator? (built-ins won't have a location)
2881        QualType FnType
2882          = Context.getFunctionType(Cand->BuiltinTypes.ResultTy,
2883                                    Cand->BuiltinTypes.ParamTypes,
2884                                    Cand->Conversions.size(),
2885                                    false, 0);
2886
2887        Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType;
2888      }
2889    }
2890  }
2891}
2892
2893/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
2894/// an overloaded function (C++ [over.over]), where @p From is an
2895/// expression with overloaded function type and @p ToType is the type
2896/// we're trying to resolve to. For example:
2897///
2898/// @code
2899/// int f(double);
2900/// int f(int);
2901///
2902/// int (*pfd)(double) = f; // selects f(double)
2903/// @endcode
2904///
2905/// This routine returns the resulting FunctionDecl if it could be
2906/// resolved, and NULL otherwise. When @p Complain is true, this
2907/// routine will emit diagnostics if there is an error.
2908FunctionDecl *
2909Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
2910                                         bool Complain) {
2911  QualType FunctionType = ToType;
2912  if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType())
2913    FunctionType = ToTypePtr->getPointeeType();
2914
2915  // We only look at pointers or references to functions.
2916  if (!FunctionType->isFunctionType())
2917    return 0;
2918
2919  // Find the actual overloaded function declaration.
2920  OverloadedFunctionDecl *Ovl = 0;
2921
2922  // C++ [over.over]p1:
2923  //   [...] [Note: any redundant set of parentheses surrounding the
2924  //   overloaded function name is ignored (5.1). ]
2925  Expr *OvlExpr = From->IgnoreParens();
2926
2927  // C++ [over.over]p1:
2928  //   [...] The overloaded function name can be preceded by the &
2929  //   operator.
2930  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
2931    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
2932      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
2933  }
2934
2935  // Try to dig out the overloaded function.
2936  if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr))
2937    Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
2938
2939  // If there's no overloaded function declaration, we're done.
2940  if (!Ovl)
2941    return 0;
2942
2943  // Look through all of the overloaded functions, searching for one
2944  // whose type matches exactly.
2945  // FIXME: When templates or using declarations come along, we'll actually
2946  // have to deal with duplicates, partial ordering, etc. For now, we
2947  // can just do a simple search.
2948  FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType());
2949  for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin();
2950       Fun != Ovl->function_end(); ++Fun) {
2951    // C++ [over.over]p3:
2952    //   Non-member functions and static member functions match
2953    //   targets of type “pointer-to-function”or
2954    //   “reference-to-function.”
2955    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun))
2956      if (!Method->isStatic())
2957        continue;
2958
2959    if (FunctionType == Context.getCanonicalType((*Fun)->getType()))
2960      return *Fun;
2961  }
2962
2963  return 0;
2964}
2965
2966/// ResolveOverloadedCallFn - Given the call expression that calls Fn
2967/// (which eventually refers to the set of overloaded functions in
2968/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the
2969/// function call down to a specific function. If overload resolution
2970/// succeeds, returns an expression that refers to a specific function
2971/// and deletes Fn. Otherwise, emits diagnostics, deletes all of the
2972/// arguments and Fn, and returns NULL.
2973Expr *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl,
2974                                    SourceLocation LParenLoc,
2975                                    Expr **Args, unsigned NumArgs,
2976                                    SourceLocation *CommaLocs,
2977                                    SourceLocation RParenLoc) {
2978  OverloadCandidateSet CandidateSet;
2979  AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet);
2980  OverloadCandidateSet::iterator Best;
2981  switch (BestViableFunction(CandidateSet, Best)) {
2982  case OR_Success: {
2983    Expr *NewFn = new DeclRefExpr(Best->Function, Best->Function->getType(),
2984                                  Fn->getSourceRange().getBegin());
2985    Fn->Destroy(Context);
2986    return NewFn;
2987  }
2988
2989  case OR_No_Viable_Function:
2990    Diag(Fn->getSourceRange().getBegin(),
2991         diag::err_ovl_no_viable_function_in_call)
2992      << Ovl->getDeclName() << (unsigned)CandidateSet.size()
2993      << Fn->getSourceRange();
2994    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
2995    break;
2996
2997  case OR_Ambiguous:
2998    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
2999      << Ovl->getDeclName() << Fn->getSourceRange();
3000    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3001    break;
3002  }
3003
3004  // Overload resolution failed. Destroy all of the subexpressions and
3005  // return NULL.
3006  Fn->Destroy(Context);
3007  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
3008    Args[Arg]->Destroy(Context);
3009  return 0;
3010}
3011
3012/// BuildCallToObjectOfClassType - Build a call to an object of class
3013/// type (C++ [over.call.object]), which can end up invoking an
3014/// overloaded function call operator (@c operator()) or performing a
3015/// user-defined conversion on the object argument.
3016Action::ExprResult
3017Sema::BuildCallToObjectOfClassType(Expr *Object, SourceLocation LParenLoc,
3018                                   Expr **Args, unsigned NumArgs,
3019                                   SourceLocation *CommaLocs,
3020                                   SourceLocation RParenLoc) {
3021  assert(Object->getType()->isRecordType() && "Requires object type argument");
3022  const RecordType *Record = Object->getType()->getAsRecordType();
3023
3024  // C++ [over.call.object]p1:
3025  //  If the primary-expression E in the function call syntax
3026  //  evaluates to a class object of type “cv T”, then the set of
3027  //  candidate functions includes at least the function call
3028  //  operators of T. The function call operators of T are obtained by
3029  //  ordinary lookup of the name operator() in the context of
3030  //  (E).operator().
3031  OverloadCandidateSet CandidateSet;
3032  IdentifierResolver::iterator I
3033    = IdResolver.begin(Context.DeclarationNames.getCXXOperatorName(OO_Call),
3034                       cast<CXXRecordType>(Record)->getDecl(),
3035                       /*LookInParentCtx=*/false);
3036  NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
3037  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3038    AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3039                       /*SuppressUserConversions=*/false);
3040  else if (OverloadedFunctionDecl *Ovl
3041           = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3042    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3043           FEnd = Ovl->function_end();
3044         F != FEnd; ++F) {
3045      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3046        AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet,
3047                           /*SuppressUserConversions=*/false);
3048    }
3049  }
3050
3051  // C++ [over.call.object]p2:
3052  //   In addition, for each conversion function declared in T of the
3053  //   form
3054  //
3055  //        operator conversion-type-id () cv-qualifier;
3056  //
3057  //   where cv-qualifier is the same cv-qualification as, or a
3058  //   greater cv-qualification than, cv, and where conversion-type-id
3059  //   denotes the type "pointer to function of (P1,...,Pn) returning
3060  //   R", or the type "reference to pointer to function of
3061  //   (P1,...,Pn) returning R", or the type "reference to function
3062  //   of (P1,...,Pn) returning R", a surrogate call function [...]
3063  //   is also considered as a candidate function. Similarly,
3064  //   surrogate call functions are added to the set of candidate
3065  //   functions for each conversion function declared in an
3066  //   accessible base class provided the function is not hidden
3067  //   within T by another intervening declaration.
3068  //
3069  // FIXME: Look in base classes for more conversion operators!
3070  OverloadedFunctionDecl *Conversions
3071    = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
3072  for (OverloadedFunctionDecl::function_iterator
3073         Func = Conversions->function_begin(),
3074         FuncEnd = Conversions->function_end();
3075       Func != FuncEnd; ++Func) {
3076    CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func);
3077
3078    // Strip the reference type (if any) and then the pointer type (if
3079    // any) to get down to what might be a function type.
3080    QualType ConvType = Conv->getConversionType().getNonReferenceType();
3081    if (const PointerType *ConvPtrType = ConvType->getAsPointerType())
3082      ConvType = ConvPtrType->getPointeeType();
3083
3084    if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto())
3085      AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
3086  }
3087
3088  // Perform overload resolution.
3089  OverloadCandidateSet::iterator Best;
3090  switch (BestViableFunction(CandidateSet, Best)) {
3091  case OR_Success:
3092    // Overload resolution succeeded; we'll build the appropriate call
3093    // below.
3094    break;
3095
3096  case OR_No_Viable_Function:
3097    Diag(Object->getSourceRange().getBegin(),
3098         diag::err_ovl_no_viable_object_call)
3099      << Object->getType() << (unsigned)CandidateSet.size()
3100      << Object->getSourceRange();
3101    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3102    break;
3103
3104  case OR_Ambiguous:
3105    Diag(Object->getSourceRange().getBegin(),
3106         diag::err_ovl_ambiguous_object_call)
3107      << Object->getType() << Object->getSourceRange();
3108    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3109    break;
3110  }
3111
3112  if (Best == CandidateSet.end()) {
3113    // We had an error; delete all of the subexpressions and return
3114    // the error.
3115    delete Object;
3116    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3117      delete Args[ArgIdx];
3118    return true;
3119  }
3120
3121  if (Best->Function == 0) {
3122    // Since there is no function declaration, this is one of the
3123    // surrogate candidates. Dig out the conversion function.
3124    CXXConversionDecl *Conv
3125      = cast<CXXConversionDecl>(
3126                         Best->Conversions[0].UserDefined.ConversionFunction);
3127
3128    // We selected one of the surrogate functions that converts the
3129    // object parameter to a function pointer. Perform the conversion
3130    // on the object argument, then let ActOnCallExpr finish the job.
3131    // FIXME: Represent the user-defined conversion in the AST!
3132    ImpCastExprToType(Object,
3133                      Conv->getConversionType().getNonReferenceType(),
3134                      Conv->getConversionType()->isReferenceType());
3135    return ActOnCallExpr((ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs,
3136                         CommaLocs, RParenLoc);
3137  }
3138
3139  // We found an overloaded operator(). Build a CXXOperatorCallExpr
3140  // that calls this method, using Object for the implicit object
3141  // parameter and passing along the remaining arguments.
3142  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
3143  const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto();
3144
3145  unsigned NumArgsInProto = Proto->getNumArgs();
3146  unsigned NumArgsToCheck = NumArgs;
3147
3148  // Build the full argument list for the method call (the
3149  // implicit object parameter is placed at the beginning of the
3150  // list).
3151  Expr **MethodArgs;
3152  if (NumArgs < NumArgsInProto) {
3153    NumArgsToCheck = NumArgsInProto;
3154    MethodArgs = new Expr*[NumArgsInProto + 1];
3155  } else {
3156    MethodArgs = new Expr*[NumArgs + 1];
3157  }
3158  MethodArgs[0] = Object;
3159  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3160    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
3161
3162  Expr *NewFn = new DeclRefExpr(Method, Method->getType(),
3163                                SourceLocation());
3164  UsualUnaryConversions(NewFn);
3165
3166  // Once we've built TheCall, all of the expressions are properly
3167  // owned.
3168  QualType ResultTy = Method->getResultType().getNonReferenceType();
3169  llvm::OwningPtr<CXXOperatorCallExpr>
3170    TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1,
3171                                    ResultTy, RParenLoc));
3172  delete [] MethodArgs;
3173
3174  // Initialize the implicit object parameter.
3175  if (!PerformObjectArgumentInitialization(Object, Method))
3176    return true;
3177  TheCall->setArg(0, Object);
3178
3179  // Check the argument types.
3180  for (unsigned i = 0; i != NumArgsToCheck; i++) {
3181    QualType ProtoArgType = Proto->getArgType(i);
3182
3183    Expr *Arg;
3184    if (i < NumArgs)
3185      Arg = Args[i];
3186    else
3187      Arg = new CXXDefaultArgExpr(Method->getParamDecl(i));
3188    QualType ArgType = Arg->getType();
3189
3190    // Pass the argument.
3191    if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
3192      return true;
3193
3194    TheCall->setArg(i + 1, Arg);
3195  }
3196
3197  // If this is a variadic call, handle args passed through "...".
3198  if (Proto->isVariadic()) {
3199    // Promote the arguments (C99 6.5.2.2p7).
3200    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
3201      Expr *Arg = Args[i];
3202      DefaultArgumentPromotion(Arg);
3203      TheCall->setArg(i + 1, Arg);
3204    }
3205  }
3206
3207  return CheckFunctionCall(Method, TheCall.take());
3208}
3209
3210/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
3211///  (if one exists), where @c Base is an expression of class type and
3212/// @c Member is the name of the member we're trying to find.
3213Action::ExprResult
3214Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc,
3215                               SourceLocation MemberLoc,
3216                               IdentifierInfo &Member) {
3217  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
3218
3219  // C++ [over.ref]p1:
3220  //
3221  //   [...] An expression x->m is interpreted as (x.operator->())->m
3222  //   for a class object x of type T if T::operator->() exists and if
3223  //   the operator is selected as the best match function by the
3224  //   overload resolution mechanism (13.3).
3225  // FIXME: look in base classes.
3226  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
3227  OverloadCandidateSet CandidateSet;
3228  const RecordType *BaseRecord = Base->getType()->getAsRecordType();
3229  IdentifierResolver::iterator I
3230    = IdResolver.begin(OpName, cast<CXXRecordType>(BaseRecord)->getDecl(),
3231                       /*LookInParentCtx=*/false);
3232  NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I;
3233  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps))
3234    AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3235                       /*SuppressUserConversions=*/false);
3236  else if (OverloadedFunctionDecl *Ovl
3237             = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) {
3238    for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(),
3239           FEnd = Ovl->function_end();
3240         F != FEnd; ++F) {
3241      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F))
3242        AddMethodCandidate(Method, Base, 0, 0, CandidateSet,
3243                           /*SuppressUserConversions=*/false);
3244    }
3245  }
3246
3247  llvm::OwningPtr<Expr> BasePtr(Base);
3248
3249  // Perform overload resolution.
3250  OverloadCandidateSet::iterator Best;
3251  switch (BestViableFunction(CandidateSet, Best)) {
3252  case OR_Success:
3253    // Overload resolution succeeded; we'll build the call below.
3254    break;
3255
3256  case OR_No_Viable_Function:
3257    if (CandidateSet.empty())
3258      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
3259        << BasePtr->getType() << BasePtr->getSourceRange();
3260    else
3261      Diag(OpLoc, diag::err_ovl_no_viable_oper)
3262        << "operator->" << (unsigned)CandidateSet.size()
3263        << BasePtr->getSourceRange();
3264    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
3265    return true;
3266
3267  case OR_Ambiguous:
3268    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
3269      << "operator->" << BasePtr->getSourceRange();
3270    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3271    return true;
3272  }
3273
3274  // Convert the object parameter.
3275  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
3276  if (PerformObjectArgumentInitialization(Base, Method))
3277    return true;
3278
3279  // No concerns about early exits now.
3280  BasePtr.take();
3281
3282  // Build the operator call.
3283  Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation());
3284  UsualUnaryConversions(FnExpr);
3285  Base = new CXXOperatorCallExpr(FnExpr, &Base, 1,
3286                                 Method->getResultType().getNonReferenceType(),
3287                                 OpLoc);
3288  return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member);
3289}
3290
3291/// FixOverloadedFunctionReference - E is an expression that refers to
3292/// a C++ overloaded function (possibly with some parentheses and
3293/// perhaps a '&' around it). We have resolved the overloaded function
3294/// to the function declaration Fn, so patch up the expression E to
3295/// refer (possibly indirectly) to Fn.
3296void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
3297  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
3298    FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
3299    E->setType(PE->getSubExpr()->getType());
3300  } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
3301    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
3302           "Can only take the address of an overloaded function");
3303    FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
3304    E->setType(Context.getPointerType(E->getType()));
3305  } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
3306    assert(isa<OverloadedFunctionDecl>(DR->getDecl()) &&
3307           "Expected overloaded function");
3308    DR->setDecl(Fn);
3309    E->setType(Fn->getType());
3310  } else {
3311    assert(false && "Invalid reference to overloaded function");
3312  }
3313}
3314
3315} // end namespace clang
3316