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