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