SemaOverload.cpp revision 200583
1193326Sed//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2193326Sed//
3193326Sed//                     The LLVM Compiler Infrastructure
4193326Sed//
5193326Sed// This file is distributed under the University of Illinois Open Source
6193326Sed// License. See LICENSE.TXT for details.
7193326Sed//
8193326Sed//===----------------------------------------------------------------------===//
9193326Sed//
10193326Sed// This file provides Sema routines for C++ overloading.
11193326Sed//
12193326Sed//===----------------------------------------------------------------------===//
13193326Sed
14193326Sed#include "Sema.h"
15199482Srdivacky#include "Lookup.h"
16193326Sed#include "clang/Basic/Diagnostic.h"
17193326Sed#include "clang/Lex/Preprocessor.h"
18193326Sed#include "clang/AST/ASTContext.h"
19198092Srdivacky#include "clang/AST/CXXInheritance.h"
20193326Sed#include "clang/AST/Expr.h"
21193326Sed#include "clang/AST/ExprCXX.h"
22193326Sed#include "clang/AST/TypeOrdering.h"
23198092Srdivacky#include "clang/Basic/PartialDiagnostic.h"
24193326Sed#include "llvm/ADT/SmallPtrSet.h"
25193326Sed#include "llvm/ADT/STLExtras.h"
26193326Sed#include <algorithm>
27198092Srdivacky#include <cstdio>
28193326Sed
29193326Sednamespace clang {
30193326Sed
31193326Sed/// GetConversionCategory - Retrieve the implicit conversion
32193326Sed/// category corresponding to the given implicit conversion kind.
33198092SrdivackyImplicitConversionCategory
34193326SedGetConversionCategory(ImplicitConversionKind Kind) {
35193326Sed  static const ImplicitConversionCategory
36193326Sed    Category[(int)ICK_Num_Conversion_Kinds] = {
37193326Sed    ICC_Identity,
38193326Sed    ICC_Lvalue_Transformation,
39193326Sed    ICC_Lvalue_Transformation,
40193326Sed    ICC_Lvalue_Transformation,
41200583Srdivacky    ICC_Identity,
42193326Sed    ICC_Qualification_Adjustment,
43193326Sed    ICC_Promotion,
44193326Sed    ICC_Promotion,
45193326Sed    ICC_Promotion,
46193326Sed    ICC_Conversion,
47193326Sed    ICC_Conversion,
48193326Sed    ICC_Conversion,
49193326Sed    ICC_Conversion,
50193326Sed    ICC_Conversion,
51193326Sed    ICC_Conversion,
52193326Sed    ICC_Conversion,
53193326Sed    ICC_Conversion,
54193326Sed    ICC_Conversion,
55193326Sed    ICC_Conversion
56193326Sed  };
57193326Sed  return Category[(int)Kind];
58193326Sed}
59193326Sed
60193326Sed/// GetConversionRank - Retrieve the implicit conversion rank
61193326Sed/// corresponding to the given implicit conversion kind.
62193326SedImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63193326Sed  static const ImplicitConversionRank
64193326Sed    Rank[(int)ICK_Num_Conversion_Kinds] = {
65193326Sed    ICR_Exact_Match,
66193326Sed    ICR_Exact_Match,
67193326Sed    ICR_Exact_Match,
68193326Sed    ICR_Exact_Match,
69193326Sed    ICR_Exact_Match,
70200583Srdivacky    ICR_Exact_Match,
71193326Sed    ICR_Promotion,
72193326Sed    ICR_Promotion,
73193326Sed    ICR_Promotion,
74193326Sed    ICR_Conversion,
75193326Sed    ICR_Conversion,
76193326Sed    ICR_Conversion,
77193326Sed    ICR_Conversion,
78193326Sed    ICR_Conversion,
79193326Sed    ICR_Conversion,
80193326Sed    ICR_Conversion,
81193326Sed    ICR_Conversion,
82193326Sed    ICR_Conversion,
83193326Sed    ICR_Conversion
84193326Sed  };
85193326Sed  return Rank[(int)Kind];
86193326Sed}
87193326Sed
88193326Sed/// GetImplicitConversionName - Return the name of this kind of
89193326Sed/// implicit conversion.
90193326Sedconst char* GetImplicitConversionName(ImplicitConversionKind Kind) {
91193326Sed  static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
92193326Sed    "No conversion",
93193326Sed    "Lvalue-to-rvalue",
94193326Sed    "Array-to-pointer",
95193326Sed    "Function-to-pointer",
96200583Srdivacky    "Noreturn adjustment",
97193326Sed    "Qualification",
98193326Sed    "Integral promotion",
99193326Sed    "Floating point promotion",
100193326Sed    "Complex promotion",
101193326Sed    "Integral conversion",
102193326Sed    "Floating conversion",
103193326Sed    "Complex conversion",
104193326Sed    "Floating-integral conversion",
105193326Sed    "Complex-real conversion",
106193326Sed    "Pointer conversion",
107193326Sed    "Pointer-to-member conversion",
108193326Sed    "Boolean conversion",
109193326Sed    "Compatible-types conversion",
110193326Sed    "Derived-to-base conversion"
111193326Sed  };
112193326Sed  return Name[Kind];
113193326Sed}
114193326Sed
115193326Sed/// StandardConversionSequence - Set the standard conversion
116193326Sed/// sequence to the identity conversion.
117193326Sedvoid StandardConversionSequence::setAsIdentityConversion() {
118193326Sed  First = ICK_Identity;
119193326Sed  Second = ICK_Identity;
120193326Sed  Third = ICK_Identity;
121193326Sed  Deprecated = false;
122193326Sed  ReferenceBinding = false;
123193326Sed  DirectBinding = false;
124193326Sed  RRefBinding = false;
125193326Sed  CopyConstructor = 0;
126193326Sed}
127193326Sed
128193326Sed/// getRank - Retrieve the rank of this standard conversion sequence
129193326Sed/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130193326Sed/// implicit conversions.
131193326SedImplicitConversionRank StandardConversionSequence::getRank() const {
132193326Sed  ImplicitConversionRank Rank = ICR_Exact_Match;
133193326Sed  if  (GetConversionRank(First) > Rank)
134193326Sed    Rank = GetConversionRank(First);
135193326Sed  if  (GetConversionRank(Second) > Rank)
136193326Sed    Rank = GetConversionRank(Second);
137193326Sed  if  (GetConversionRank(Third) > Rank)
138193326Sed    Rank = GetConversionRank(Third);
139193326Sed  return Rank;
140193326Sed}
141193326Sed
142193326Sed/// isPointerConversionToBool - Determines whether this conversion is
143193326Sed/// a conversion of a pointer or pointer-to-member to bool. This is
144198092Srdivacky/// used as part of the ranking of standard conversion sequences
145193326Sed/// (C++ 13.3.3.2p4).
146198092Srdivackybool StandardConversionSequence::isPointerConversionToBool() const {
147193326Sed  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
148193326Sed  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
149193326Sed
150193326Sed  // Note that FromType has not necessarily been transformed by the
151193326Sed  // array-to-pointer or function-to-pointer implicit conversions, so
152193326Sed  // check for their presence as well as checking whether FromType is
153193326Sed  // a pointer.
154193326Sed  if (ToType->isBooleanType() &&
155193326Sed      (FromType->isPointerType() || FromType->isBlockPointerType() ||
156193326Sed       First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
157193326Sed    return true;
158193326Sed
159193326Sed  return false;
160193326Sed}
161193326Sed
162193326Sed/// isPointerConversionToVoidPointer - Determines whether this
163193326Sed/// conversion is a conversion of a pointer to a void pointer. This is
164193326Sed/// used as part of the ranking of standard conversion sequences (C++
165193326Sed/// 13.3.3.2p4).
166198092Srdivackybool
167193326SedStandardConversionSequence::
168198092SrdivackyisPointerConversionToVoidPointer(ASTContext& Context) const {
169193326Sed  QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
170193326Sed  QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
171193326Sed
172193326Sed  // Note that FromType has not necessarily been transformed by the
173193326Sed  // array-to-pointer implicit conversion, so check for its presence
174193326Sed  // and redo the conversion to get a pointer.
175193326Sed  if (First == ICK_Array_To_Pointer)
176193326Sed    FromType = Context.getArrayDecayedType(FromType);
177193326Sed
178200583Srdivacky  if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
179198092Srdivacky    if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
180193326Sed      return ToPtrType->getPointeeType()->isVoidType();
181193326Sed
182193326Sed  return false;
183193326Sed}
184193326Sed
185193326Sed/// DebugPrint - Print this standard conversion sequence to standard
186193326Sed/// error. Useful for debugging overloading issues.
187193326Sedvoid StandardConversionSequence::DebugPrint() const {
188193326Sed  bool PrintedSomething = false;
189193326Sed  if (First != ICK_Identity) {
190193326Sed    fprintf(stderr, "%s", GetImplicitConversionName(First));
191193326Sed    PrintedSomething = true;
192193326Sed  }
193193326Sed
194193326Sed  if (Second != ICK_Identity) {
195193326Sed    if (PrintedSomething) {
196193326Sed      fprintf(stderr, " -> ");
197193326Sed    }
198193326Sed    fprintf(stderr, "%s", GetImplicitConversionName(Second));
199193326Sed
200193326Sed    if (CopyConstructor) {
201193326Sed      fprintf(stderr, " (by copy constructor)");
202193326Sed    } else if (DirectBinding) {
203193326Sed      fprintf(stderr, " (direct reference binding)");
204193326Sed    } else if (ReferenceBinding) {
205193326Sed      fprintf(stderr, " (reference binding)");
206193326Sed    }
207193326Sed    PrintedSomething = true;
208193326Sed  }
209193326Sed
210193326Sed  if (Third != ICK_Identity) {
211193326Sed    if (PrintedSomething) {
212193326Sed      fprintf(stderr, " -> ");
213193326Sed    }
214193326Sed    fprintf(stderr, "%s", GetImplicitConversionName(Third));
215193326Sed    PrintedSomething = true;
216193326Sed  }
217193326Sed
218193326Sed  if (!PrintedSomething) {
219193326Sed    fprintf(stderr, "No conversions required");
220193326Sed  }
221193326Sed}
222193326Sed
223193326Sed/// DebugPrint - Print this user-defined conversion sequence to standard
224193326Sed/// error. Useful for debugging overloading issues.
225193326Sedvoid UserDefinedConversionSequence::DebugPrint() const {
226193326Sed  if (Before.First || Before.Second || Before.Third) {
227193326Sed    Before.DebugPrint();
228193326Sed    fprintf(stderr, " -> ");
229193326Sed  }
230193326Sed  fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
231193326Sed  if (After.First || After.Second || After.Third) {
232193326Sed    fprintf(stderr, " -> ");
233193326Sed    After.DebugPrint();
234193326Sed  }
235193326Sed}
236193326Sed
237193326Sed/// DebugPrint - Print this implicit conversion sequence to standard
238193326Sed/// error. Useful for debugging overloading issues.
239193326Sedvoid ImplicitConversionSequence::DebugPrint() const {
240193326Sed  switch (ConversionKind) {
241193326Sed  case StandardConversion:
242193326Sed    fprintf(stderr, "Standard conversion: ");
243193326Sed    Standard.DebugPrint();
244193326Sed    break;
245193326Sed  case UserDefinedConversion:
246193326Sed    fprintf(stderr, "User-defined conversion: ");
247193326Sed    UserDefined.DebugPrint();
248193326Sed    break;
249193326Sed  case EllipsisConversion:
250193326Sed    fprintf(stderr, "Ellipsis conversion");
251193326Sed    break;
252193326Sed  case BadConversion:
253193326Sed    fprintf(stderr, "Bad conversion");
254193326Sed    break;
255193326Sed  }
256193326Sed
257193326Sed  fprintf(stderr, "\n");
258193326Sed}
259193326Sed
260193326Sed// IsOverload - Determine whether the given New declaration is an
261200583Srdivacky// overload of the declarations in Old. This routine returns false if
262200583Srdivacky// New and Old cannot be overloaded, e.g., if New has the same
263200583Srdivacky// signature as some function in Old (C++ 1.3.10) or if the Old
264200583Srdivacky// declarations aren't functions (or function templates) at all. When
265200583Srdivacky// it does return false, MatchedDecl will point to the decl that New
266200583Srdivacky// cannot be overloaded with.  This decl may be a UsingShadowDecl on
267200583Srdivacky// top of the underlying declaration.
268193326Sed//
269193326Sed// Example: Given the following input:
270193326Sed//
271193326Sed//   void f(int, float); // #1
272193326Sed//   void f(int, int); // #2
273193326Sed//   int f(int, int); // #3
274193326Sed//
275193326Sed// When we process #1, there is no previous declaration of "f",
276198092Srdivacky// so IsOverload will not be used.
277193326Sed//
278200583Srdivacky// When we process #2, Old contains only the FunctionDecl for #1.  By
279200583Srdivacky// comparing the parameter types, we see that #1 and #2 are overloaded
280200583Srdivacky// (since they have different signatures), so this routine returns
281200583Srdivacky// false; MatchedDecl is unchanged.
282193326Sed//
283200583Srdivacky// When we process #3, Old is an overload set containing #1 and #2. We
284200583Srdivacky// compare the signatures of #3 to #1 (they're overloaded, so we do
285200583Srdivacky// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
286200583Srdivacky// identical (return types of functions are not part of the
287193326Sed// signature), IsOverload returns false and MatchedDecl will be set to
288193326Sed// point to the FunctionDecl for #2.
289200583SrdivackySema::OverloadKind
290200583SrdivackySema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
291200583Srdivacky                    NamedDecl *&Match) {
292200583Srdivacky  for (LookupResult::iterator I = Old.begin(), E = Old.end();
293199512Srdivacky         I != E; ++I) {
294200583Srdivacky    NamedDecl *OldD = (*I)->getUnderlyingDecl();
295200583Srdivacky    if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
296199512Srdivacky      if (!IsOverload(New, OldT->getTemplatedDecl())) {
297200583Srdivacky        Match = *I;
298200583Srdivacky        return Ovl_Match;
299193326Sed      }
300200583Srdivacky    } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
301199512Srdivacky      if (!IsOverload(New, OldF)) {
302200583Srdivacky        Match = *I;
303200583Srdivacky        return Ovl_Match;
304199512Srdivacky      }
305200583Srdivacky    } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
306200583Srdivacky      // We can overload with these, which can show up when doing
307200583Srdivacky      // redeclaration checks for UsingDecls.
308200583Srdivacky      assert(Old.getLookupKind() == LookupUsingDeclName);
309200583Srdivacky    } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
310200583Srdivacky      // Optimistically assume that an unresolved using decl will
311200583Srdivacky      // overload; if it doesn't, we'll have to diagnose during
312200583Srdivacky      // template instantiation.
313199512Srdivacky    } else {
314199512Srdivacky      // (C++ 13p1):
315199512Srdivacky      //   Only function declarations can be overloaded; object and type
316199512Srdivacky      //   declarations cannot be overloaded.
317200583Srdivacky      Match = *I;
318200583Srdivacky      return Ovl_NonFunction;
319193326Sed    }
320199512Srdivacky  }
321193326Sed
322200583Srdivacky  return Ovl_Overload;
323199512Srdivacky}
324198092Srdivacky
325199512Srdivackybool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
326199512Srdivacky  FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
327199512Srdivacky  FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
328195099Sed
329199512Srdivacky  // C++ [temp.fct]p2:
330199512Srdivacky  //   A function template can be overloaded with other function templates
331199512Srdivacky  //   and with normal (non-template) functions.
332199512Srdivacky  if ((OldTemplate == 0) != (NewTemplate == 0))
333199512Srdivacky    return true;
334193326Sed
335199512Srdivacky  // Is the function New an overload of the function Old?
336199512Srdivacky  QualType OldQType = Context.getCanonicalType(Old->getType());
337199512Srdivacky  QualType NewQType = Context.getCanonicalType(New->getType());
338193326Sed
339199512Srdivacky  // Compare the signatures (C++ 1.3.10) of the two functions to
340199512Srdivacky  // determine whether they are overloads. If we find any mismatch
341199512Srdivacky  // in the signature, they are overloads.
342193326Sed
343199512Srdivacky  // If either of these functions is a K&R-style function (no
344199512Srdivacky  // prototype), then we consider them to have matching signatures.
345199512Srdivacky  if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
346199512Srdivacky      isa<FunctionNoProtoType>(NewQType.getTypePtr()))
347199512Srdivacky    return false;
348193326Sed
349199512Srdivacky  FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
350199512Srdivacky  FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
351193326Sed
352199512Srdivacky  // The signature of a function includes the types of its
353199512Srdivacky  // parameters (C++ 1.3.10), which includes the presence or absence
354199512Srdivacky  // of the ellipsis; see C++ DR 357).
355199512Srdivacky  if (OldQType != NewQType &&
356199512Srdivacky      (OldType->getNumArgs() != NewType->getNumArgs() ||
357199512Srdivacky       OldType->isVariadic() != NewType->isVariadic() ||
358199512Srdivacky       !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
359199512Srdivacky                   NewType->arg_type_begin())))
360199512Srdivacky    return true;
361198092Srdivacky
362199512Srdivacky  // C++ [temp.over.link]p4:
363199512Srdivacky  //   The signature of a function template consists of its function
364199512Srdivacky  //   signature, its return type and its template parameter list. The names
365199512Srdivacky  //   of the template parameters are significant only for establishing the
366199512Srdivacky  //   relationship between the template parameters and the rest of the
367199512Srdivacky  //   signature.
368199512Srdivacky  //
369199512Srdivacky  // We check the return type and template parameter lists for function
370199512Srdivacky  // templates first; the remaining checks follow.
371199512Srdivacky  if (NewTemplate &&
372199512Srdivacky      (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
373199512Srdivacky                                       OldTemplate->getTemplateParameters(),
374199512Srdivacky                                       false, TPL_TemplateMatch) ||
375199512Srdivacky       OldType->getResultType() != NewType->getResultType()))
376199512Srdivacky    return true;
377193326Sed
378199512Srdivacky  // If the function is a class member, its signature includes the
379199512Srdivacky  // cv-qualifiers (if any) on the function itself.
380199512Srdivacky  //
381199512Srdivacky  // As part of this, also check whether one of the member functions
382199512Srdivacky  // is static, in which case they are not overloads (C++
383199512Srdivacky  // 13.1p2). While not part of the definition of the signature,
384199512Srdivacky  // this check is important to determine whether these functions
385199512Srdivacky  // can be overloaded.
386199512Srdivacky  CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
387199512Srdivacky  CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
388199512Srdivacky  if (OldMethod && NewMethod &&
389199512Srdivacky      !OldMethod->isStatic() && !NewMethod->isStatic() &&
390199512Srdivacky      OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
391199512Srdivacky    return true;
392199512Srdivacky
393199512Srdivacky  // The signatures match; this is not an overload.
394199512Srdivacky  return false;
395193326Sed}
396193326Sed
397193326Sed/// TryImplicitConversion - Attempt to perform an implicit conversion
398193326Sed/// from the given expression (Expr) to the given type (ToType). This
399193326Sed/// function returns an implicit conversion sequence that can be used
400193326Sed/// to perform the initialization. Given
401193326Sed///
402193326Sed///   void f(float f);
403193326Sed///   void g(int i) { f(i); }
404193326Sed///
405193326Sed/// this routine would produce an implicit conversion sequence to
406193326Sed/// describe the initialization of f from i, which will be a standard
407193326Sed/// conversion sequence containing an lvalue-to-rvalue conversion (C++
408193326Sed/// 4.1) followed by a floating-integral conversion (C++ 4.9).
409193326Sed//
410193326Sed/// Note that this routine only determines how the conversion can be
411193326Sed/// performed; it does not actually perform the conversion. As such,
412193326Sed/// it will not produce any diagnostics if no conversion is available,
413193326Sed/// but will instead return an implicit conversion sequence of kind
414193326Sed/// "BadConversion".
415193326Sed///
416193326Sed/// If @p SuppressUserConversions, then user-defined conversions are
417193326Sed/// not permitted.
418193326Sed/// If @p AllowExplicit, then explicit user-defined conversions are
419193326Sed/// permitted.
420193326Sed/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
421193326Sed/// no matter its actual lvalueness.
422198092Srdivacky/// If @p UserCast, the implicit conversion is being done for a user-specified
423198092Srdivacky/// cast.
424193326SedImplicitConversionSequence
425193326SedSema::TryImplicitConversion(Expr* From, QualType ToType,
426193326Sed                            bool SuppressUserConversions,
427198092Srdivacky                            bool AllowExplicit, bool ForceRValue,
428198092Srdivacky                            bool InOverloadResolution,
429198092Srdivacky                            bool UserCast) {
430193326Sed  ImplicitConversionSequence ICS;
431198092Srdivacky  OverloadCandidateSet Conversions;
432198092Srdivacky  OverloadingResult UserDefResult = OR_Success;
433198092Srdivacky  if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
434193326Sed    ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
435193326Sed  else if (getLangOptions().CPlusPlus &&
436198092Srdivacky           (UserDefResult = IsUserDefinedConversion(From, ToType,
437198092Srdivacky                                   ICS.UserDefined,
438198092Srdivacky                                   Conversions,
439193326Sed                                   !SuppressUserConversions, AllowExplicit,
440198092Srdivacky				   ForceRValue, UserCast)) == OR_Success) {
441193326Sed    ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
442193326Sed    // C++ [over.ics.user]p4:
443193326Sed    //   A conversion of an expression of class type to the same class
444193326Sed    //   type is given Exact Match rank, and a conversion of an
445193326Sed    //   expression of class type to a base class of that type is
446193326Sed    //   given Conversion rank, in spite of the fact that a copy
447193326Sed    //   constructor (i.e., a user-defined conversion function) is
448193326Sed    //   called for those cases.
449198092Srdivacky    if (CXXConstructorDecl *Constructor
450193326Sed          = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
451198092Srdivacky      QualType FromCanon
452193326Sed        = Context.getCanonicalType(From->getType().getUnqualifiedType());
453193326Sed      QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
454193326Sed      if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
455193326Sed        // Turn this into a "standard" conversion sequence, so that it
456193326Sed        // gets ranked with standard conversion sequences.
457193326Sed        ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
458193326Sed        ICS.Standard.setAsIdentityConversion();
459193326Sed        ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
460193326Sed        ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
461193326Sed        ICS.Standard.CopyConstructor = Constructor;
462193326Sed        if (ToCanon != FromCanon)
463193326Sed          ICS.Standard.Second = ICK_Derived_To_Base;
464193326Sed      }
465193326Sed    }
466193326Sed
467193326Sed    // C++ [over.best.ics]p4:
468193326Sed    //   However, when considering the argument of a user-defined
469193326Sed    //   conversion function that is a candidate by 13.3.1.3 when
470193326Sed    //   invoked for the copying of the temporary in the second step
471193326Sed    //   of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
472193326Sed    //   13.3.1.6 in all cases, only standard conversion sequences and
473193326Sed    //   ellipsis conversion sequences are allowed.
474193326Sed    if (SuppressUserConversions &&
475193326Sed        ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
476193326Sed      ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
477198092Srdivacky  } else {
478193326Sed    ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
479198092Srdivacky    if (UserDefResult == OR_Ambiguous) {
480198092Srdivacky      for (OverloadCandidateSet::iterator Cand = Conversions.begin();
481198092Srdivacky           Cand != Conversions.end(); ++Cand)
482198092Srdivacky        if (Cand->Viable)
483198092Srdivacky          ICS.ConversionFunctionSet.push_back(Cand->Function);
484198092Srdivacky    }
485198092Srdivacky  }
486193326Sed
487193326Sed  return ICS;
488193326Sed}
489193326Sed
490200583Srdivacky/// \brief Determine whether the conversion from FromType to ToType is a valid
491200583Srdivacky/// conversion that strips "noreturn" off the nested function type.
492200583Srdivackystatic bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
493200583Srdivacky                                 QualType ToType, QualType &ResultTy) {
494200583Srdivacky  if (Context.hasSameUnqualifiedType(FromType, ToType))
495200583Srdivacky    return false;
496200583Srdivacky
497200583Srdivacky  // Strip the noreturn off the type we're converting from; noreturn can
498200583Srdivacky  // safely be removed.
499200583Srdivacky  FromType = Context.getNoReturnType(FromType, false);
500200583Srdivacky  if (!Context.hasSameUnqualifiedType(FromType, ToType))
501200583Srdivacky    return false;
502200583Srdivacky
503200583Srdivacky  ResultTy = FromType;
504200583Srdivacky  return true;
505200583Srdivacky}
506200583Srdivacky
507193326Sed/// IsStandardConversion - Determines whether there is a standard
508193326Sed/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
509193326Sed/// expression From to the type ToType. Standard conversion sequences
510193326Sed/// only consider non-class types; for conversions that involve class
511193326Sed/// types, use TryImplicitConversion. If a conversion exists, SCS will
512193326Sed/// contain the standard conversion sequence required to perform this
513193326Sed/// conversion and this routine will return true. Otherwise, this
514193326Sed/// routine will return false and the value of SCS is unspecified.
515198092Srdivackybool
516198092SrdivackySema::IsStandardConversion(Expr* From, QualType ToType,
517198092Srdivacky                           bool InOverloadResolution,
518198092Srdivacky                           StandardConversionSequence &SCS) {
519193326Sed  QualType FromType = From->getType();
520193326Sed
521193326Sed  // Standard conversions (C++ [conv])
522193326Sed  SCS.setAsIdentityConversion();
523193326Sed  SCS.Deprecated = false;
524193326Sed  SCS.IncompatibleObjC = false;
525193326Sed  SCS.FromTypePtr = FromType.getAsOpaquePtr();
526193326Sed  SCS.CopyConstructor = 0;
527193326Sed
528193326Sed  // There are no standard conversions for class types in C++, so
529198092Srdivacky  // abort early. When overloading in C, however, we do permit
530193326Sed  if (FromType->isRecordType() || ToType->isRecordType()) {
531193326Sed    if (getLangOptions().CPlusPlus)
532193326Sed      return false;
533193326Sed
534198092Srdivacky    // When we're overloading in C, we allow, as standard conversions,
535193326Sed  }
536193326Sed
537193326Sed  // The first conversion can be an lvalue-to-rvalue conversion,
538193326Sed  // array-to-pointer conversion, or function-to-pointer conversion
539193326Sed  // (C++ 4p1).
540193326Sed
541198092Srdivacky  // Lvalue-to-rvalue conversion (C++ 4.1):
542193326Sed  //   An lvalue (3.10) of a non-function, non-array type T can be
543193326Sed  //   converted to an rvalue.
544193326Sed  Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
545198092Srdivacky  if (argIsLvalue == Expr::LV_Valid &&
546193326Sed      !FromType->isFunctionType() && !FromType->isArrayType() &&
547193326Sed      Context.getCanonicalType(FromType) != Context.OverloadTy) {
548193326Sed    SCS.First = ICK_Lvalue_To_Rvalue;
549193326Sed
550193326Sed    // If T is a non-class type, the type of the rvalue is the
551193326Sed    // cv-unqualified version of T. Otherwise, the type of the rvalue
552193326Sed    // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
553193326Sed    // just strip the qualifiers because they don't matter.
554193326Sed    FromType = FromType.getUnqualifiedType();
555198092Srdivacky  } else if (FromType->isArrayType()) {
556198092Srdivacky    // Array-to-pointer conversion (C++ 4.2)
557193326Sed    SCS.First = ICK_Array_To_Pointer;
558193326Sed
559193326Sed    // An lvalue or rvalue of type "array of N T" or "array of unknown
560193326Sed    // bound of T" can be converted to an rvalue of type "pointer to
561193326Sed    // T" (C++ 4.2p1).
562193326Sed    FromType = Context.getArrayDecayedType(FromType);
563193326Sed
564193326Sed    if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
565193326Sed      // This conversion is deprecated. (C++ D.4).
566193326Sed      SCS.Deprecated = true;
567193326Sed
568193326Sed      // For the purpose of ranking in overload resolution
569193326Sed      // (13.3.3.1.1), this conversion is considered an
570193326Sed      // array-to-pointer conversion followed by a qualification
571193326Sed      // conversion (4.4). (C++ 4.2p2)
572193326Sed      SCS.Second = ICK_Identity;
573193326Sed      SCS.Third = ICK_Qualification;
574193326Sed      SCS.ToTypePtr = ToType.getAsOpaquePtr();
575193326Sed      return true;
576193326Sed    }
577198092Srdivacky  } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
578198092Srdivacky    // Function-to-pointer conversion (C++ 4.3).
579193326Sed    SCS.First = ICK_Function_To_Pointer;
580193326Sed
581193326Sed    // An lvalue of function type T can be converted to an rvalue of
582193326Sed    // type "pointer to T." The result is a pointer to the
583193326Sed    // function. (C++ 4.3p1).
584193326Sed    FromType = Context.getPointerType(FromType);
585198092Srdivacky  } else if (FunctionDecl *Fn
586200583Srdivacky               = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
587198092Srdivacky    // Address of overloaded function (C++ [over.over]).
588193326Sed    SCS.First = ICK_Function_To_Pointer;
589193326Sed
590193326Sed    // We were able to resolve the address of the overloaded function,
591193326Sed    // so we can convert to the type of that function.
592193326Sed    FromType = Fn->getType();
593193326Sed    if (ToType->isLValueReferenceType())
594193326Sed      FromType = Context.getLValueReferenceType(FromType);
595193326Sed    else if (ToType->isRValueReferenceType())
596193326Sed      FromType = Context.getRValueReferenceType(FromType);
597193326Sed    else if (ToType->isMemberPointerType()) {
598193326Sed      // Resolve address only succeeds if both sides are member pointers,
599193326Sed      // but it doesn't have to be the same class. See DR 247.
600193326Sed      // Note that this means that the type of &Derived::fn can be
601193326Sed      // Ret (Base::*)(Args) if the fn overload actually found is from the
602193326Sed      // base class, even if it was brought into the derived class via a
603193326Sed      // using declaration. The standard isn't clear on this issue at all.
604193326Sed      CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
605193326Sed      FromType = Context.getMemberPointerType(FromType,
606193326Sed                    Context.getTypeDeclType(M->getParent()).getTypePtr());
607193326Sed    } else
608193326Sed      FromType = Context.getPointerType(FromType);
609198092Srdivacky  } else {
610198092Srdivacky    // We don't require any conversions for the first step.
611193326Sed    SCS.First = ICK_Identity;
612193326Sed  }
613193326Sed
614193326Sed  // The second conversion can be an integral promotion, floating
615193326Sed  // point promotion, integral conversion, floating point conversion,
616193326Sed  // floating-integral conversion, pointer conversion,
617193326Sed  // pointer-to-member conversion, or boolean conversion (C++ 4p1).
618193326Sed  // For overloading in C, this can also be a "compatible-type"
619193326Sed  // conversion.
620193326Sed  bool IncompatibleObjC = false;
621193326Sed  if (Context.hasSameUnqualifiedType(FromType, ToType)) {
622193326Sed    // The unqualified versions of the types are the same: there's no
623193326Sed    // conversion to do.
624193326Sed    SCS.Second = ICK_Identity;
625198092Srdivacky  } else if (IsIntegralPromotion(From, FromType, ToType)) {
626198092Srdivacky    // Integral promotion (C++ 4.5).
627193326Sed    SCS.Second = ICK_Integral_Promotion;
628193326Sed    FromType = ToType.getUnqualifiedType();
629198092Srdivacky  } else if (IsFloatingPointPromotion(FromType, ToType)) {
630198092Srdivacky    // Floating point promotion (C++ 4.6).
631193326Sed    SCS.Second = ICK_Floating_Promotion;
632193326Sed    FromType = ToType.getUnqualifiedType();
633198092Srdivacky  } else if (IsComplexPromotion(FromType, ToType)) {
634198092Srdivacky    // Complex promotion (Clang extension)
635193326Sed    SCS.Second = ICK_Complex_Promotion;
636193326Sed    FromType = ToType.getUnqualifiedType();
637198092Srdivacky  } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
638193326Sed           (ToType->isIntegralType() && !ToType->isEnumeralType())) {
639198092Srdivacky    // Integral conversions (C++ 4.7).
640198092Srdivacky    // FIXME: isIntegralType shouldn't be true for enums in C++.
641193326Sed    SCS.Second = ICK_Integral_Conversion;
642193326Sed    FromType = ToType.getUnqualifiedType();
643198092Srdivacky  } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
644198092Srdivacky    // Floating point conversions (C++ 4.8).
645193326Sed    SCS.Second = ICK_Floating_Conversion;
646193326Sed    FromType = ToType.getUnqualifiedType();
647198092Srdivacky  } else if (FromType->isComplexType() && ToType->isComplexType()) {
648198092Srdivacky    // Complex conversions (C99 6.3.1.6)
649193326Sed    SCS.Second = ICK_Complex_Conversion;
650193326Sed    FromType = ToType.getUnqualifiedType();
651198092Srdivacky  } else if ((FromType->isFloatingType() &&
652198092Srdivacky              ToType->isIntegralType() && (!ToType->isBooleanType() &&
653198092Srdivacky                                           !ToType->isEnumeralType())) ||
654198092Srdivacky             ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
655198092Srdivacky              ToType->isFloatingType())) {
656198092Srdivacky    // Floating-integral conversions (C++ 4.9).
657198092Srdivacky    // FIXME: isIntegralType shouldn't be true for enums in C++.
658193326Sed    SCS.Second = ICK_Floating_Integral;
659193326Sed    FromType = ToType.getUnqualifiedType();
660198092Srdivacky  } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
661198092Srdivacky             (ToType->isComplexType() && FromType->isArithmeticType())) {
662198092Srdivacky    // Complex-real conversions (C99 6.3.1.7)
663193326Sed    SCS.Second = ICK_Complex_Real;
664193326Sed    FromType = ToType.getUnqualifiedType();
665198092Srdivacky  } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
666198092Srdivacky                                 FromType, IncompatibleObjC)) {
667198092Srdivacky    // Pointer conversions (C++ 4.10).
668193326Sed    SCS.Second = ICK_Pointer_Conversion;
669193326Sed    SCS.IncompatibleObjC = IncompatibleObjC;
670198092Srdivacky  } else if (IsMemberPointerConversion(From, FromType, ToType,
671198092Srdivacky                                       InOverloadResolution, FromType)) {
672198092Srdivacky    // Pointer to member conversions (4.11).
673193326Sed    SCS.Second = ICK_Pointer_Member;
674198092Srdivacky  } else if (ToType->isBooleanType() &&
675198092Srdivacky             (FromType->isArithmeticType() ||
676198092Srdivacky              FromType->isEnumeralType() ||
677200583Srdivacky              FromType->isAnyPointerType() ||
678198092Srdivacky              FromType->isBlockPointerType() ||
679198092Srdivacky              FromType->isMemberPointerType() ||
680198092Srdivacky              FromType->isNullPtrType())) {
681198092Srdivacky    // Boolean conversions (C++ 4.12).
682193326Sed    SCS.Second = ICK_Boolean_Conversion;
683193326Sed    FromType = Context.BoolTy;
684198092Srdivacky  } else if (!getLangOptions().CPlusPlus &&
685198092Srdivacky             Context.typesAreCompatible(ToType, FromType)) {
686198092Srdivacky    // Compatible conversions (Clang extension for C function overloading)
687193326Sed    SCS.Second = ICK_Compatible_Conversion;
688200583Srdivacky  } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
689200583Srdivacky    // Treat a conversion that strips "noreturn" as an identity conversion.
690200583Srdivacky    SCS.Second = ICK_NoReturn_Adjustment;
691193326Sed  } else {
692193326Sed    // No second conversion required.
693193326Sed    SCS.Second = ICK_Identity;
694193326Sed  }
695193326Sed
696193326Sed  QualType CanonFrom;
697193326Sed  QualType CanonTo;
698193326Sed  // The third conversion can be a qualification conversion (C++ 4p1).
699193326Sed  if (IsQualificationConversion(FromType, ToType)) {
700193326Sed    SCS.Third = ICK_Qualification;
701193326Sed    FromType = ToType;
702193326Sed    CanonFrom = Context.getCanonicalType(FromType);
703193326Sed    CanonTo = Context.getCanonicalType(ToType);
704193326Sed  } else {
705193326Sed    // No conversion required
706193326Sed    SCS.Third = ICK_Identity;
707193326Sed
708198092Srdivacky    // C++ [over.best.ics]p6:
709193326Sed    //   [...] Any difference in top-level cv-qualification is
710193326Sed    //   subsumed by the initialization itself and does not constitute
711193326Sed    //   a conversion. [...]
712193326Sed    CanonFrom = Context.getCanonicalType(FromType);
713198092Srdivacky    CanonTo = Context.getCanonicalType(ToType);
714199482Srdivacky    if (CanonFrom.getLocalUnqualifiedType()
715199482Srdivacky                                       == CanonTo.getLocalUnqualifiedType() &&
716199482Srdivacky        CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
717193326Sed      FromType = ToType;
718193326Sed      CanonFrom = CanonTo;
719193326Sed    }
720193326Sed  }
721193326Sed
722193326Sed  // If we have not converted the argument type to the parameter type,
723193326Sed  // this is a bad conversion sequence.
724193326Sed  if (CanonFrom != CanonTo)
725193326Sed    return false;
726193326Sed
727193326Sed  SCS.ToTypePtr = FromType.getAsOpaquePtr();
728193326Sed  return true;
729193326Sed}
730193326Sed
731193326Sed/// IsIntegralPromotion - Determines whether the conversion from the
732193326Sed/// expression From (whose potentially-adjusted type is FromType) to
733193326Sed/// ToType is an integral promotion (C++ 4.5). If so, returns true and
734193326Sed/// sets PromotedType to the promoted type.
735198092Srdivackybool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
736198092Srdivacky  const BuiltinType *To = ToType->getAs<BuiltinType>();
737193326Sed  // All integers are built-in.
738193326Sed  if (!To) {
739193326Sed    return false;
740193326Sed  }
741193326Sed
742193326Sed  // An rvalue of type char, signed char, unsigned char, short int, or
743193326Sed  // unsigned short int can be converted to an rvalue of type int if
744193326Sed  // int can represent all the values of the source type; otherwise,
745193326Sed  // the source rvalue can be converted to an rvalue of type unsigned
746193326Sed  // int (C++ 4.5p1).
747193326Sed  if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
748193326Sed    if (// We can promote any signed, promotable integer type to an int
749193326Sed        (FromType->isSignedIntegerType() ||
750193326Sed         // We can promote any unsigned integer type whose size is
751193326Sed         // less than int to an int.
752198092Srdivacky         (!FromType->isSignedIntegerType() &&
753193326Sed          Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
754193326Sed      return To->getKind() == BuiltinType::Int;
755193326Sed    }
756193326Sed
757193326Sed    return To->getKind() == BuiltinType::UInt;
758193326Sed  }
759193326Sed
760193326Sed  // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
761193326Sed  // can be converted to an rvalue of the first of the following types
762193326Sed  // that can represent all the values of its underlying type: int,
763193326Sed  // unsigned int, long, or unsigned long (C++ 4.5p2).
764200583Srdivacky
765200583Srdivacky  // We pre-calculate the promotion type for enum types.
766200583Srdivacky  if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
767200583Srdivacky    if (ToType->isIntegerType())
768200583Srdivacky      return Context.hasSameUnqualifiedType(ToType,
769200583Srdivacky                                FromEnumType->getDecl()->getPromotionType());
770200583Srdivacky
771200583Srdivacky  if (FromType->isWideCharType() && ToType->isIntegerType()) {
772193326Sed    // Determine whether the type we're converting from is signed or
773193326Sed    // unsigned.
774193326Sed    bool FromIsSigned;
775193326Sed    uint64_t FromSize = Context.getTypeSize(FromType);
776200583Srdivacky
777200583Srdivacky    // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
778200583Srdivacky    FromIsSigned = true;
779193326Sed
780193326Sed    // The types we'll try to promote to, in the appropriate
781193326Sed    // order. Try each of these types.
782198092Srdivacky    QualType PromoteTypes[6] = {
783198092Srdivacky      Context.IntTy, Context.UnsignedIntTy,
784193326Sed      Context.LongTy, Context.UnsignedLongTy ,
785193326Sed      Context.LongLongTy, Context.UnsignedLongLongTy
786193326Sed    };
787193326Sed    for (int Idx = 0; Idx < 6; ++Idx) {
788193326Sed      uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
789193326Sed      if (FromSize < ToSize ||
790198092Srdivacky          (FromSize == ToSize &&
791193326Sed           FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
792193326Sed        // We found the type that we can promote to. If this is the
793193326Sed        // type we wanted, we have a promotion. Otherwise, no
794193326Sed        // promotion.
795199482Srdivacky        return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
796193326Sed      }
797193326Sed    }
798193326Sed  }
799193326Sed
800193326Sed  // An rvalue for an integral bit-field (9.6) can be converted to an
801193326Sed  // rvalue of type int if int can represent all the values of the
802193326Sed  // bit-field; otherwise, it can be converted to unsigned int if
803193326Sed  // unsigned int can represent all the values of the bit-field. If
804193326Sed  // the bit-field is larger yet, no integral promotion applies to
805193326Sed  // it. If the bit-field has an enumerated type, it is treated as any
806193326Sed  // other value of that type for promotion purposes (C++ 4.5p3).
807193326Sed  // FIXME: We should delay checking of bit-fields until we actually perform the
808193326Sed  // conversion.
809193326Sed  using llvm::APSInt;
810193326Sed  if (From)
811193326Sed    if (FieldDecl *MemberDecl = From->getBitField()) {
812193326Sed      APSInt BitWidth;
813193326Sed      if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
814193326Sed          MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
815193326Sed        APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
816193326Sed        ToSize = Context.getTypeSize(ToType);
817198092Srdivacky
818193326Sed        // Are we promoting to an int from a bitfield that fits in an int?
819193326Sed        if (BitWidth < ToSize ||
820193326Sed            (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
821193326Sed          return To->getKind() == BuiltinType::Int;
822193326Sed        }
823198092Srdivacky
824193326Sed        // Are we promoting to an unsigned int from an unsigned bitfield
825193326Sed        // that fits into an unsigned int?
826193326Sed        if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
827193326Sed          return To->getKind() == BuiltinType::UInt;
828193326Sed        }
829198092Srdivacky
830193326Sed        return false;
831193326Sed      }
832193326Sed    }
833198092Srdivacky
834193326Sed  // An rvalue of type bool can be converted to an rvalue of type int,
835193326Sed  // with false becoming zero and true becoming one (C++ 4.5p4).
836193326Sed  if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
837193326Sed    return true;
838193326Sed  }
839193326Sed
840193326Sed  return false;
841193326Sed}
842193326Sed
843193326Sed/// IsFloatingPointPromotion - Determines whether the conversion from
844193326Sed/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
845193326Sed/// returns true and sets PromotedType to the promoted type.
846198092Srdivackybool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
847193326Sed  /// An rvalue of type float can be converted to an rvalue of type
848193326Sed  /// double. (C++ 4.6p1).
849198092Srdivacky  if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
850198092Srdivacky    if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
851193326Sed      if (FromBuiltin->getKind() == BuiltinType::Float &&
852193326Sed          ToBuiltin->getKind() == BuiltinType::Double)
853193326Sed        return true;
854193326Sed
855193326Sed      // C99 6.3.1.5p1:
856193326Sed      //   When a float is promoted to double or long double, or a
857193326Sed      //   double is promoted to long double [...].
858193326Sed      if (!getLangOptions().CPlusPlus &&
859193326Sed          (FromBuiltin->getKind() == BuiltinType::Float ||
860193326Sed           FromBuiltin->getKind() == BuiltinType::Double) &&
861193326Sed          (ToBuiltin->getKind() == BuiltinType::LongDouble))
862193326Sed        return true;
863193326Sed    }
864193326Sed
865193326Sed  return false;
866193326Sed}
867193326Sed
868193326Sed/// \brief Determine if a conversion is a complex promotion.
869193326Sed///
870193326Sed/// A complex promotion is defined as a complex -> complex conversion
871193326Sed/// where the conversion between the underlying real types is a
872193326Sed/// floating-point or integral promotion.
873193326Sedbool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
874198092Srdivacky  const ComplexType *FromComplex = FromType->getAs<ComplexType>();
875193326Sed  if (!FromComplex)
876193326Sed    return false;
877193326Sed
878198092Srdivacky  const ComplexType *ToComplex = ToType->getAs<ComplexType>();
879193326Sed  if (!ToComplex)
880193326Sed    return false;
881193326Sed
882193326Sed  return IsFloatingPointPromotion(FromComplex->getElementType(),
883193326Sed                                  ToComplex->getElementType()) ||
884193326Sed    IsIntegralPromotion(0, FromComplex->getElementType(),
885193326Sed                        ToComplex->getElementType());
886193326Sed}
887193326Sed
888193326Sed/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
889193326Sed/// the pointer type FromPtr to a pointer to type ToPointee, with the
890193326Sed/// same type qualifiers as FromPtr has on its pointee type. ToType,
891193326Sed/// if non-empty, will be a pointer to ToType that may or may not have
892193326Sed/// the right set of qualifiers on its pointee.
893198092Srdivackystatic QualType
894198092SrdivackyBuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
895193326Sed                                   QualType ToPointee, QualType ToType,
896193326Sed                                   ASTContext &Context) {
897193326Sed  QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
898193326Sed  QualType CanonToPointee = Context.getCanonicalType(ToPointee);
899198092Srdivacky  Qualifiers Quals = CanonFromPointee.getQualifiers();
900198092Srdivacky
901198092Srdivacky  // Exact qualifier match -> return the pointer type we're converting to.
902199482Srdivacky  if (CanonToPointee.getLocalQualifiers() == Quals) {
903193326Sed    // ToType is exactly what we need. Return it.
904198092Srdivacky    if (!ToType.isNull())
905193326Sed      return ToType;
906193326Sed
907193326Sed    // Build a pointer to ToPointee. It has the right qualifiers
908193326Sed    // already.
909193326Sed    return Context.getPointerType(ToPointee);
910193326Sed  }
911193326Sed
912193326Sed  // Just build a canonical type that has the right qualifiers.
913198092Srdivacky  return Context.getPointerType(
914199482Srdivacky         Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
915199482Srdivacky                                  Quals));
916193326Sed}
917193326Sed
918198092Srdivackystatic bool isNullPointerConstantForConversion(Expr *Expr,
919198092Srdivacky                                               bool InOverloadResolution,
920198092Srdivacky                                               ASTContext &Context) {
921198092Srdivacky  // Handle value-dependent integral null pointer constants correctly.
922198092Srdivacky  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
923198092Srdivacky  if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
924198092Srdivacky      Expr->getType()->isIntegralType())
925198092Srdivacky    return !InOverloadResolution;
926198092Srdivacky
927198092Srdivacky  return Expr->isNullPointerConstant(Context,
928198092Srdivacky                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
929198092Srdivacky                                        : Expr::NPC_ValueDependentIsNull);
930198092Srdivacky}
931198092Srdivacky
932193326Sed/// IsPointerConversion - Determines whether the conversion of the
933193326Sed/// expression From, which has the (possibly adjusted) type FromType,
934193326Sed/// can be converted to the type ToType via a pointer conversion (C++
935193326Sed/// 4.10). If so, returns true and places the converted type (that
936193326Sed/// might differ from ToType in its cv-qualifiers at some level) into
937193326Sed/// ConvertedType.
938193326Sed///
939193326Sed/// This routine also supports conversions to and from block pointers
940193326Sed/// and conversions with Objective-C's 'id', 'id<protocols...>', and
941193326Sed/// pointers to interfaces. FIXME: Once we've determined the
942193326Sed/// appropriate overloading rules for Objective-C, we may want to
943193326Sed/// split the Objective-C checks into a different routine; however,
944193326Sed/// GCC seems to consider all of these conversions to be pointer
945193326Sed/// conversions, so for now they live here. IncompatibleObjC will be
946193326Sed/// set if the conversion is an allowed Objective-C conversion that
947193326Sed/// should result in a warning.
948193326Sedbool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
949198092Srdivacky                               bool InOverloadResolution,
950193326Sed                               QualType& ConvertedType,
951198092Srdivacky                               bool &IncompatibleObjC) {
952193326Sed  IncompatibleObjC = false;
953193326Sed  if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
954193326Sed    return true;
955193326Sed
956198092Srdivacky  // Conversion from a null pointer constant to any Objective-C pointer type.
957198092Srdivacky  if (ToType->isObjCObjectPointerType() &&
958198092Srdivacky      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
959193326Sed    ConvertedType = ToType;
960193326Sed    return true;
961193326Sed  }
962193326Sed
963193326Sed  // Blocks: Block pointers can be converted to void*.
964193326Sed  if (FromType->isBlockPointerType() && ToType->isPointerType() &&
965198092Srdivacky      ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
966193326Sed    ConvertedType = ToType;
967193326Sed    return true;
968193326Sed  }
969193326Sed  // Blocks: A null pointer constant can be converted to a block
970193326Sed  // pointer type.
971198092Srdivacky  if (ToType->isBlockPointerType() &&
972198092Srdivacky      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
973193326Sed    ConvertedType = ToType;
974193326Sed    return true;
975193326Sed  }
976193326Sed
977193326Sed  // If the left-hand-side is nullptr_t, the right side can be a null
978193326Sed  // pointer constant.
979198092Srdivacky  if (ToType->isNullPtrType() &&
980198092Srdivacky      isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
981193326Sed    ConvertedType = ToType;
982193326Sed    return true;
983193326Sed  }
984193326Sed
985198092Srdivacky  const PointerType* ToTypePtr = ToType->getAs<PointerType>();
986193326Sed  if (!ToTypePtr)
987193326Sed    return false;
988193326Sed
989193326Sed  // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
990198092Srdivacky  if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
991193326Sed    ConvertedType = ToType;
992193326Sed    return true;
993193326Sed  }
994193326Sed
995193326Sed  // Beyond this point, both types need to be pointers.
996198092Srdivacky  const PointerType *FromTypePtr = FromType->getAs<PointerType>();
997193326Sed  if (!FromTypePtr)
998193326Sed    return false;
999193326Sed
1000193326Sed  QualType FromPointeeType = FromTypePtr->getPointeeType();
1001193326Sed  QualType ToPointeeType = ToTypePtr->getPointeeType();
1002193326Sed
1003193326Sed  // An rvalue of type "pointer to cv T," where T is an object type,
1004193326Sed  // can be converted to an rvalue of type "pointer to cv void" (C++
1005193326Sed  // 4.10p2).
1006193326Sed  if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
1007198092Srdivacky    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1008193326Sed                                                       ToPointeeType,
1009193326Sed                                                       ToType, Context);
1010193326Sed    return true;
1011193326Sed  }
1012193326Sed
1013193326Sed  // When we're overloading in C, we allow a special kind of pointer
1014193326Sed  // conversion for compatible-but-not-identical pointee types.
1015198092Srdivacky  if (!getLangOptions().CPlusPlus &&
1016193326Sed      Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1017198092Srdivacky    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1018193326Sed                                                       ToPointeeType,
1019198092Srdivacky                                                       ToType, Context);
1020193326Sed    return true;
1021193326Sed  }
1022193326Sed
1023193326Sed  // C++ [conv.ptr]p3:
1024198092Srdivacky  //
1025193326Sed  //   An rvalue of type "pointer to cv D," where D is a class type,
1026193326Sed  //   can be converted to an rvalue of type "pointer to cv B," where
1027193326Sed  //   B is a base class (clause 10) of D. If B is an inaccessible
1028193326Sed  //   (clause 11) or ambiguous (10.2) base class of D, a program that
1029193326Sed  //   necessitates this conversion is ill-formed. The result of the
1030193326Sed  //   conversion is a pointer to the base class sub-object of the
1031193326Sed  //   derived class object. The null pointer value is converted to
1032193326Sed  //   the null pointer value of the destination type.
1033193326Sed  //
1034193326Sed  // Note that we do not check for ambiguity or inaccessibility
1035193326Sed  // here. That is handled by CheckPointerConversion.
1036193326Sed  if (getLangOptions().CPlusPlus &&
1037193326Sed      FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1038198893Srdivacky      !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1039193326Sed      IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1040198092Srdivacky    ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1041193326Sed                                                       ToPointeeType,
1042193326Sed                                                       ToType, Context);
1043193326Sed    return true;
1044193326Sed  }
1045193326Sed
1046193326Sed  return false;
1047193326Sed}
1048193326Sed
1049193326Sed/// isObjCPointerConversion - Determines whether this is an
1050193326Sed/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1051193326Sed/// with the same arguments and return values.
1052198092Srdivackybool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1053193326Sed                                   QualType& ConvertedType,
1054193326Sed                                   bool &IncompatibleObjC) {
1055193326Sed  if (!getLangOptions().ObjC1)
1056193326Sed    return false;
1057193326Sed
1058198092Srdivacky  // First, we handle all conversions on ObjC object pointer types.
1059198092Srdivacky  const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
1060198092Srdivacky  const ObjCObjectPointerType *FromObjCPtr =
1061198092Srdivacky    FromType->getAs<ObjCObjectPointerType>();
1062198092Srdivacky
1063198092Srdivacky  if (ToObjCPtr && FromObjCPtr) {
1064198092Srdivacky    // Objective C++: We're able to convert between "id" or "Class" and a
1065198092Srdivacky    // pointer to any interface (in both directions).
1066198092Srdivacky    if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1067198092Srdivacky      ConvertedType = ToType;
1068198092Srdivacky      return true;
1069198092Srdivacky    }
1070198092Srdivacky    // Conversions with Objective-C's id<...>.
1071198092Srdivacky    if ((FromObjCPtr->isObjCQualifiedIdType() ||
1072198092Srdivacky         ToObjCPtr->isObjCQualifiedIdType()) &&
1073198092Srdivacky        Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1074198092Srdivacky                                                  /*compare=*/false)) {
1075198092Srdivacky      ConvertedType = ToType;
1076198092Srdivacky      return true;
1077198092Srdivacky    }
1078198092Srdivacky    // Objective C++: We're able to convert from a pointer to an
1079198092Srdivacky    // interface to a pointer to a different interface.
1080198092Srdivacky    if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1081198092Srdivacky      ConvertedType = ToType;
1082198092Srdivacky      return true;
1083198092Srdivacky    }
1084198092Srdivacky
1085198092Srdivacky    if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1086198092Srdivacky      // Okay: this is some kind of implicit downcast of Objective-C
1087198092Srdivacky      // interfaces, which is permitted. However, we're going to
1088198092Srdivacky      // complain about it.
1089198092Srdivacky      IncompatibleObjC = true;
1090198092Srdivacky      ConvertedType = FromType;
1091198092Srdivacky      return true;
1092198092Srdivacky    }
1093193326Sed  }
1094198092Srdivacky  // Beyond this point, both types need to be C pointers or block pointers.
1095193326Sed  QualType ToPointeeType;
1096198092Srdivacky  if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1097198092Srdivacky    ToPointeeType = ToCPtr->getPointeeType();
1098198092Srdivacky  else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
1099193326Sed    ToPointeeType = ToBlockPtr->getPointeeType();
1100193326Sed  else
1101193326Sed    return false;
1102193326Sed
1103193326Sed  QualType FromPointeeType;
1104198092Srdivacky  if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1105198092Srdivacky    FromPointeeType = FromCPtr->getPointeeType();
1106198092Srdivacky  else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
1107193326Sed    FromPointeeType = FromBlockPtr->getPointeeType();
1108193326Sed  else
1109193326Sed    return false;
1110193326Sed
1111193326Sed  // If we have pointers to pointers, recursively check whether this
1112193326Sed  // is an Objective-C conversion.
1113193326Sed  if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1114193326Sed      isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1115193326Sed                              IncompatibleObjC)) {
1116193326Sed    // We always complain about this conversion.
1117193326Sed    IncompatibleObjC = true;
1118193326Sed    ConvertedType = ToType;
1119193326Sed    return true;
1120193326Sed  }
1121193326Sed  // If we have pointers to functions or blocks, check whether the only
1122193326Sed  // differences in the argument and result types are in Objective-C
1123193326Sed  // pointer conversions. If so, we permit the conversion (but
1124193326Sed  // complain about it).
1125198092Srdivacky  const FunctionProtoType *FromFunctionType
1126198092Srdivacky    = FromPointeeType->getAs<FunctionProtoType>();
1127193326Sed  const FunctionProtoType *ToFunctionType
1128198092Srdivacky    = ToPointeeType->getAs<FunctionProtoType>();
1129193326Sed  if (FromFunctionType && ToFunctionType) {
1130193326Sed    // If the function types are exactly the same, this isn't an
1131193326Sed    // Objective-C pointer conversion.
1132193326Sed    if (Context.getCanonicalType(FromPointeeType)
1133193326Sed          == Context.getCanonicalType(ToPointeeType))
1134193326Sed      return false;
1135193326Sed
1136193326Sed    // Perform the quick checks that will tell us whether these
1137193326Sed    // function types are obviously different.
1138193326Sed    if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1139193326Sed        FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1140193326Sed        FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1141193326Sed      return false;
1142193326Sed
1143193326Sed    bool HasObjCConversion = false;
1144193326Sed    if (Context.getCanonicalType(FromFunctionType->getResultType())
1145193326Sed          == Context.getCanonicalType(ToFunctionType->getResultType())) {
1146193326Sed      // Okay, the types match exactly. Nothing to do.
1147193326Sed    } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1148193326Sed                                       ToFunctionType->getResultType(),
1149193326Sed                                       ConvertedType, IncompatibleObjC)) {
1150193326Sed      // Okay, we have an Objective-C pointer conversion.
1151193326Sed      HasObjCConversion = true;
1152193326Sed    } else {
1153193326Sed      // Function types are too different. Abort.
1154193326Sed      return false;
1155193326Sed    }
1156198092Srdivacky
1157193326Sed    // Check argument types.
1158193326Sed    for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1159193326Sed         ArgIdx != NumArgs; ++ArgIdx) {
1160193326Sed      QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1161193326Sed      QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1162193326Sed      if (Context.getCanonicalType(FromArgType)
1163193326Sed            == Context.getCanonicalType(ToArgType)) {
1164193326Sed        // Okay, the types match exactly. Nothing to do.
1165193326Sed      } else if (isObjCPointerConversion(FromArgType, ToArgType,
1166193326Sed                                         ConvertedType, IncompatibleObjC)) {
1167193326Sed        // Okay, we have an Objective-C pointer conversion.
1168193326Sed        HasObjCConversion = true;
1169193326Sed      } else {
1170193326Sed        // Argument types are too different. Abort.
1171193326Sed        return false;
1172193326Sed      }
1173193326Sed    }
1174193326Sed
1175193326Sed    if (HasObjCConversion) {
1176193326Sed      // We had an Objective-C conversion. Allow this pointer
1177193326Sed      // conversion, but complain about it.
1178193326Sed      ConvertedType = ToType;
1179193326Sed      IncompatibleObjC = true;
1180193326Sed      return true;
1181193326Sed    }
1182193326Sed  }
1183193326Sed
1184193326Sed  return false;
1185193326Sed}
1186193326Sed
1187193326Sed/// CheckPointerConversion - Check the pointer conversion from the
1188193326Sed/// expression From to the type ToType. This routine checks for
1189198092Srdivacky/// ambiguous or inaccessible derived-to-base pointer
1190193326Sed/// conversions for which IsPointerConversion has already returned
1191193326Sed/// true. It returns true and produces a diagnostic if there was an
1192193326Sed/// error, or returns false otherwise.
1193198092Srdivackybool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1194199482Srdivacky                                  CastExpr::CastKind &Kind,
1195199482Srdivacky                                  bool IgnoreBaseAccess) {
1196193326Sed  QualType FromType = From->getType();
1197193326Sed
1198198092Srdivacky  if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1199198092Srdivacky    if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
1200193326Sed      QualType FromPointeeType = FromPtrType->getPointeeType(),
1201193326Sed               ToPointeeType   = ToPtrType->getPointeeType();
1202193326Sed
1203193326Sed      if (FromPointeeType->isRecordType() &&
1204193326Sed          ToPointeeType->isRecordType()) {
1205193326Sed        // We must have a derived-to-base conversion. Check an
1206193326Sed        // ambiguous or inaccessible conversion.
1207198092Srdivacky        if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1208198092Srdivacky                                         From->getExprLoc(),
1209199482Srdivacky                                         From->getSourceRange(),
1210199482Srdivacky                                         IgnoreBaseAccess))
1211198092Srdivacky          return true;
1212198092Srdivacky
1213198092Srdivacky        // The conversion was successful.
1214198092Srdivacky        Kind = CastExpr::CK_DerivedToBase;
1215193326Sed      }
1216193326Sed    }
1217198092Srdivacky  if (const ObjCObjectPointerType *FromPtrType =
1218198092Srdivacky        FromType->getAs<ObjCObjectPointerType>())
1219198092Srdivacky    if (const ObjCObjectPointerType *ToPtrType =
1220198092Srdivacky          ToType->getAs<ObjCObjectPointerType>()) {
1221198092Srdivacky      // Objective-C++ conversions are always okay.
1222198092Srdivacky      // FIXME: We should have a different class of conversions for the
1223198092Srdivacky      // Objective-C++ implicit conversions.
1224198092Srdivacky      if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
1225198092Srdivacky        return false;
1226193326Sed
1227198092Srdivacky  }
1228193326Sed  return false;
1229193326Sed}
1230193326Sed
1231193326Sed/// IsMemberPointerConversion - Determines whether the conversion of the
1232193326Sed/// expression From, which has the (possibly adjusted) type FromType, can be
1233193326Sed/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1234193326Sed/// If so, returns true and places the converted type (that might differ from
1235193326Sed/// ToType in its cv-qualifiers at some level) into ConvertedType.
1236193326Sedbool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
1237198092Srdivacky                                     QualType ToType,
1238198092Srdivacky                                     bool InOverloadResolution,
1239198092Srdivacky                                     QualType &ConvertedType) {
1240198092Srdivacky  const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
1241193326Sed  if (!ToTypePtr)
1242193326Sed    return false;
1243193326Sed
1244193326Sed  // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
1245198092Srdivacky  if (From->isNullPointerConstant(Context,
1246198092Srdivacky                    InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1247198092Srdivacky                                        : Expr::NPC_ValueDependentIsNull)) {
1248193326Sed    ConvertedType = ToType;
1249193326Sed    return true;
1250193326Sed  }
1251193326Sed
1252193326Sed  // Otherwise, both types have to be member pointers.
1253198092Srdivacky  const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
1254193326Sed  if (!FromTypePtr)
1255193326Sed    return false;
1256193326Sed
1257193326Sed  // A pointer to member of B can be converted to a pointer to member of D,
1258193326Sed  // where D is derived from B (C++ 4.11p2).
1259193326Sed  QualType FromClass(FromTypePtr->getClass(), 0);
1260193326Sed  QualType ToClass(ToTypePtr->getClass(), 0);
1261193326Sed  // FIXME: What happens when these are dependent? Is this function even called?
1262193326Sed
1263193326Sed  if (IsDerivedFrom(ToClass, FromClass)) {
1264193326Sed    ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1265193326Sed                                                 ToClass.getTypePtr());
1266193326Sed    return true;
1267193326Sed  }
1268193326Sed
1269193326Sed  return false;
1270193326Sed}
1271200583Srdivacky
1272193326Sed/// CheckMemberPointerConversion - Check the member pointer conversion from the
1273193326Sed/// expression From to the type ToType. This routine checks for ambiguous or
1274193326Sed/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1275193326Sed/// for which IsMemberPointerConversion has already returned true. It returns
1276193326Sed/// true and produces a diagnostic if there was an error, or returns false
1277193326Sed/// otherwise.
1278198092Srdivackybool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
1279199482Srdivacky                                        CastExpr::CastKind &Kind,
1280199482Srdivacky                                        bool IgnoreBaseAccess) {
1281199482Srdivacky  (void)IgnoreBaseAccess;
1282193326Sed  QualType FromType = From->getType();
1283198092Srdivacky  const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
1284198092Srdivacky  if (!FromPtrType) {
1285198092Srdivacky    // This must be a null pointer to member pointer conversion
1286198092Srdivacky    assert(From->isNullPointerConstant(Context,
1287198092Srdivacky                                       Expr::NPC_ValueDependentIsNull) &&
1288198092Srdivacky           "Expr must be null pointer constant!");
1289198092Srdivacky    Kind = CastExpr::CK_NullToMemberPointer;
1290193326Sed    return false;
1291198092Srdivacky  }
1292193326Sed
1293198092Srdivacky  const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
1294193326Sed  assert(ToPtrType && "No member pointer cast has a target type "
1295193326Sed                      "that is not a member pointer.");
1296193326Sed
1297193326Sed  QualType FromClass = QualType(FromPtrType->getClass(), 0);
1298193326Sed  QualType ToClass   = QualType(ToPtrType->getClass(), 0);
1299193326Sed
1300193326Sed  // FIXME: What about dependent types?
1301193326Sed  assert(FromClass->isRecordType() && "Pointer into non-class.");
1302193326Sed  assert(ToClass->isRecordType() && "Pointer into non-class.");
1303193326Sed
1304198092Srdivacky  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1305198092Srdivacky                     /*DetectVirtual=*/true);
1306193326Sed  bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1307193326Sed  assert(DerivationOkay &&
1308193326Sed         "Should not have been called if derivation isn't OK.");
1309193326Sed  (void)DerivationOkay;
1310193326Sed
1311193326Sed  if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1312193326Sed                                  getUnqualifiedType())) {
1313193326Sed    // Derivation is ambiguous. Redo the check to find the exact paths.
1314193326Sed    Paths.clear();
1315193326Sed    Paths.setRecordingPaths(true);
1316193326Sed    bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1317193326Sed    assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1318193326Sed    (void)StillOkay;
1319193326Sed
1320193326Sed    std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1321193326Sed    Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1322193326Sed      << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1323193326Sed    return true;
1324193326Sed  }
1325193326Sed
1326193326Sed  if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1327193326Sed    Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1328193326Sed      << FromClass << ToClass << QualType(VBase, 0)
1329193326Sed      << From->getSourceRange();
1330193326Sed    return true;
1331193326Sed  }
1332193326Sed
1333198092Srdivacky  // Must be a base to derived member conversion.
1334198092Srdivacky  Kind = CastExpr::CK_BaseToDerivedMemberPointer;
1335193326Sed  return false;
1336193326Sed}
1337193326Sed
1338193326Sed/// IsQualificationConversion - Determines whether the conversion from
1339193326Sed/// an rvalue of type FromType to ToType is a qualification conversion
1340193326Sed/// (C++ 4.4).
1341198092Srdivackybool
1342198092SrdivackySema::IsQualificationConversion(QualType FromType, QualType ToType) {
1343193326Sed  FromType = Context.getCanonicalType(FromType);
1344193326Sed  ToType = Context.getCanonicalType(ToType);
1345193326Sed
1346193326Sed  // If FromType and ToType are the same type, this is not a
1347193326Sed  // qualification conversion.
1348193326Sed  if (FromType == ToType)
1349193326Sed    return false;
1350193326Sed
1351193326Sed  // (C++ 4.4p4):
1352193326Sed  //   A conversion can add cv-qualifiers at levels other than the first
1353193326Sed  //   in multi-level pointers, subject to the following rules: [...]
1354193326Sed  bool PreviousToQualsIncludeConst = true;
1355193326Sed  bool UnwrappedAnyPointer = false;
1356193326Sed  while (UnwrapSimilarPointerTypes(FromType, ToType)) {
1357193326Sed    // Within each iteration of the loop, we check the qualifiers to
1358193326Sed    // determine if this still looks like a qualification
1359193326Sed    // conversion. Then, if all is well, we unwrap one more level of
1360193326Sed    // pointers or pointers-to-members and do it all again
1361193326Sed    // until there are no more pointers or pointers-to-members left to
1362193326Sed    // unwrap.
1363193326Sed    UnwrappedAnyPointer = true;
1364193326Sed
1365193326Sed    //   -- for every j > 0, if const is in cv 1,j then const is in cv
1366193326Sed    //      2,j, and similarly for volatile.
1367193326Sed    if (!ToType.isAtLeastAsQualifiedAs(FromType))
1368193326Sed      return false;
1369198092Srdivacky
1370193326Sed    //   -- if the cv 1,j and cv 2,j are different, then const is in
1371193326Sed    //      every cv for 0 < k < j.
1372193326Sed    if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
1373193326Sed        && !PreviousToQualsIncludeConst)
1374193326Sed      return false;
1375198092Srdivacky
1376193326Sed    // Keep track of whether all prior cv-qualifiers in the "to" type
1377193326Sed    // include const.
1378198092Srdivacky    PreviousToQualsIncludeConst
1379193326Sed      = PreviousToQualsIncludeConst && ToType.isConstQualified();
1380193326Sed  }
1381193326Sed
1382193326Sed  // We are left with FromType and ToType being the pointee types
1383193326Sed  // after unwrapping the original FromType and ToType the same number
1384193326Sed  // of types. If we unwrapped any pointers, and if FromType and
1385193326Sed  // ToType have the same unqualified type (since we checked
1386193326Sed  // qualifiers above), then this is a qualification conversion.
1387199482Srdivacky  return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
1388193326Sed}
1389193326Sed
1390193326Sed/// Determines whether there is a user-defined conversion sequence
1391193326Sed/// (C++ [over.ics.user]) that converts expression From to the type
1392193326Sed/// ToType. If such a conversion exists, User will contain the
1393193326Sed/// user-defined conversion sequence that performs such a conversion
1394193326Sed/// and this routine will return true. Otherwise, this routine returns
1395193326Sed/// false and User is unspecified.
1396193326Sed///
1397193326Sed/// \param AllowConversionFunctions true if the conversion should
1398193326Sed/// consider conversion functions at all. If false, only constructors
1399193326Sed/// will be considered.
1400193326Sed///
1401193326Sed/// \param AllowExplicit  true if the conversion should consider C++0x
1402193326Sed/// "explicit" conversion functions as well as non-explicit conversion
1403193326Sed/// functions (C++0x [class.conv.fct]p2).
1404193326Sed///
1405193326Sed/// \param ForceRValue  true if the expression should be treated as an rvalue
1406193326Sed/// for overload resolution.
1407198092Srdivacky/// \param UserCast true if looking for user defined conversion for a static
1408198092Srdivacky/// cast.
1409200583SrdivackyOverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1410200583Srdivacky                                          UserDefinedConversionSequence& User,
1411200583Srdivacky                                            OverloadCandidateSet& CandidateSet,
1412200583Srdivacky                                                bool AllowConversionFunctions,
1413200583Srdivacky                                                bool AllowExplicit,
1414200583Srdivacky                                                bool ForceRValue,
1415200583Srdivacky                                                bool UserCast) {
1416198092Srdivacky  if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
1417198954Srdivacky    if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1418198954Srdivacky      // We're not going to find any constructors.
1419198954Srdivacky    } else if (CXXRecordDecl *ToRecordDecl
1420198954Srdivacky                 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1421193326Sed      // C++ [over.match.ctor]p1:
1422193326Sed      //   When objects of class type are direct-initialized (8.5), or
1423193326Sed      //   copy-initialized from an expression of the same or a
1424193326Sed      //   derived class type (8.5), overload resolution selects the
1425193326Sed      //   constructor. [...] For copy-initialization, the candidate
1426193326Sed      //   functions are all the converting constructors (12.3.1) of
1427193326Sed      //   that class. The argument list is the expression-list within
1428193326Sed      //   the parentheses of the initializer.
1429199482Srdivacky      bool SuppressUserConversions = !UserCast;
1430199482Srdivacky      if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1431199482Srdivacky          IsDerivedFrom(From->getType(), ToType)) {
1432199482Srdivacky        SuppressUserConversions = false;
1433199482Srdivacky        AllowConversionFunctions = false;
1434199482Srdivacky      }
1435199482Srdivacky
1436198092Srdivacky      DeclarationName ConstructorName
1437193326Sed        = Context.DeclarationNames.getCXXConstructorName(
1438193326Sed                          Context.getCanonicalType(ToType).getUnqualifiedType());
1439193326Sed      DeclContext::lookup_iterator Con, ConEnd;
1440198092Srdivacky      for (llvm::tie(Con, ConEnd)
1441195341Sed             = ToRecordDecl->lookup(ConstructorName);
1442193326Sed           Con != ConEnd; ++Con) {
1443198092Srdivacky        // Find the constructor (which may be a template).
1444198092Srdivacky        CXXConstructorDecl *Constructor = 0;
1445198092Srdivacky        FunctionTemplateDecl *ConstructorTmpl
1446198092Srdivacky          = dyn_cast<FunctionTemplateDecl>(*Con);
1447198092Srdivacky        if (ConstructorTmpl)
1448198092Srdivacky          Constructor
1449198092Srdivacky            = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1450198092Srdivacky        else
1451198092Srdivacky          Constructor = cast<CXXConstructorDecl>(*Con);
1452199482Srdivacky
1453198092Srdivacky        if (!Constructor->isInvalidDecl() &&
1454198092Srdivacky            Constructor->isConvertingConstructor(AllowExplicit)) {
1455198092Srdivacky          if (ConstructorTmpl)
1456199990Srdivacky            AddTemplateOverloadCandidate(ConstructorTmpl, /*ExplicitArgs*/ 0,
1457199990Srdivacky                                         &From, 1, CandidateSet,
1458199482Srdivacky                                         SuppressUserConversions, ForceRValue);
1459198092Srdivacky          else
1460198092Srdivacky            // Allow one user-defined conversion when user specifies a
1461198092Srdivacky            // From->ToType conversion via an static cast (c-style, etc).
1462198092Srdivacky            AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
1463199482Srdivacky                                 SuppressUserConversions, ForceRValue);
1464198092Srdivacky        }
1465193326Sed      }
1466193326Sed    }
1467193326Sed  }
1468193326Sed
1469193326Sed  if (!AllowConversionFunctions) {
1470193326Sed    // Don't allow any conversion functions to enter the overload set.
1471198092Srdivacky  } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1472198092Srdivacky                                 PDiag(0)
1473198092Srdivacky                                   << From->getSourceRange())) {
1474198092Srdivacky    // No conversion functions from incomplete types.
1475198092Srdivacky  } else if (const RecordType *FromRecordType
1476198092Srdivacky               = From->getType()->getAs<RecordType>()) {
1477198092Srdivacky    if (CXXRecordDecl *FromRecordDecl
1478198092Srdivacky         = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1479193326Sed      // Add all of the conversion functions as candidates.
1480199990Srdivacky      const UnresolvedSet *Conversions
1481198092Srdivacky        = FromRecordDecl->getVisibleConversionFunctions();
1482199990Srdivacky      for (UnresolvedSet::iterator I = Conversions->begin(),
1483199990Srdivacky             E = Conversions->end(); I != E; ++I) {
1484200583Srdivacky        NamedDecl *D = *I;
1485200583Srdivacky        CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1486200583Srdivacky        if (isa<UsingShadowDecl>(D))
1487200583Srdivacky          D = cast<UsingShadowDecl>(D)->getTargetDecl();
1488200583Srdivacky
1489198092Srdivacky        CXXConversionDecl *Conv;
1490198092Srdivacky        FunctionTemplateDecl *ConvTemplate;
1491199990Srdivacky        if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(*I)))
1492198092Srdivacky          Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1493198092Srdivacky        else
1494199990Srdivacky          Conv = dyn_cast<CXXConversionDecl>(*I);
1495198092Srdivacky
1496198092Srdivacky        if (AllowExplicit || !Conv->isExplicit()) {
1497198092Srdivacky          if (ConvTemplate)
1498200583Srdivacky            AddTemplateConversionCandidate(ConvTemplate, ActingContext,
1499200583Srdivacky                                           From, ToType, CandidateSet);
1500198092Srdivacky          else
1501200583Srdivacky            AddConversionCandidate(Conv, ActingContext, From, ToType,
1502200583Srdivacky                                   CandidateSet);
1503198092Srdivacky        }
1504193326Sed      }
1505193326Sed    }
1506193326Sed  }
1507193326Sed
1508193326Sed  OverloadCandidateSet::iterator Best;
1509194613Sed  switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
1510193326Sed    case OR_Success:
1511193326Sed      // Record the standard conversion we used and the conversion function.
1512198092Srdivacky      if (CXXConstructorDecl *Constructor
1513193326Sed            = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1514193326Sed        // C++ [over.ics.user]p1:
1515193326Sed        //   If the user-defined conversion is specified by a
1516193326Sed        //   constructor (12.3.1), the initial standard conversion
1517193326Sed        //   sequence converts the source type to the type required by
1518193326Sed        //   the argument of the constructor.
1519193326Sed        //
1520193326Sed        QualType ThisType = Constructor->getThisType(Context);
1521199482Srdivacky        if (Best->Conversions[0].ConversionKind ==
1522199482Srdivacky            ImplicitConversionSequence::EllipsisConversion)
1523199482Srdivacky          User.EllipsisConversion = true;
1524199482Srdivacky        else {
1525199482Srdivacky          User.Before = Best->Conversions[0].Standard;
1526199482Srdivacky          User.EllipsisConversion = false;
1527199482Srdivacky        }
1528193326Sed        User.ConversionFunction = Constructor;
1529193326Sed        User.After.setAsIdentityConversion();
1530198092Srdivacky        User.After.FromTypePtr
1531198092Srdivacky          = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
1532193326Sed        User.After.ToTypePtr = ToType.getAsOpaquePtr();
1533198092Srdivacky        return OR_Success;
1534193326Sed      } else if (CXXConversionDecl *Conversion
1535193326Sed                   = dyn_cast<CXXConversionDecl>(Best->Function)) {
1536193326Sed        // C++ [over.ics.user]p1:
1537193326Sed        //
1538193326Sed        //   [...] If the user-defined conversion is specified by a
1539193326Sed        //   conversion function (12.3.2), the initial standard
1540193326Sed        //   conversion sequence converts the source type to the
1541193326Sed        //   implicit object parameter of the conversion function.
1542193326Sed        User.Before = Best->Conversions[0].Standard;
1543193326Sed        User.ConversionFunction = Conversion;
1544199482Srdivacky        User.EllipsisConversion = false;
1545198092Srdivacky
1546198092Srdivacky        // C++ [over.ics.user]p2:
1547193326Sed        //   The second standard conversion sequence converts the
1548193326Sed        //   result of the user-defined conversion to the target type
1549193326Sed        //   for the sequence. Since an implicit conversion sequence
1550193326Sed        //   is an initialization, the special rules for
1551193326Sed        //   initialization by user-defined conversion apply when
1552193326Sed        //   selecting the best user-defined conversion for a
1553193326Sed        //   user-defined conversion sequence (see 13.3.3 and
1554193326Sed        //   13.3.3.1).
1555193326Sed        User.After = Best->FinalConversion;
1556198092Srdivacky        return OR_Success;
1557193326Sed      } else {
1558193326Sed        assert(false && "Not a constructor or conversion function?");
1559198092Srdivacky        return OR_No_Viable_Function;
1560193326Sed      }
1561198092Srdivacky
1562193326Sed    case OR_No_Viable_Function:
1563198092Srdivacky      return OR_No_Viable_Function;
1564193326Sed    case OR_Deleted:
1565193326Sed      // No conversion here! We're done.
1566198092Srdivacky      return OR_Deleted;
1567193326Sed
1568193326Sed    case OR_Ambiguous:
1569198092Srdivacky      return OR_Ambiguous;
1570193326Sed    }
1571193326Sed
1572198092Srdivacky  return OR_No_Viable_Function;
1573193326Sed}
1574198092Srdivacky
1575198092Srdivackybool
1576199512SrdivackySema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
1577198092Srdivacky  ImplicitConversionSequence ICS;
1578198092Srdivacky  OverloadCandidateSet CandidateSet;
1579198092Srdivacky  OverloadingResult OvResult =
1580198092Srdivacky    IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1581198092Srdivacky                            CandidateSet, true, false, false);
1582199512Srdivacky  if (OvResult == OR_Ambiguous)
1583199512Srdivacky    Diag(From->getSourceRange().getBegin(),
1584199512Srdivacky         diag::err_typecheck_ambiguous_condition)
1585199512Srdivacky          << From->getType() << ToType << From->getSourceRange();
1586199512Srdivacky  else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1587199512Srdivacky    Diag(From->getSourceRange().getBegin(),
1588199512Srdivacky         diag::err_typecheck_nonviable_condition)
1589199512Srdivacky    << From->getType() << ToType << From->getSourceRange();
1590199512Srdivacky  else
1591198092Srdivacky    return false;
1592199512Srdivacky  PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1593198092Srdivacky  return true;
1594198092Srdivacky}
1595193326Sed
1596193326Sed/// CompareImplicitConversionSequences - Compare two implicit
1597193326Sed/// conversion sequences to determine whether one is better than the
1598193326Sed/// other or if they are indistinguishable (C++ 13.3.3.2).
1599198092SrdivackyImplicitConversionSequence::CompareKind
1600193326SedSema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1601193326Sed                                         const ImplicitConversionSequence& ICS2)
1602193326Sed{
1603193326Sed  // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1604193326Sed  // conversion sequences (as defined in 13.3.3.1)
1605193326Sed  //   -- a standard conversion sequence (13.3.3.1.1) is a better
1606193326Sed  //      conversion sequence than a user-defined conversion sequence or
1607193326Sed  //      an ellipsis conversion sequence, and
1608193326Sed  //   -- a user-defined conversion sequence (13.3.3.1.2) is a better
1609193326Sed  //      conversion sequence than an ellipsis conversion sequence
1610193326Sed  //      (13.3.3.1.3).
1611198092Srdivacky  //
1612193326Sed  if (ICS1.ConversionKind < ICS2.ConversionKind)
1613193326Sed    return ImplicitConversionSequence::Better;
1614193326Sed  else if (ICS2.ConversionKind < ICS1.ConversionKind)
1615193326Sed    return ImplicitConversionSequence::Worse;
1616193326Sed
1617193326Sed  // Two implicit conversion sequences of the same form are
1618193326Sed  // indistinguishable conversion sequences unless one of the
1619193326Sed  // following rules apply: (C++ 13.3.3.2p3):
1620193326Sed  if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1621193326Sed    return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
1622198092Srdivacky  else if (ICS1.ConversionKind ==
1623193326Sed             ImplicitConversionSequence::UserDefinedConversion) {
1624193326Sed    // User-defined conversion sequence U1 is a better conversion
1625193326Sed    // sequence than another user-defined conversion sequence U2 if
1626193326Sed    // they contain the same user-defined conversion function or
1627193326Sed    // constructor and if the second standard conversion sequence of
1628193326Sed    // U1 is better than the second standard conversion sequence of
1629193326Sed    // U2 (C++ 13.3.3.2p3).
1630198092Srdivacky    if (ICS1.UserDefined.ConversionFunction ==
1631193326Sed          ICS2.UserDefined.ConversionFunction)
1632193326Sed      return CompareStandardConversionSequences(ICS1.UserDefined.After,
1633193326Sed                                                ICS2.UserDefined.After);
1634193326Sed  }
1635193326Sed
1636193326Sed  return ImplicitConversionSequence::Indistinguishable;
1637193326Sed}
1638193326Sed
1639193326Sed/// CompareStandardConversionSequences - Compare two standard
1640193326Sed/// conversion sequences to determine whether one is better than the
1641193326Sed/// other or if they are indistinguishable (C++ 13.3.3.2p3).
1642198092SrdivackyImplicitConversionSequence::CompareKind
1643193326SedSema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1644193326Sed                                         const StandardConversionSequence& SCS2)
1645193326Sed{
1646193326Sed  // Standard conversion sequence S1 is a better conversion sequence
1647193326Sed  // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1648193326Sed
1649193326Sed  //  -- S1 is a proper subsequence of S2 (comparing the conversion
1650193326Sed  //     sequences in the canonical form defined by 13.3.3.1.1,
1651193326Sed  //     excluding any Lvalue Transformation; the identity conversion
1652193326Sed  //     sequence is considered to be a subsequence of any
1653193326Sed  //     non-identity conversion sequence) or, if not that,
1654193326Sed  if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1655193326Sed    // Neither is a proper subsequence of the other. Do nothing.
1656193326Sed    ;
1657193326Sed  else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1658193326Sed           (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
1659198092Srdivacky           (SCS1.Second == ICK_Identity &&
1660193326Sed            SCS1.Third == ICK_Identity))
1661193326Sed    // SCS1 is a proper subsequence of SCS2.
1662193326Sed    return ImplicitConversionSequence::Better;
1663193326Sed  else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1664193326Sed           (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
1665198092Srdivacky           (SCS2.Second == ICK_Identity &&
1666193326Sed            SCS2.Third == ICK_Identity))
1667193326Sed    // SCS2 is a proper subsequence of SCS1.
1668193326Sed    return ImplicitConversionSequence::Worse;
1669193326Sed
1670193326Sed  //  -- the rank of S1 is better than the rank of S2 (by the rules
1671193326Sed  //     defined below), or, if not that,
1672193326Sed  ImplicitConversionRank Rank1 = SCS1.getRank();
1673193326Sed  ImplicitConversionRank Rank2 = SCS2.getRank();
1674193326Sed  if (Rank1 < Rank2)
1675193326Sed    return ImplicitConversionSequence::Better;
1676193326Sed  else if (Rank2 < Rank1)
1677193326Sed    return ImplicitConversionSequence::Worse;
1678193326Sed
1679193326Sed  // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1680193326Sed  // are indistinguishable unless one of the following rules
1681193326Sed  // applies:
1682198092Srdivacky
1683193326Sed  //   A conversion that is not a conversion of a pointer, or
1684193326Sed  //   pointer to member, to bool is better than another conversion
1685193326Sed  //   that is such a conversion.
1686193326Sed  if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1687193326Sed    return SCS2.isPointerConversionToBool()
1688193326Sed             ? ImplicitConversionSequence::Better
1689193326Sed             : ImplicitConversionSequence::Worse;
1690193326Sed
1691193326Sed  // C++ [over.ics.rank]p4b2:
1692193326Sed  //
1693193326Sed  //   If class B is derived directly or indirectly from class A,
1694193326Sed  //   conversion of B* to A* is better than conversion of B* to
1695193326Sed  //   void*, and conversion of A* to void* is better than conversion
1696193326Sed  //   of B* to void*.
1697198092Srdivacky  bool SCS1ConvertsToVoid
1698193326Sed    = SCS1.isPointerConversionToVoidPointer(Context);
1699198092Srdivacky  bool SCS2ConvertsToVoid
1700193326Sed    = SCS2.isPointerConversionToVoidPointer(Context);
1701193326Sed  if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1702193326Sed    // Exactly one of the conversion sequences is a conversion to
1703193326Sed    // a void pointer; it's the worse conversion.
1704193326Sed    return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1705193326Sed                              : ImplicitConversionSequence::Worse;
1706193326Sed  } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1707193326Sed    // Neither conversion sequence converts to a void pointer; compare
1708193326Sed    // their derived-to-base conversions.
1709193326Sed    if (ImplicitConversionSequence::CompareKind DerivedCK
1710193326Sed          = CompareDerivedToBaseConversions(SCS1, SCS2))
1711193326Sed      return DerivedCK;
1712193326Sed  } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1713193326Sed    // Both conversion sequences are conversions to void
1714193326Sed    // pointers. Compare the source types to determine if there's an
1715193326Sed    // inheritance relationship in their sources.
1716193326Sed    QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1717193326Sed    QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1718193326Sed
1719193326Sed    // Adjust the types we're converting from via the array-to-pointer
1720193326Sed    // conversion, if we need to.
1721193326Sed    if (SCS1.First == ICK_Array_To_Pointer)
1722193326Sed      FromType1 = Context.getArrayDecayedType(FromType1);
1723193326Sed    if (SCS2.First == ICK_Array_To_Pointer)
1724193326Sed      FromType2 = Context.getArrayDecayedType(FromType2);
1725193326Sed
1726198092Srdivacky    QualType FromPointee1
1727198092Srdivacky      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1728193326Sed    QualType FromPointee2
1729198092Srdivacky      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1730193326Sed
1731193326Sed    if (IsDerivedFrom(FromPointee2, FromPointee1))
1732193326Sed      return ImplicitConversionSequence::Better;
1733193326Sed    else if (IsDerivedFrom(FromPointee1, FromPointee2))
1734193326Sed      return ImplicitConversionSequence::Worse;
1735193326Sed
1736193326Sed    // Objective-C++: If one interface is more specific than the
1737193326Sed    // other, it is the better one.
1738198092Srdivacky    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1739198092Srdivacky    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1740193326Sed    if (FromIface1 && FromIface1) {
1741193326Sed      if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1742193326Sed        return ImplicitConversionSequence::Better;
1743193326Sed      else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1744193326Sed        return ImplicitConversionSequence::Worse;
1745193326Sed    }
1746193326Sed  }
1747193326Sed
1748193326Sed  // Compare based on qualification conversions (C++ 13.3.3.2p3,
1749193326Sed  // bullet 3).
1750198092Srdivacky  if (ImplicitConversionSequence::CompareKind QualCK
1751193326Sed        = CompareQualificationConversions(SCS1, SCS2))
1752193326Sed    return QualCK;
1753193326Sed
1754193326Sed  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
1755193326Sed    // C++0x [over.ics.rank]p3b4:
1756193326Sed    //   -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1757193326Sed    //      implicit object parameter of a non-static member function declared
1758193326Sed    //      without a ref-qualifier, and S1 binds an rvalue reference to an
1759193326Sed    //      rvalue and S2 binds an lvalue reference.
1760193326Sed    // FIXME: We don't know if we're dealing with the implicit object parameter,
1761193326Sed    // or if the member function in this case has a ref qualifier.
1762193326Sed    // (Of course, we don't have ref qualifiers yet.)
1763193326Sed    if (SCS1.RRefBinding != SCS2.RRefBinding)
1764193326Sed      return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1765193326Sed                              : ImplicitConversionSequence::Worse;
1766193326Sed
1767193326Sed    // C++ [over.ics.rank]p3b4:
1768193326Sed    //   -- S1 and S2 are reference bindings (8.5.3), and the types to
1769193326Sed    //      which the references refer are the same type except for
1770193326Sed    //      top-level cv-qualifiers, and the type to which the reference
1771193326Sed    //      initialized by S2 refers is more cv-qualified than the type
1772193326Sed    //      to which the reference initialized by S1 refers.
1773193326Sed    QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1774193326Sed    QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1775193326Sed    T1 = Context.getCanonicalType(T1);
1776193326Sed    T2 = Context.getCanonicalType(T2);
1777199482Srdivacky    if (Context.hasSameUnqualifiedType(T1, T2)) {
1778193326Sed      if (T2.isMoreQualifiedThan(T1))
1779193326Sed        return ImplicitConversionSequence::Better;
1780193326Sed      else if (T1.isMoreQualifiedThan(T2))
1781193326Sed        return ImplicitConversionSequence::Worse;
1782193326Sed    }
1783193326Sed  }
1784193326Sed
1785193326Sed  return ImplicitConversionSequence::Indistinguishable;
1786193326Sed}
1787193326Sed
1788193326Sed/// CompareQualificationConversions - Compares two standard conversion
1789193326Sed/// sequences to determine whether they can be ranked based on their
1790198092Srdivacky/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1791198092SrdivackyImplicitConversionSequence::CompareKind
1792193326SedSema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
1793198092Srdivacky                                      const StandardConversionSequence& SCS2) {
1794193326Sed  // C++ 13.3.3.2p3:
1795193326Sed  //  -- S1 and S2 differ only in their qualification conversion and
1796193326Sed  //     yield similar types T1 and T2 (C++ 4.4), respectively, and the
1797193326Sed  //     cv-qualification signature of type T1 is a proper subset of
1798193326Sed  //     the cv-qualification signature of type T2, and S1 is not the
1799193326Sed  //     deprecated string literal array-to-pointer conversion (4.2).
1800193326Sed  if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1801193326Sed      SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1802193326Sed    return ImplicitConversionSequence::Indistinguishable;
1803193326Sed
1804193326Sed  // FIXME: the example in the standard doesn't use a qualification
1805193326Sed  // conversion (!)
1806193326Sed  QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1807193326Sed  QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1808193326Sed  T1 = Context.getCanonicalType(T1);
1809193326Sed  T2 = Context.getCanonicalType(T2);
1810193326Sed
1811193326Sed  // If the types are the same, we won't learn anything by unwrapped
1812193326Sed  // them.
1813199482Srdivacky  if (Context.hasSameUnqualifiedType(T1, T2))
1814193326Sed    return ImplicitConversionSequence::Indistinguishable;
1815193326Sed
1816198092Srdivacky  ImplicitConversionSequence::CompareKind Result
1817193326Sed    = ImplicitConversionSequence::Indistinguishable;
1818193326Sed  while (UnwrapSimilarPointerTypes(T1, T2)) {
1819193326Sed    // Within each iteration of the loop, we check the qualifiers to
1820193326Sed    // determine if this still looks like a qualification
1821193326Sed    // conversion. Then, if all is well, we unwrap one more level of
1822193326Sed    // pointers or pointers-to-members and do it all again
1823193326Sed    // until there are no more pointers or pointers-to-members left
1824193326Sed    // to unwrap. This essentially mimics what
1825193326Sed    // IsQualificationConversion does, but here we're checking for a
1826193326Sed    // strict subset of qualifiers.
1827193326Sed    if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1828193326Sed      // The qualifiers are the same, so this doesn't tell us anything
1829193326Sed      // about how the sequences rank.
1830193326Sed      ;
1831193326Sed    else if (T2.isMoreQualifiedThan(T1)) {
1832193326Sed      // T1 has fewer qualifiers, so it could be the better sequence.
1833193326Sed      if (Result == ImplicitConversionSequence::Worse)
1834193326Sed        // Neither has qualifiers that are a subset of the other's
1835193326Sed        // qualifiers.
1836193326Sed        return ImplicitConversionSequence::Indistinguishable;
1837198092Srdivacky
1838193326Sed      Result = ImplicitConversionSequence::Better;
1839193326Sed    } else if (T1.isMoreQualifiedThan(T2)) {
1840193326Sed      // T2 has fewer qualifiers, so it could be the better sequence.
1841193326Sed      if (Result == ImplicitConversionSequence::Better)
1842193326Sed        // Neither has qualifiers that are a subset of the other's
1843193326Sed        // qualifiers.
1844193326Sed        return ImplicitConversionSequence::Indistinguishable;
1845198092Srdivacky
1846193326Sed      Result = ImplicitConversionSequence::Worse;
1847193326Sed    } else {
1848193326Sed      // Qualifiers are disjoint.
1849193326Sed      return ImplicitConversionSequence::Indistinguishable;
1850193326Sed    }
1851193326Sed
1852193326Sed    // If the types after this point are equivalent, we're done.
1853199482Srdivacky    if (Context.hasSameUnqualifiedType(T1, T2))
1854193326Sed      break;
1855193326Sed  }
1856193326Sed
1857193326Sed  // Check that the winning standard conversion sequence isn't using
1858193326Sed  // the deprecated string literal array to pointer conversion.
1859193326Sed  switch (Result) {
1860193326Sed  case ImplicitConversionSequence::Better:
1861193326Sed    if (SCS1.Deprecated)
1862193326Sed      Result = ImplicitConversionSequence::Indistinguishable;
1863193326Sed    break;
1864193326Sed
1865193326Sed  case ImplicitConversionSequence::Indistinguishable:
1866193326Sed    break;
1867193326Sed
1868193326Sed  case ImplicitConversionSequence::Worse:
1869193326Sed    if (SCS2.Deprecated)
1870193326Sed      Result = ImplicitConversionSequence::Indistinguishable;
1871193326Sed    break;
1872193326Sed  }
1873193326Sed
1874193326Sed  return Result;
1875193326Sed}
1876193326Sed
1877193326Sed/// CompareDerivedToBaseConversions - Compares two standard conversion
1878193326Sed/// sequences to determine whether they can be ranked based on their
1879193326Sed/// various kinds of derived-to-base conversions (C++
1880193326Sed/// [over.ics.rank]p4b3).  As part of these checks, we also look at
1881193326Sed/// conversions between Objective-C interface types.
1882193326SedImplicitConversionSequence::CompareKind
1883193326SedSema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1884193326Sed                                      const StandardConversionSequence& SCS2) {
1885193326Sed  QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1886193326Sed  QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1887193326Sed  QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1888193326Sed  QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1889193326Sed
1890193326Sed  // Adjust the types we're converting from via the array-to-pointer
1891193326Sed  // conversion, if we need to.
1892193326Sed  if (SCS1.First == ICK_Array_To_Pointer)
1893193326Sed    FromType1 = Context.getArrayDecayedType(FromType1);
1894193326Sed  if (SCS2.First == ICK_Array_To_Pointer)
1895193326Sed    FromType2 = Context.getArrayDecayedType(FromType2);
1896193326Sed
1897193326Sed  // Canonicalize all of the types.
1898193326Sed  FromType1 = Context.getCanonicalType(FromType1);
1899193326Sed  ToType1 = Context.getCanonicalType(ToType1);
1900193326Sed  FromType2 = Context.getCanonicalType(FromType2);
1901193326Sed  ToType2 = Context.getCanonicalType(ToType2);
1902193326Sed
1903193326Sed  // C++ [over.ics.rank]p4b3:
1904193326Sed  //
1905193326Sed  //   If class B is derived directly or indirectly from class A and
1906193326Sed  //   class C is derived directly or indirectly from B,
1907193326Sed  //
1908193326Sed  // For Objective-C, we let A, B, and C also be Objective-C
1909193326Sed  // interfaces.
1910193326Sed
1911193326Sed  // Compare based on pointer conversions.
1912198092Srdivacky  if (SCS1.Second == ICK_Pointer_Conversion &&
1913193326Sed      SCS2.Second == ICK_Pointer_Conversion &&
1914193326Sed      /*FIXME: Remove if Objective-C id conversions get their own rank*/
1915193326Sed      FromType1->isPointerType() && FromType2->isPointerType() &&
1916193326Sed      ToType1->isPointerType() && ToType2->isPointerType()) {
1917198092Srdivacky    QualType FromPointee1
1918198092Srdivacky      = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1919198092Srdivacky    QualType ToPointee1
1920198092Srdivacky      = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1921193326Sed    QualType FromPointee2
1922198092Srdivacky      = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1923193326Sed    QualType ToPointee2
1924198092Srdivacky      = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
1925193326Sed
1926198092Srdivacky    const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1927198092Srdivacky    const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1928198092Srdivacky    const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1929198092Srdivacky    const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
1930193326Sed
1931193326Sed    //   -- conversion of C* to B* is better than conversion of C* to A*,
1932193326Sed    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1933193326Sed      if (IsDerivedFrom(ToPointee1, ToPointee2))
1934193326Sed        return ImplicitConversionSequence::Better;
1935193326Sed      else if (IsDerivedFrom(ToPointee2, ToPointee1))
1936193326Sed        return ImplicitConversionSequence::Worse;
1937193326Sed
1938193326Sed      if (ToIface1 && ToIface2) {
1939193326Sed        if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1940193326Sed          return ImplicitConversionSequence::Better;
1941193326Sed        else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1942193326Sed          return ImplicitConversionSequence::Worse;
1943193326Sed      }
1944193326Sed    }
1945193326Sed
1946193326Sed    //   -- conversion of B* to A* is better than conversion of C* to A*,
1947193326Sed    if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1948193326Sed      if (IsDerivedFrom(FromPointee2, FromPointee1))
1949193326Sed        return ImplicitConversionSequence::Better;
1950193326Sed      else if (IsDerivedFrom(FromPointee1, FromPointee2))
1951193326Sed        return ImplicitConversionSequence::Worse;
1952198092Srdivacky
1953193326Sed      if (FromIface1 && FromIface2) {
1954193326Sed        if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1955193326Sed          return ImplicitConversionSequence::Better;
1956193326Sed        else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1957193326Sed          return ImplicitConversionSequence::Worse;
1958193326Sed      }
1959193326Sed    }
1960193326Sed  }
1961193326Sed
1962193326Sed  // Compare based on reference bindings.
1963193326Sed  if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1964193326Sed      SCS1.Second == ICK_Derived_To_Base) {
1965193326Sed    //   -- binding of an expression of type C to a reference of type
1966193326Sed    //      B& is better than binding an expression of type C to a
1967193326Sed    //      reference of type A&,
1968199482Srdivacky    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1969199482Srdivacky        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
1970193326Sed      if (IsDerivedFrom(ToType1, ToType2))
1971193326Sed        return ImplicitConversionSequence::Better;
1972193326Sed      else if (IsDerivedFrom(ToType2, ToType1))
1973193326Sed        return ImplicitConversionSequence::Worse;
1974193326Sed    }
1975193326Sed
1976193326Sed    //   -- binding of an expression of type B to a reference of type
1977193326Sed    //      A& is better than binding an expression of type C to a
1978193326Sed    //      reference of type A&,
1979199482Srdivacky    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
1980199482Srdivacky        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
1981193326Sed      if (IsDerivedFrom(FromType2, FromType1))
1982193326Sed        return ImplicitConversionSequence::Better;
1983193326Sed      else if (IsDerivedFrom(FromType1, FromType2))
1984193326Sed        return ImplicitConversionSequence::Worse;
1985193326Sed    }
1986193326Sed  }
1987198398Srdivacky
1988198398Srdivacky  // Ranking of member-pointer types.
1989198398Srdivacky  if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1990198398Srdivacky      FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1991198398Srdivacky      ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1992198398Srdivacky    const MemberPointerType * FromMemPointer1 =
1993198398Srdivacky                                        FromType1->getAs<MemberPointerType>();
1994198398Srdivacky    const MemberPointerType * ToMemPointer1 =
1995198398Srdivacky                                          ToType1->getAs<MemberPointerType>();
1996198398Srdivacky    const MemberPointerType * FromMemPointer2 =
1997198398Srdivacky                                          FromType2->getAs<MemberPointerType>();
1998198398Srdivacky    const MemberPointerType * ToMemPointer2 =
1999198398Srdivacky                                          ToType2->getAs<MemberPointerType>();
2000198398Srdivacky    const Type *FromPointeeType1 = FromMemPointer1->getClass();
2001198398Srdivacky    const Type *ToPointeeType1 = ToMemPointer1->getClass();
2002198398Srdivacky    const Type *FromPointeeType2 = FromMemPointer2->getClass();
2003198398Srdivacky    const Type *ToPointeeType2 = ToMemPointer2->getClass();
2004198398Srdivacky    QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2005198398Srdivacky    QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2006198398Srdivacky    QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2007198398Srdivacky    QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
2008198398Srdivacky    // conversion of A::* to B::* is better than conversion of A::* to C::*,
2009198398Srdivacky    if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2010198398Srdivacky      if (IsDerivedFrom(ToPointee1, ToPointee2))
2011198398Srdivacky        return ImplicitConversionSequence::Worse;
2012198398Srdivacky      else if (IsDerivedFrom(ToPointee2, ToPointee1))
2013198398Srdivacky        return ImplicitConversionSequence::Better;
2014198398Srdivacky    }
2015198398Srdivacky    // conversion of B::* to C::* is better than conversion of A::* to C::*
2016198398Srdivacky    if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2017198398Srdivacky      if (IsDerivedFrom(FromPointee1, FromPointee2))
2018198398Srdivacky        return ImplicitConversionSequence::Better;
2019198398Srdivacky      else if (IsDerivedFrom(FromPointee2, FromPointee1))
2020198398Srdivacky        return ImplicitConversionSequence::Worse;
2021198398Srdivacky    }
2022198398Srdivacky  }
2023198398Srdivacky
2024193326Sed  if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
2025193326Sed      SCS1.Second == ICK_Derived_To_Base) {
2026193326Sed    //   -- conversion of C to B is better than conversion of C to A,
2027199482Srdivacky    if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2028199482Srdivacky        !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2029193326Sed      if (IsDerivedFrom(ToType1, ToType2))
2030193326Sed        return ImplicitConversionSequence::Better;
2031193326Sed      else if (IsDerivedFrom(ToType2, ToType1))
2032193326Sed        return ImplicitConversionSequence::Worse;
2033193326Sed    }
2034193326Sed
2035193326Sed    //   -- conversion of B to A is better than conversion of C to A.
2036199482Srdivacky    if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2037199482Srdivacky        Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2038193326Sed      if (IsDerivedFrom(FromType2, FromType1))
2039193326Sed        return ImplicitConversionSequence::Better;
2040193326Sed      else if (IsDerivedFrom(FromType1, FromType2))
2041193326Sed        return ImplicitConversionSequence::Worse;
2042193326Sed    }
2043193326Sed  }
2044193326Sed
2045193326Sed  return ImplicitConversionSequence::Indistinguishable;
2046193326Sed}
2047193326Sed
2048193326Sed/// TryCopyInitialization - Try to copy-initialize a value of type
2049193326Sed/// ToType from the expression From. Return the implicit conversion
2050193326Sed/// sequence required to pass this argument, which may be a bad
2051193326Sed/// conversion sequence (meaning that the argument cannot be passed to
2052193326Sed/// a parameter of this type). If @p SuppressUserConversions, then we
2053193326Sed/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2054193326Sed/// then we treat @p From as an rvalue, even if it is an lvalue.
2055198092SrdivackyImplicitConversionSequence
2056198092SrdivackySema::TryCopyInitialization(Expr *From, QualType ToType,
2057198092Srdivacky                            bool SuppressUserConversions, bool ForceRValue,
2058198092Srdivacky                            bool InOverloadResolution) {
2059193326Sed  if (ToType->isReferenceType()) {
2060193326Sed    ImplicitConversionSequence ICS;
2061198092Srdivacky    CheckReferenceInit(From, ToType,
2062198092Srdivacky                       /*FIXME:*/From->getLocStart(),
2063198092Srdivacky                       SuppressUserConversions,
2064198092Srdivacky                       /*AllowExplicit=*/false,
2065198092Srdivacky                       ForceRValue,
2066198092Srdivacky                       &ICS);
2067193326Sed    return ICS;
2068193326Sed  } else {
2069198092Srdivacky    return TryImplicitConversion(From, ToType,
2070198092Srdivacky                                 SuppressUserConversions,
2071198092Srdivacky                                 /*AllowExplicit=*/false,
2072198092Srdivacky                                 ForceRValue,
2073198092Srdivacky                                 InOverloadResolution);
2074193326Sed  }
2075193326Sed}
2076193326Sed
2077193326Sed/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2078193326Sed/// the expression @p From. Returns true (and emits a diagnostic) if there was
2079193326Sed/// an error, returns false if the initialization succeeded. Elidable should
2080193326Sed/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2081193326Sed/// differently in C++0x for this case.
2082198092Srdivackybool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
2083193326Sed                                     const char* Flavor, bool Elidable) {
2084193326Sed  if (!getLangOptions().CPlusPlus) {
2085193326Sed    // In C, argument passing is the same as performing an assignment.
2086193326Sed    QualType FromType = From->getType();
2087198092Srdivacky
2088193326Sed    AssignConvertType ConvTy =
2089193326Sed      CheckSingleAssignmentConstraints(ToType, From);
2090193326Sed    if (ConvTy != Compatible &&
2091193326Sed        CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2092193326Sed      ConvTy = Compatible;
2093198092Srdivacky
2094193326Sed    return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2095193326Sed                                    FromType, From, Flavor);
2096193326Sed  }
2097193326Sed
2098193326Sed  if (ToType->isReferenceType())
2099198092Srdivacky    return CheckReferenceInit(From, ToType,
2100198092Srdivacky                              /*FIXME:*/From->getLocStart(),
2101198092Srdivacky                              /*SuppressUserConversions=*/false,
2102198092Srdivacky                              /*AllowExplicit=*/false,
2103198092Srdivacky                              /*ForceRValue=*/false);
2104193326Sed
2105193326Sed  if (!PerformImplicitConversion(From, ToType, Flavor,
2106193326Sed                                 /*AllowExplicit=*/false, Elidable))
2107193326Sed    return false;
2108199512Srdivacky  if (!DiagnoseMultipleUserDefinedConversion(From, ToType))
2109198092Srdivacky    return Diag(From->getSourceRange().getBegin(),
2110198092Srdivacky                diag::err_typecheck_convert_incompatible)
2111198092Srdivacky      << ToType << From->getType() << Flavor << From->getSourceRange();
2112198092Srdivacky  return true;
2113193326Sed}
2114193326Sed
2115193326Sed/// TryObjectArgumentInitialization - Try to initialize the object
2116193326Sed/// parameter of the given member function (@c Method) from the
2117193326Sed/// expression @p From.
2118193326SedImplicitConversionSequence
2119200583SrdivackySema::TryObjectArgumentInitialization(QualType FromType,
2120200583Srdivacky                                      CXXMethodDecl *Method,
2121200583Srdivacky                                      CXXRecordDecl *ActingContext) {
2122200583Srdivacky  QualType ClassType = Context.getTypeDeclType(ActingContext);
2123199512Srdivacky  // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2124199512Srdivacky  //                 const volatile object.
2125199512Srdivacky  unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2126199512Srdivacky    Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2127199512Srdivacky  QualType ImplicitParamType =  Context.getCVRQualifiedType(ClassType, Quals);
2128193326Sed
2129193326Sed  // Set up the conversion sequence as a "bad" conversion, to allow us
2130193326Sed  // to exit early.
2131193326Sed  ImplicitConversionSequence ICS;
2132193326Sed  ICS.Standard.setAsIdentityConversion();
2133193326Sed  ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2134193326Sed
2135193326Sed  // We need to have an object of class type.
2136198092Srdivacky  if (const PointerType *PT = FromType->getAs<PointerType>())
2137193326Sed    FromType = PT->getPointeeType();
2138193326Sed
2139193326Sed  assert(FromType->isRecordType());
2140193326Sed
2141199512Srdivacky  // The implicit object parameter is has the type "reference to cv X",
2142193326Sed  // where X is the class of which the function is a member
2143193326Sed  // (C++ [over.match.funcs]p4). However, when finding an implicit
2144193326Sed  // conversion sequence for the argument, we are not allowed to
2145198092Srdivacky  // create temporaries or perform user-defined conversions
2146193326Sed  // (C++ [over.match.funcs]p5). We perform a simplified version of
2147193326Sed  // reference binding here, that allows class rvalues to bind to
2148193326Sed  // non-constant references.
2149193326Sed
2150193326Sed  // First check the qualifiers. We don't care about lvalue-vs-rvalue
2151193326Sed  // with the implicit object parameter (C++ [over.match.funcs]p5).
2152193326Sed  QualType FromTypeCanon = Context.getCanonicalType(FromType);
2153199482Srdivacky  if (ImplicitParamType.getCVRQualifiers()
2154199482Srdivacky                                    != FromTypeCanon.getLocalCVRQualifiers() &&
2155198954Srdivacky      !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
2156193326Sed    return ICS;
2157193326Sed
2158193326Sed  // Check that we have either the same type or a derived type. It
2159193326Sed  // affects the conversion rank.
2160193326Sed  QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2161199482Srdivacky  if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType())
2162193326Sed    ICS.Standard.Second = ICK_Identity;
2163193326Sed  else if (IsDerivedFrom(FromType, ClassType))
2164193326Sed    ICS.Standard.Second = ICK_Derived_To_Base;
2165193326Sed  else
2166193326Sed    return ICS;
2167193326Sed
2168193326Sed  // Success. Mark this as a reference binding.
2169193326Sed  ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2170193326Sed  ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2171193326Sed  ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2172193326Sed  ICS.Standard.ReferenceBinding = true;
2173193326Sed  ICS.Standard.DirectBinding = true;
2174193326Sed  ICS.Standard.RRefBinding = false;
2175193326Sed  return ICS;
2176193326Sed}
2177193326Sed
2178193326Sed/// PerformObjectArgumentInitialization - Perform initialization of
2179193326Sed/// the implicit object parameter for the given Method with the given
2180193326Sed/// expression.
2181193326Sedbool
2182193326SedSema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
2183193326Sed  QualType FromRecordType, DestType;
2184198092Srdivacky  QualType ImplicitParamRecordType  =
2185198092Srdivacky    Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
2186198092Srdivacky
2187198092Srdivacky  if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
2188193326Sed    FromRecordType = PT->getPointeeType();
2189193326Sed    DestType = Method->getThisType(Context);
2190193326Sed  } else {
2191193326Sed    FromRecordType = From->getType();
2192193326Sed    DestType = ImplicitParamRecordType;
2193193326Sed  }
2194193326Sed
2195200583Srdivacky  // Note that we always use the true parent context when performing
2196200583Srdivacky  // the actual argument initialization.
2197198092Srdivacky  ImplicitConversionSequence ICS
2198200583Srdivacky    = TryObjectArgumentInitialization(From->getType(), Method,
2199200583Srdivacky                                      Method->getParent());
2200193326Sed  if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2201193326Sed    return Diag(From->getSourceRange().getBegin(),
2202193326Sed                diag::err_implicit_object_parameter_init)
2203193326Sed       << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
2204198092Srdivacky
2205193326Sed  if (ICS.Standard.Second == ICK_Derived_To_Base &&
2206193326Sed      CheckDerivedToBaseConversion(FromRecordType,
2207193326Sed                                   ImplicitParamRecordType,
2208193326Sed                                   From->getSourceRange().getBegin(),
2209193326Sed                                   From->getSourceRange()))
2210193326Sed    return true;
2211193326Sed
2212198092Srdivacky  ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
2213198092Srdivacky                    /*isLvalue=*/true);
2214193326Sed  return false;
2215193326Sed}
2216193326Sed
2217193326Sed/// TryContextuallyConvertToBool - Attempt to contextually convert the
2218193326Sed/// expression From to bool (C++0x [conv]p3).
2219193326SedImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
2220198092Srdivacky  return TryImplicitConversion(From, Context.BoolTy,
2221198092Srdivacky                               // FIXME: Are these flags correct?
2222198092Srdivacky                               /*SuppressUserConversions=*/false,
2223198092Srdivacky                               /*AllowExplicit=*/true,
2224198092Srdivacky                               /*ForceRValue=*/false,
2225198092Srdivacky                               /*InOverloadResolution=*/false);
2226193326Sed}
2227193326Sed
2228193326Sed/// PerformContextuallyConvertToBool - Perform a contextual conversion
2229193326Sed/// of the expression From to bool (C++0x [conv]p3).
2230193326Sedbool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2231193326Sed  ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2232193326Sed  if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2233193326Sed    return false;
2234198092Srdivacky
2235199512Srdivacky  if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
2236198092Srdivacky    return  Diag(From->getSourceRange().getBegin(),
2237198092Srdivacky                 diag::err_typecheck_bool_condition)
2238198092Srdivacky                  << From->getType() << From->getSourceRange();
2239198092Srdivacky  return true;
2240193326Sed}
2241193326Sed
2242193326Sed/// AddOverloadCandidate - Adds the given function to the set of
2243193326Sed/// candidate functions, using the given function call arguments.  If
2244193326Sed/// @p SuppressUserConversions, then don't allow user-defined
2245193326Sed/// conversions via constructors or conversion operators.
2246193326Sed/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2247193326Sed/// hacky way to implement the overloading rules for elidable copy
2248193326Sed/// initialization in C++0x (C++0x 12.8p15).
2249198092Srdivacky///
2250198092Srdivacky/// \para PartialOverloading true if we are performing "partial" overloading
2251198092Srdivacky/// based on an incomplete set of function arguments. This feature is used by
2252198092Srdivacky/// code completion.
2253198092Srdivackyvoid
2254198092SrdivackySema::AddOverloadCandidate(FunctionDecl *Function,
2255193326Sed                           Expr **Args, unsigned NumArgs,
2256193326Sed                           OverloadCandidateSet& CandidateSet,
2257193326Sed                           bool SuppressUserConversions,
2258198092Srdivacky                           bool ForceRValue,
2259198092Srdivacky                           bool PartialOverloading) {
2260198092Srdivacky  const FunctionProtoType* Proto
2261198092Srdivacky    = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
2262193326Sed  assert(Proto && "Functions without a prototype cannot be overloaded");
2263198092Srdivacky  assert(!isa<CXXConversionDecl>(Function) &&
2264193326Sed         "Use AddConversionCandidate for conversion functions");
2265198092Srdivacky  assert(!Function->getDescribedFunctionTemplate() &&
2266195099Sed         "Use AddTemplateOverloadCandidate for function templates");
2267198092Srdivacky
2268193326Sed  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
2269193326Sed    if (!isa<CXXConstructorDecl>(Method)) {
2270193326Sed      // If we get here, it's because we're calling a member function
2271193326Sed      // that is named without a member access expression (e.g.,
2272193326Sed      // "this->f") that was either written explicitly or created
2273193326Sed      // implicitly. This can happen with a qualified call to a member
2274200583Srdivacky      // function, e.g., X::f(). We use an empty type for the implied
2275200583Srdivacky      // object argument (C++ [over.call.func]p3), and the acting context
2276200583Srdivacky      // is irrelevant.
2277200583Srdivacky      AddMethodCandidate(Method, Method->getParent(),
2278200583Srdivacky                         QualType(), Args, NumArgs, CandidateSet,
2279193326Sed                         SuppressUserConversions, ForceRValue);
2280193326Sed      return;
2281193326Sed    }
2282193326Sed    // We treat a constructor like a non-member function, since its object
2283193326Sed    // argument doesn't participate in overload resolution.
2284193326Sed  }
2285193326Sed
2286198092Srdivacky  if (!CandidateSet.isNewCandidate(Function))
2287198092Srdivacky    return;
2288199482Srdivacky
2289199990Srdivacky  // Overload resolution is always an unevaluated context.
2290199990Srdivacky  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2291199990Srdivacky
2292199482Srdivacky  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2293199482Srdivacky    // C++ [class.copy]p3:
2294199482Srdivacky    //   A member function template is never instantiated to perform the copy
2295199482Srdivacky    //   of a class object to an object of its class type.
2296199482Srdivacky    QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2297199482Srdivacky    if (NumArgs == 1 &&
2298199482Srdivacky        Constructor->isCopyConstructorLikeSpecialization() &&
2299199482Srdivacky        Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()))
2300199482Srdivacky      return;
2301199482Srdivacky  }
2302199482Srdivacky
2303193326Sed  // Add this candidate
2304193326Sed  CandidateSet.push_back(OverloadCandidate());
2305193326Sed  OverloadCandidate& Candidate = CandidateSet.back();
2306193326Sed  Candidate.Function = Function;
2307193326Sed  Candidate.Viable = true;
2308193326Sed  Candidate.IsSurrogate = false;
2309193326Sed  Candidate.IgnoreObjectArgument = false;
2310193326Sed
2311193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
2312193326Sed
2313193326Sed  // (C++ 13.3.2p2): A candidate function having fewer than m
2314193326Sed  // parameters is viable only if it has an ellipsis in its parameter
2315193326Sed  // list (8.3.5).
2316198092Srdivacky  if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2317198092Srdivacky      !Proto->isVariadic()) {
2318193326Sed    Candidate.Viable = false;
2319193326Sed    return;
2320193326Sed  }
2321193326Sed
2322193326Sed  // (C++ 13.3.2p2): A candidate function having more than m parameters
2323193326Sed  // is viable only if the (m+1)st parameter has a default argument
2324193326Sed  // (8.3.6). For the purposes of overload resolution, the
2325193326Sed  // parameter list is truncated on the right, so that there are
2326193326Sed  // exactly m parameters.
2327193326Sed  unsigned MinRequiredArgs = Function->getMinRequiredArguments();
2328198092Srdivacky  if (NumArgs < MinRequiredArgs && !PartialOverloading) {
2329193326Sed    // Not enough arguments.
2330193326Sed    Candidate.Viable = false;
2331193326Sed    return;
2332193326Sed  }
2333193326Sed
2334193326Sed  // Determine the implicit conversion sequences for each of the
2335193326Sed  // arguments.
2336193326Sed  Candidate.Conversions.resize(NumArgs);
2337193326Sed  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2338193326Sed    if (ArgIdx < NumArgsInProto) {
2339193326Sed      // (C++ 13.3.2p3): for F to be a viable function, there shall
2340193326Sed      // exist for each argument an implicit conversion sequence
2341193326Sed      // (13.3.3.1) that converts that argument to the corresponding
2342193326Sed      // parameter of F.
2343193326Sed      QualType ParamType = Proto->getArgType(ArgIdx);
2344198092Srdivacky      Candidate.Conversions[ArgIdx]
2345198092Srdivacky        = TryCopyInitialization(Args[ArgIdx], ParamType,
2346198092Srdivacky                                SuppressUserConversions, ForceRValue,
2347198092Srdivacky                                /*InOverloadResolution=*/true);
2348198092Srdivacky      if (Candidate.Conversions[ArgIdx].ConversionKind
2349193326Sed            == ImplicitConversionSequence::BadConversion) {
2350198092Srdivacky      // 13.3.3.1-p10 If several different sequences of conversions exist that
2351198092Srdivacky      // each convert the argument to the parameter type, the implicit conversion
2352198092Srdivacky      // sequence associated with the parameter is defined to be the unique conversion
2353198092Srdivacky      // sequence designated the ambiguous conversion sequence. For the purpose of
2354198092Srdivacky      // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2355198092Srdivacky      // conversion sequence is treated as a user-defined sequence that is
2356198092Srdivacky      // indistinguishable from any other user-defined conversion sequence
2357198092Srdivacky        if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
2358198092Srdivacky          Candidate.Conversions[ArgIdx].ConversionKind =
2359198092Srdivacky            ImplicitConversionSequence::UserDefinedConversion;
2360198092Srdivacky          // Set the conversion function to one of them. As due to ambiguity,
2361198092Srdivacky          // they carry the same weight and is needed for overload resolution
2362198092Srdivacky          // later.
2363198092Srdivacky          Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2364198092Srdivacky            Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2365198092Srdivacky        }
2366198092Srdivacky        else {
2367198092Srdivacky          Candidate.Viable = false;
2368198092Srdivacky          break;
2369198092Srdivacky        }
2370193326Sed      }
2371193326Sed    } else {
2372193326Sed      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2373193326Sed      // argument for which there is no corresponding parameter is
2374193326Sed      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2375198092Srdivacky      Candidate.Conversions[ArgIdx].ConversionKind
2376193326Sed        = ImplicitConversionSequence::EllipsisConversion;
2377193326Sed    }
2378193326Sed  }
2379193326Sed}
2380193326Sed
2381193326Sed/// \brief Add all of the function declarations in the given function set to
2382193326Sed/// the overload canddiate set.
2383193326Sedvoid Sema::AddFunctionCandidates(const FunctionSet &Functions,
2384193326Sed                                 Expr **Args, unsigned NumArgs,
2385193326Sed                                 OverloadCandidateSet& CandidateSet,
2386193326Sed                                 bool SuppressUserConversions) {
2387198092Srdivacky  for (FunctionSet::const_iterator F = Functions.begin(),
2388193326Sed                                FEnd = Functions.end();
2389195341Sed       F != FEnd; ++F) {
2390200583Srdivacky    // FIXME: using declarations
2391198092Srdivacky    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2392198092Srdivacky      if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2393198092Srdivacky        AddMethodCandidate(cast<CXXMethodDecl>(FD),
2394200583Srdivacky                           cast<CXXMethodDecl>(FD)->getParent(),
2395200583Srdivacky                           Args[0]->getType(), Args + 1, NumArgs - 1,
2396198092Srdivacky                           CandidateSet, SuppressUserConversions);
2397198092Srdivacky      else
2398198092Srdivacky        AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2399198092Srdivacky                             SuppressUserConversions);
2400198092Srdivacky    } else {
2401198092Srdivacky      FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2402198092Srdivacky      if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2403198092Srdivacky          !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2404198092Srdivacky        AddMethodTemplateCandidate(FunTmpl,
2405200583Srdivacky                              cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
2406199990Srdivacky                                   /*FIXME: explicit args */ 0,
2407200583Srdivacky                                   Args[0]->getType(), Args + 1, NumArgs - 1,
2408198092Srdivacky                                   CandidateSet,
2409195341Sed                                   SuppressUserConversions);
2410198092Srdivacky      else
2411198092Srdivacky        AddTemplateOverloadCandidate(FunTmpl,
2412199990Srdivacky                                     /*FIXME: explicit args */ 0,
2413198092Srdivacky                                     Args, NumArgs, CandidateSet,
2414198092Srdivacky                                     SuppressUserConversions);
2415198092Srdivacky    }
2416195341Sed  }
2417193326Sed}
2418193326Sed
2419199482Srdivacky/// AddMethodCandidate - Adds a named decl (which is some kind of
2420199482Srdivacky/// method) as a method candidate to the given overload set.
2421200583Srdivackyvoid Sema::AddMethodCandidate(NamedDecl *Decl,
2422200583Srdivacky                              QualType ObjectType,
2423199482Srdivacky                              Expr **Args, unsigned NumArgs,
2424199482Srdivacky                              OverloadCandidateSet& CandidateSet,
2425199482Srdivacky                              bool SuppressUserConversions, bool ForceRValue) {
2426199482Srdivacky
2427199482Srdivacky  // FIXME: use this
2428200583Srdivacky  CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
2429199482Srdivacky
2430199482Srdivacky  if (isa<UsingShadowDecl>(Decl))
2431199482Srdivacky    Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
2432199482Srdivacky
2433199482Srdivacky  if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
2434199482Srdivacky    assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
2435199482Srdivacky           "Expected a member function template");
2436200583Srdivacky    AddMethodTemplateCandidate(TD, ActingContext, /*ExplicitArgs*/ 0,
2437200583Srdivacky                               ObjectType, Args, NumArgs,
2438199482Srdivacky                               CandidateSet,
2439199482Srdivacky                               SuppressUserConversions,
2440199482Srdivacky                               ForceRValue);
2441199482Srdivacky  } else {
2442200583Srdivacky    AddMethodCandidate(cast<CXXMethodDecl>(Decl), ActingContext,
2443200583Srdivacky                       ObjectType, Args, NumArgs,
2444199482Srdivacky                       CandidateSet, SuppressUserConversions, ForceRValue);
2445199482Srdivacky  }
2446199482Srdivacky}
2447199482Srdivacky
2448193326Sed/// AddMethodCandidate - Adds the given C++ member function to the set
2449193326Sed/// of candidate functions, using the given function call arguments
2450193326Sed/// and the object argument (@c Object). For example, in a call
2451193326Sed/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2452193326Sed/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2453193326Sed/// allow user-defined conversions via constructors or conversion
2454193326Sed/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2455193326Sed/// a slightly hacky way to implement the overloading rules for elidable copy
2456193326Sed/// initialization in C++0x (C++0x 12.8p15).
2457198092Srdivackyvoid
2458200583SrdivackySema::AddMethodCandidate(CXXMethodDecl *Method, CXXRecordDecl *ActingContext,
2459200583Srdivacky                         QualType ObjectType, Expr **Args, unsigned NumArgs,
2460193326Sed                         OverloadCandidateSet& CandidateSet,
2461198092Srdivacky                         bool SuppressUserConversions, bool ForceRValue) {
2462198092Srdivacky  const FunctionProtoType* Proto
2463198092Srdivacky    = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
2464193326Sed  assert(Proto && "Methods without a prototype cannot be overloaded");
2465193326Sed  assert(!isa<CXXConversionDecl>(Method) &&
2466193326Sed         "Use AddConversionCandidate for conversion functions");
2467193326Sed  assert(!isa<CXXConstructorDecl>(Method) &&
2468193326Sed         "Use AddOverloadCandidate for constructors");
2469193326Sed
2470198092Srdivacky  if (!CandidateSet.isNewCandidate(Method))
2471198092Srdivacky    return;
2472198092Srdivacky
2473199990Srdivacky  // Overload resolution is always an unevaluated context.
2474199990Srdivacky  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2475199990Srdivacky
2476193326Sed  // Add this candidate
2477193326Sed  CandidateSet.push_back(OverloadCandidate());
2478193326Sed  OverloadCandidate& Candidate = CandidateSet.back();
2479193326Sed  Candidate.Function = Method;
2480193326Sed  Candidate.IsSurrogate = false;
2481193326Sed  Candidate.IgnoreObjectArgument = false;
2482193326Sed
2483193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
2484193326Sed
2485193326Sed  // (C++ 13.3.2p2): A candidate function having fewer than m
2486193326Sed  // parameters is viable only if it has an ellipsis in its parameter
2487193326Sed  // list (8.3.5).
2488193326Sed  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2489193326Sed    Candidate.Viable = false;
2490193326Sed    return;
2491193326Sed  }
2492193326Sed
2493193326Sed  // (C++ 13.3.2p2): A candidate function having more than m parameters
2494193326Sed  // is viable only if the (m+1)st parameter has a default argument
2495193326Sed  // (8.3.6). For the purposes of overload resolution, the
2496193326Sed  // parameter list is truncated on the right, so that there are
2497193326Sed  // exactly m parameters.
2498193326Sed  unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2499193326Sed  if (NumArgs < MinRequiredArgs) {
2500193326Sed    // Not enough arguments.
2501193326Sed    Candidate.Viable = false;
2502193326Sed    return;
2503193326Sed  }
2504193326Sed
2505193326Sed  Candidate.Viable = true;
2506193326Sed  Candidate.Conversions.resize(NumArgs + 1);
2507193326Sed
2508200583Srdivacky  if (Method->isStatic() || ObjectType.isNull())
2509193326Sed    // The implicit object argument is ignored.
2510193326Sed    Candidate.IgnoreObjectArgument = true;
2511193326Sed  else {
2512193326Sed    // Determine the implicit conversion sequence for the object
2513193326Sed    // parameter.
2514200583Srdivacky    Candidate.Conversions[0]
2515200583Srdivacky      = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
2516198092Srdivacky    if (Candidate.Conversions[0].ConversionKind
2517193326Sed          == ImplicitConversionSequence::BadConversion) {
2518193326Sed      Candidate.Viable = false;
2519193326Sed      return;
2520193326Sed    }
2521193326Sed  }
2522193326Sed
2523193326Sed  // Determine the implicit conversion sequences for each of the
2524193326Sed  // arguments.
2525193326Sed  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2526193326Sed    if (ArgIdx < NumArgsInProto) {
2527193326Sed      // (C++ 13.3.2p3): for F to be a viable function, there shall
2528193326Sed      // exist for each argument an implicit conversion sequence
2529193326Sed      // (13.3.3.1) that converts that argument to the corresponding
2530193326Sed      // parameter of F.
2531193326Sed      QualType ParamType = Proto->getArgType(ArgIdx);
2532198092Srdivacky      Candidate.Conversions[ArgIdx + 1]
2533198092Srdivacky        = TryCopyInitialization(Args[ArgIdx], ParamType,
2534198092Srdivacky                                SuppressUserConversions, ForceRValue,
2535198092Srdivacky                                /*InOverloadResolution=*/true);
2536198092Srdivacky      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2537193326Sed            == ImplicitConversionSequence::BadConversion) {
2538193326Sed        Candidate.Viable = false;
2539193326Sed        break;
2540193326Sed      }
2541193326Sed    } else {
2542193326Sed      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2543193326Sed      // argument for which there is no corresponding parameter is
2544193326Sed      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2545198092Srdivacky      Candidate.Conversions[ArgIdx + 1].ConversionKind
2546193326Sed        = ImplicitConversionSequence::EllipsisConversion;
2547193326Sed    }
2548193326Sed  }
2549193326Sed}
2550193326Sed
2551198092Srdivacky/// \brief Add a C++ member function template as a candidate to the candidate
2552198092Srdivacky/// set, using template argument deduction to produce an appropriate member
2553198092Srdivacky/// function template specialization.
2554198092Srdivackyvoid
2555198092SrdivackySema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2556200583Srdivacky                                 CXXRecordDecl *ActingContext,
2557199990Srdivacky                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
2558200583Srdivacky                                 QualType ObjectType,
2559200583Srdivacky                                 Expr **Args, unsigned NumArgs,
2560198092Srdivacky                                 OverloadCandidateSet& CandidateSet,
2561198092Srdivacky                                 bool SuppressUserConversions,
2562198092Srdivacky                                 bool ForceRValue) {
2563198092Srdivacky  if (!CandidateSet.isNewCandidate(MethodTmpl))
2564198092Srdivacky    return;
2565198092Srdivacky
2566198092Srdivacky  // C++ [over.match.funcs]p7:
2567198092Srdivacky  //   In each case where a candidate is a function template, candidate
2568198092Srdivacky  //   function template specializations are generated using template argument
2569198092Srdivacky  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2570198092Srdivacky  //   candidate functions in the usual way.113) A given name can refer to one
2571198092Srdivacky  //   or more function templates and also to a set of overloaded non-template
2572198092Srdivacky  //   functions. In such a case, the candidate functions generated from each
2573198092Srdivacky  //   function template are combined with the set of non-template candidate
2574198092Srdivacky  //   functions.
2575198092Srdivacky  TemplateDeductionInfo Info(Context);
2576198092Srdivacky  FunctionDecl *Specialization = 0;
2577198092Srdivacky  if (TemplateDeductionResult Result
2578199990Srdivacky      = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
2579198092Srdivacky                                Args, NumArgs, Specialization, Info)) {
2580198092Srdivacky        // FIXME: Record what happened with template argument deduction, so
2581198092Srdivacky        // that we can give the user a beautiful diagnostic.
2582198092Srdivacky        (void)Result;
2583198092Srdivacky        return;
2584198092Srdivacky      }
2585198092Srdivacky
2586198092Srdivacky  // Add the function template specialization produced by template argument
2587198092Srdivacky  // deduction as a candidate.
2588198092Srdivacky  assert(Specialization && "Missing member function template specialization?");
2589198092Srdivacky  assert(isa<CXXMethodDecl>(Specialization) &&
2590198092Srdivacky         "Specialization is not a member function?");
2591200583Srdivacky  AddMethodCandidate(cast<CXXMethodDecl>(Specialization), ActingContext,
2592200583Srdivacky                     ObjectType, Args, NumArgs,
2593198092Srdivacky                     CandidateSet, SuppressUserConversions, ForceRValue);
2594198092Srdivacky}
2595198092Srdivacky
2596198092Srdivacky/// \brief Add a C++ function template specialization as a candidate
2597198092Srdivacky/// in the candidate set, using template argument deduction to produce
2598198092Srdivacky/// an appropriate function template specialization.
2599198092Srdivackyvoid
2600195099SedSema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
2601199990Srdivacky                        const TemplateArgumentListInfo *ExplicitTemplateArgs,
2602195099Sed                                   Expr **Args, unsigned NumArgs,
2603195099Sed                                   OverloadCandidateSet& CandidateSet,
2604195099Sed                                   bool SuppressUserConversions,
2605195099Sed                                   bool ForceRValue) {
2606198092Srdivacky  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2607198092Srdivacky    return;
2608198092Srdivacky
2609195099Sed  // C++ [over.match.funcs]p7:
2610198092Srdivacky  //   In each case where a candidate is a function template, candidate
2611195099Sed  //   function template specializations are generated using template argument
2612198092Srdivacky  //   deduction (14.8.3, 14.8.2). Those candidates are then handled as
2613195099Sed  //   candidate functions in the usual way.113) A given name can refer to one
2614195099Sed  //   or more function templates and also to a set of overloaded non-template
2615195099Sed  //   functions. In such a case, the candidate functions generated from each
2616195099Sed  //   function template are combined with the set of non-template candidate
2617195099Sed  //   functions.
2618195099Sed  TemplateDeductionInfo Info(Context);
2619195099Sed  FunctionDecl *Specialization = 0;
2620195099Sed  if (TemplateDeductionResult Result
2621199990Srdivacky        = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
2622195341Sed                                  Args, NumArgs, Specialization, Info)) {
2623195099Sed    // FIXME: Record what happened with template argument deduction, so
2624195099Sed    // that we can give the user a beautiful diagnostic.
2625195099Sed    (void)Result;
2626195099Sed    return;
2627195099Sed  }
2628198092Srdivacky
2629195099Sed  // Add the function template specialization produced by template argument
2630195099Sed  // deduction as a candidate.
2631195099Sed  assert(Specialization && "Missing function template specialization?");
2632195099Sed  AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2633195099Sed                       SuppressUserConversions, ForceRValue);
2634195099Sed}
2635198092Srdivacky
2636193326Sed/// AddConversionCandidate - Add a C++ conversion function as a
2637198092Srdivacky/// candidate in the candidate set (C++ [over.match.conv],
2638193326Sed/// C++ [over.match.copy]). From is the expression we're converting from,
2639198092Srdivacky/// and ToType is the type that we're eventually trying to convert to
2640193326Sed/// (which may or may not be the same type as the type that the
2641193326Sed/// conversion function produces).
2642193326Sedvoid
2643193326SedSema::AddConversionCandidate(CXXConversionDecl *Conversion,
2644200583Srdivacky                             CXXRecordDecl *ActingContext,
2645193326Sed                             Expr *From, QualType ToType,
2646193326Sed                             OverloadCandidateSet& CandidateSet) {
2647198092Srdivacky  assert(!Conversion->getDescribedFunctionTemplate() &&
2648198092Srdivacky         "Conversion function templates use AddTemplateConversionCandidate");
2649198092Srdivacky
2650198092Srdivacky  if (!CandidateSet.isNewCandidate(Conversion))
2651198092Srdivacky    return;
2652198092Srdivacky
2653199990Srdivacky  // Overload resolution is always an unevaluated context.
2654199990Srdivacky  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2655199990Srdivacky
2656193326Sed  // Add this candidate
2657193326Sed  CandidateSet.push_back(OverloadCandidate());
2658193326Sed  OverloadCandidate& Candidate = CandidateSet.back();
2659193326Sed  Candidate.Function = Conversion;
2660193326Sed  Candidate.IsSurrogate = false;
2661193326Sed  Candidate.IgnoreObjectArgument = false;
2662193326Sed  Candidate.FinalConversion.setAsIdentityConversion();
2663198092Srdivacky  Candidate.FinalConversion.FromTypePtr
2664193326Sed    = Conversion->getConversionType().getAsOpaquePtr();
2665193326Sed  Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2666193326Sed
2667193326Sed  // Determine the implicit conversion sequence for the implicit
2668193326Sed  // object parameter.
2669193326Sed  Candidate.Viable = true;
2670193326Sed  Candidate.Conversions.resize(1);
2671200583Srdivacky  Candidate.Conversions[0]
2672200583Srdivacky    = TryObjectArgumentInitialization(From->getType(), Conversion,
2673200583Srdivacky                                      ActingContext);
2674198092Srdivacky  // Conversion functions to a different type in the base class is visible in
2675198092Srdivacky  // the derived class.  So, a derived to base conversion should not participate
2676198092Srdivacky  // in overload resolution.
2677198092Srdivacky  if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2678198092Srdivacky    Candidate.Conversions[0].Standard.Second = ICK_Identity;
2679198092Srdivacky  if (Candidate.Conversions[0].ConversionKind
2680193326Sed      == ImplicitConversionSequence::BadConversion) {
2681193326Sed    Candidate.Viable = false;
2682193326Sed    return;
2683193326Sed  }
2684198398Srdivacky
2685198398Srdivacky  // We won't go through a user-define type conversion function to convert a
2686198398Srdivacky  // derived to base as such conversions are given Conversion Rank. They only
2687198398Srdivacky  // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2688198398Srdivacky  QualType FromCanon
2689198398Srdivacky    = Context.getCanonicalType(From->getType().getUnqualifiedType());
2690198398Srdivacky  QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2691198398Srdivacky  if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2692198398Srdivacky    Candidate.Viable = false;
2693198398Srdivacky    return;
2694198398Srdivacky  }
2695198398Srdivacky
2696193326Sed
2697193326Sed  // To determine what the conversion from the result of calling the
2698193326Sed  // conversion function to the type we're eventually trying to
2699193326Sed  // convert to (ToType), we need to synthesize a call to the
2700193326Sed  // conversion function and attempt copy initialization from it. This
2701193326Sed  // makes sure that we get the right semantics with respect to
2702193326Sed  // lvalues/rvalues and the type. Fortunately, we can allocate this
2703193326Sed  // call on the stack and we don't need its arguments to be
2704193326Sed  // well-formed.
2705198092Srdivacky  DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
2706199482Srdivacky                            From->getLocStart());
2707193326Sed  ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
2708198398Srdivacky                                CastExpr::CK_FunctionToPointerDecay,
2709193326Sed                                &ConversionRef, false);
2710198092Srdivacky
2711198092Srdivacky  // Note that it is safe to allocate CallExpr on the stack here because
2712193326Sed  // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2713193326Sed  // allocator).
2714198092Srdivacky  CallExpr Call(Context, &ConversionFn, 0, 0,
2715193326Sed                Conversion->getConversionType().getNonReferenceType(),
2716199482Srdivacky                From->getLocStart());
2717198092Srdivacky  ImplicitConversionSequence ICS =
2718198092Srdivacky    TryCopyInitialization(&Call, ToType,
2719198092Srdivacky                          /*SuppressUserConversions=*/true,
2720198092Srdivacky                          /*ForceRValue=*/false,
2721198092Srdivacky                          /*InOverloadResolution=*/false);
2722198092Srdivacky
2723193326Sed  switch (ICS.ConversionKind) {
2724193326Sed  case ImplicitConversionSequence::StandardConversion:
2725193326Sed    Candidate.FinalConversion = ICS.Standard;
2726193326Sed    break;
2727193326Sed
2728193326Sed  case ImplicitConversionSequence::BadConversion:
2729193326Sed    Candidate.Viable = false;
2730193326Sed    break;
2731193326Sed
2732193326Sed  default:
2733198092Srdivacky    assert(false &&
2734193326Sed           "Can only end up with a standard conversion sequence or failure");
2735193326Sed  }
2736193326Sed}
2737193326Sed
2738198092Srdivacky/// \brief Adds a conversion function template specialization
2739198092Srdivacky/// candidate to the overload set, using template argument deduction
2740198092Srdivacky/// to deduce the template arguments of the conversion function
2741198092Srdivacky/// template from the type that we are converting to (C++
2742198092Srdivacky/// [temp.deduct.conv]).
2743198092Srdivackyvoid
2744198092SrdivackySema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2745200583Srdivacky                                     CXXRecordDecl *ActingDC,
2746198092Srdivacky                                     Expr *From, QualType ToType,
2747198092Srdivacky                                     OverloadCandidateSet &CandidateSet) {
2748198092Srdivacky  assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2749198092Srdivacky         "Only conversion function templates permitted here");
2750198092Srdivacky
2751198092Srdivacky  if (!CandidateSet.isNewCandidate(FunctionTemplate))
2752198092Srdivacky    return;
2753198092Srdivacky
2754198092Srdivacky  TemplateDeductionInfo Info(Context);
2755198092Srdivacky  CXXConversionDecl *Specialization = 0;
2756198092Srdivacky  if (TemplateDeductionResult Result
2757198092Srdivacky        = DeduceTemplateArguments(FunctionTemplate, ToType,
2758198092Srdivacky                                  Specialization, Info)) {
2759198092Srdivacky    // FIXME: Record what happened with template argument deduction, so
2760198092Srdivacky    // that we can give the user a beautiful diagnostic.
2761198092Srdivacky    (void)Result;
2762198092Srdivacky    return;
2763198092Srdivacky  }
2764198092Srdivacky
2765198092Srdivacky  // Add the conversion function template specialization produced by
2766198092Srdivacky  // template argument deduction as a candidate.
2767198092Srdivacky  assert(Specialization && "Missing function template specialization?");
2768200583Srdivacky  AddConversionCandidate(Specialization, ActingDC, From, ToType, CandidateSet);
2769198092Srdivacky}
2770198092Srdivacky
2771193326Sed/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2772193326Sed/// converts the given @c Object to a function pointer via the
2773193326Sed/// conversion function @c Conversion, and then attempts to call it
2774193326Sed/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2775193326Sed/// the type of function that we'll eventually be calling.
2776193326Sedvoid Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
2777200583Srdivacky                                 CXXRecordDecl *ActingContext,
2778193326Sed                                 const FunctionProtoType *Proto,
2779200583Srdivacky                                 QualType ObjectType,
2780200583Srdivacky                                 Expr **Args, unsigned NumArgs,
2781193326Sed                                 OverloadCandidateSet& CandidateSet) {
2782198092Srdivacky  if (!CandidateSet.isNewCandidate(Conversion))
2783198092Srdivacky    return;
2784198092Srdivacky
2785199990Srdivacky  // Overload resolution is always an unevaluated context.
2786199990Srdivacky  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2787199990Srdivacky
2788193326Sed  CandidateSet.push_back(OverloadCandidate());
2789193326Sed  OverloadCandidate& Candidate = CandidateSet.back();
2790193326Sed  Candidate.Function = 0;
2791193326Sed  Candidate.Surrogate = Conversion;
2792193326Sed  Candidate.Viable = true;
2793193326Sed  Candidate.IsSurrogate = true;
2794193326Sed  Candidate.IgnoreObjectArgument = false;
2795193326Sed  Candidate.Conversions.resize(NumArgs + 1);
2796193326Sed
2797193326Sed  // Determine the implicit conversion sequence for the implicit
2798193326Sed  // object parameter.
2799198092Srdivacky  ImplicitConversionSequence ObjectInit
2800200583Srdivacky    = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
2801193326Sed  if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2802193326Sed    Candidate.Viable = false;
2803193326Sed    return;
2804193326Sed  }
2805193326Sed
2806193326Sed  // The first conversion is actually a user-defined conversion whose
2807193326Sed  // first conversion is ObjectInit's standard conversion (which is
2808193326Sed  // effectively a reference binding). Record it as such.
2809198092Srdivacky  Candidate.Conversions[0].ConversionKind
2810193326Sed    = ImplicitConversionSequence::UserDefinedConversion;
2811193326Sed  Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2812199482Srdivacky  Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
2813193326Sed  Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
2814198092Srdivacky  Candidate.Conversions[0].UserDefined.After
2815193326Sed    = Candidate.Conversions[0].UserDefined.Before;
2816193326Sed  Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2817193326Sed
2818198092Srdivacky  // Find the
2819193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
2820193326Sed
2821193326Sed  // (C++ 13.3.2p2): A candidate function having fewer than m
2822193326Sed  // parameters is viable only if it has an ellipsis in its parameter
2823193326Sed  // list (8.3.5).
2824193326Sed  if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2825193326Sed    Candidate.Viable = false;
2826193326Sed    return;
2827193326Sed  }
2828193326Sed
2829193326Sed  // Function types don't have any default arguments, so just check if
2830193326Sed  // we have enough arguments.
2831193326Sed  if (NumArgs < NumArgsInProto) {
2832193326Sed    // Not enough arguments.
2833193326Sed    Candidate.Viable = false;
2834193326Sed    return;
2835193326Sed  }
2836193326Sed
2837193326Sed  // Determine the implicit conversion sequences for each of the
2838193326Sed  // arguments.
2839193326Sed  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2840193326Sed    if (ArgIdx < NumArgsInProto) {
2841193326Sed      // (C++ 13.3.2p3): for F to be a viable function, there shall
2842193326Sed      // exist for each argument an implicit conversion sequence
2843193326Sed      // (13.3.3.1) that converts that argument to the corresponding
2844193326Sed      // parameter of F.
2845193326Sed      QualType ParamType = Proto->getArgType(ArgIdx);
2846198092Srdivacky      Candidate.Conversions[ArgIdx + 1]
2847198092Srdivacky        = TryCopyInitialization(Args[ArgIdx], ParamType,
2848198092Srdivacky                                /*SuppressUserConversions=*/false,
2849198092Srdivacky                                /*ForceRValue=*/false,
2850198092Srdivacky                                /*InOverloadResolution=*/false);
2851198092Srdivacky      if (Candidate.Conversions[ArgIdx + 1].ConversionKind
2852193326Sed            == ImplicitConversionSequence::BadConversion) {
2853193326Sed        Candidate.Viable = false;
2854193326Sed        break;
2855193326Sed      }
2856193326Sed    } else {
2857193326Sed      // (C++ 13.3.2p2): For the purposes of overload resolution, any
2858193326Sed      // argument for which there is no corresponding parameter is
2859193326Sed      // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
2860198092Srdivacky      Candidate.Conversions[ArgIdx + 1].ConversionKind
2861193326Sed        = ImplicitConversionSequence::EllipsisConversion;
2862193326Sed    }
2863193326Sed  }
2864193326Sed}
2865193326Sed
2866193326Sed// FIXME: This will eventually be removed, once we've migrated all of the
2867193326Sed// operator overloading logic over to the scheme used by binary operators, which
2868193326Sed// works for template instantiation.
2869193326Sedvoid Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
2870193326Sed                                 SourceLocation OpLoc,
2871193326Sed                                 Expr **Args, unsigned NumArgs,
2872193326Sed                                 OverloadCandidateSet& CandidateSet,
2873193326Sed                                 SourceRange OpRange) {
2874193326Sed  FunctionSet Functions;
2875193326Sed
2876193326Sed  QualType T1 = Args[0]->getType();
2877193326Sed  QualType T2;
2878193326Sed  if (NumArgs > 1)
2879193326Sed    T2 = Args[1]->getType();
2880193326Sed
2881193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2882193326Sed  if (S)
2883193326Sed    LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
2884198893Srdivacky  ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
2885193326Sed  AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2886193326Sed  AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2887198398Srdivacky  AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
2888193326Sed}
2889193326Sed
2890193326Sed/// \brief Add overload candidates for overloaded operators that are
2891193326Sed/// member functions.
2892193326Sed///
2893193326Sed/// Add the overloaded operator candidates that are member functions
2894193326Sed/// for the operator Op that was used in an operator expression such
2895193326Sed/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2896193326Sed/// CandidateSet will store the added overload candidates. (C++
2897193326Sed/// [over.match.oper]).
2898193326Sedvoid Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2899193326Sed                                       SourceLocation OpLoc,
2900193326Sed                                       Expr **Args, unsigned NumArgs,
2901193326Sed                                       OverloadCandidateSet& CandidateSet,
2902193326Sed                                       SourceRange OpRange) {
2903193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2904193326Sed
2905193326Sed  // C++ [over.match.oper]p3:
2906193326Sed  //   For a unary operator @ with an operand of a type whose
2907193326Sed  //   cv-unqualified version is T1, and for a binary operator @ with
2908193326Sed  //   a left operand of a type whose cv-unqualified version is T1 and
2909193326Sed  //   a right operand of a type whose cv-unqualified version is T2,
2910193326Sed  //   three sets of candidate functions, designated member
2911193326Sed  //   candidates, non-member candidates and built-in candidates, are
2912193326Sed  //   constructed as follows:
2913193326Sed  QualType T1 = Args[0]->getType();
2914193326Sed  QualType T2;
2915193326Sed  if (NumArgs > 1)
2916193326Sed    T2 = Args[1]->getType();
2917193326Sed
2918193326Sed  //     -- If T1 is a class type, the set of member candidates is the
2919193326Sed  //        result of the qualified lookup of T1::operator@
2920193326Sed  //        (13.3.1.1.1); otherwise, the set of member candidates is
2921193326Sed  //        empty.
2922198092Srdivacky  if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
2923198092Srdivacky    // Complete the type if it can be completed. Otherwise, we're done.
2924198092Srdivacky    if (RequireCompleteType(OpLoc, T1, PDiag()))
2925198092Srdivacky      return;
2926198092Srdivacky
2927199482Srdivacky    LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
2928199482Srdivacky    LookupQualifiedName(Operators, T1Rec->getDecl());
2929199482Srdivacky    Operators.suppressDiagnostics();
2930199482Srdivacky
2931198092Srdivacky    for (LookupResult::iterator Oper = Operators.begin(),
2932198092Srdivacky                             OperEnd = Operators.end();
2933198092Srdivacky         Oper != OperEnd;
2934199482Srdivacky         ++Oper)
2935200583Srdivacky      AddMethodCandidate(*Oper, Args[0]->getType(),
2936200583Srdivacky                         Args + 1, NumArgs - 1, CandidateSet,
2937199482Srdivacky                         /* SuppressUserConversions = */ false);
2938193326Sed  }
2939193326Sed}
2940193326Sed
2941193326Sed/// AddBuiltinCandidate - Add a candidate for a built-in
2942193326Sed/// operator. ResultTy and ParamTys are the result and parameter types
2943193326Sed/// of the built-in candidate, respectively. Args and NumArgs are the
2944193326Sed/// arguments being passed to the candidate. IsAssignmentOperator
2945193326Sed/// should be true when this built-in candidate is an assignment
2946193326Sed/// operator. NumContextualBoolArguments is the number of arguments
2947193326Sed/// (at the beginning of the argument list) that will be contextually
2948193326Sed/// converted to bool.
2949198092Srdivackyvoid Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
2950193326Sed                               Expr **Args, unsigned NumArgs,
2951193326Sed                               OverloadCandidateSet& CandidateSet,
2952193326Sed                               bool IsAssignmentOperator,
2953193326Sed                               unsigned NumContextualBoolArguments) {
2954199990Srdivacky  // Overload resolution is always an unevaluated context.
2955199990Srdivacky  EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2956199990Srdivacky
2957193326Sed  // Add this candidate
2958193326Sed  CandidateSet.push_back(OverloadCandidate());
2959193326Sed  OverloadCandidate& Candidate = CandidateSet.back();
2960193326Sed  Candidate.Function = 0;
2961193326Sed  Candidate.IsSurrogate = false;
2962193326Sed  Candidate.IgnoreObjectArgument = false;
2963193326Sed  Candidate.BuiltinTypes.ResultTy = ResultTy;
2964193326Sed  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2965193326Sed    Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2966193326Sed
2967193326Sed  // Determine the implicit conversion sequences for each of the
2968193326Sed  // arguments.
2969193326Sed  Candidate.Viable = true;
2970193326Sed  Candidate.Conversions.resize(NumArgs);
2971193326Sed  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2972193326Sed    // C++ [over.match.oper]p4:
2973193326Sed    //   For the built-in assignment operators, conversions of the
2974193326Sed    //   left operand are restricted as follows:
2975193326Sed    //     -- no temporaries are introduced to hold the left operand, and
2976193326Sed    //     -- no user-defined conversions are applied to the left
2977193326Sed    //        operand to achieve a type match with the left-most
2978198092Srdivacky    //        parameter of a built-in candidate.
2979193326Sed    //
2980193326Sed    // We block these conversions by turning off user-defined
2981193326Sed    // conversions, since that is the only way that initialization of
2982193326Sed    // a reference to a non-class type can occur from something that
2983193326Sed    // is not of the same type.
2984193326Sed    if (ArgIdx < NumContextualBoolArguments) {
2985198092Srdivacky      assert(ParamTys[ArgIdx] == Context.BoolTy &&
2986193326Sed             "Contextual conversion to bool requires bool type");
2987193326Sed      Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2988193326Sed    } else {
2989198092Srdivacky      Candidate.Conversions[ArgIdx]
2990198092Srdivacky        = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
2991198092Srdivacky                                ArgIdx == 0 && IsAssignmentOperator,
2992198092Srdivacky                                /*ForceRValue=*/false,
2993198092Srdivacky                                /*InOverloadResolution=*/false);
2994193326Sed    }
2995198092Srdivacky    if (Candidate.Conversions[ArgIdx].ConversionKind
2996193326Sed        == ImplicitConversionSequence::BadConversion) {
2997193326Sed      Candidate.Viable = false;
2998193326Sed      break;
2999193326Sed    }
3000193326Sed  }
3001193326Sed}
3002193326Sed
3003193326Sed/// BuiltinCandidateTypeSet - A set of types that will be used for the
3004193326Sed/// candidate operator functions for built-in operators (C++
3005193326Sed/// [over.built]). The types are separated into pointer types and
3006193326Sed/// enumeration types.
3007193326Sedclass BuiltinCandidateTypeSet  {
3008193326Sed  /// TypeSet - A set of types.
3009193326Sed  typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
3010193326Sed
3011193326Sed  /// PointerTypes - The set of pointer types that will be used in the
3012193326Sed  /// built-in candidates.
3013193326Sed  TypeSet PointerTypes;
3014193326Sed
3015193326Sed  /// MemberPointerTypes - The set of member pointer types that will be
3016193326Sed  /// used in the built-in candidates.
3017193326Sed  TypeSet MemberPointerTypes;
3018193326Sed
3019193326Sed  /// EnumerationTypes - The set of enumeration types that will be
3020193326Sed  /// used in the built-in candidates.
3021193326Sed  TypeSet EnumerationTypes;
3022193326Sed
3023198092Srdivacky  /// Sema - The semantic analysis instance where we are building the
3024198092Srdivacky  /// candidate type set.
3025198092Srdivacky  Sema &SemaRef;
3026198092Srdivacky
3027193326Sed  /// Context - The AST context in which we will build the type sets.
3028193326Sed  ASTContext &Context;
3029193326Sed
3030198398Srdivacky  bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3031198398Srdivacky                                               const Qualifiers &VisibleQuals);
3032193326Sed  bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
3033193326Sed
3034193326Sedpublic:
3035193326Sed  /// iterator - Iterates through the types that are part of the set.
3036193326Sed  typedef TypeSet::iterator iterator;
3037193326Sed
3038198092Srdivacky  BuiltinCandidateTypeSet(Sema &SemaRef)
3039198092Srdivacky    : SemaRef(SemaRef), Context(SemaRef.Context) { }
3040193326Sed
3041198398Srdivacky  void AddTypesConvertedFrom(QualType Ty,
3042198398Srdivacky                             SourceLocation Loc,
3043198398Srdivacky                             bool AllowUserConversions,
3044198398Srdivacky                             bool AllowExplicitConversions,
3045198398Srdivacky                             const Qualifiers &VisibleTypeConversionsQuals);
3046193326Sed
3047193326Sed  /// pointer_begin - First pointer type found;
3048193326Sed  iterator pointer_begin() { return PointerTypes.begin(); }
3049193326Sed
3050193326Sed  /// pointer_end - Past the last pointer type found;
3051193326Sed  iterator pointer_end() { return PointerTypes.end(); }
3052193326Sed
3053193326Sed  /// member_pointer_begin - First member pointer type found;
3054193326Sed  iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3055193326Sed
3056193326Sed  /// member_pointer_end - Past the last member pointer type found;
3057193326Sed  iterator member_pointer_end() { return MemberPointerTypes.end(); }
3058193326Sed
3059193326Sed  /// enumeration_begin - First enumeration type found;
3060193326Sed  iterator enumeration_begin() { return EnumerationTypes.begin(); }
3061193326Sed
3062193326Sed  /// enumeration_end - Past the last enumeration type found;
3063193326Sed  iterator enumeration_end() { return EnumerationTypes.end(); }
3064193326Sed};
3065193326Sed
3066193326Sed/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
3067193326Sed/// the set of pointer types along with any more-qualified variants of
3068193326Sed/// that type. For example, if @p Ty is "int const *", this routine
3069193326Sed/// will add "int const *", "int const volatile *", "int const
3070193326Sed/// restrict *", and "int const volatile restrict *" to the set of
3071193326Sed/// pointer types. Returns true if the add of @p Ty itself succeeded,
3072193326Sed/// false otherwise.
3073198092Srdivacky///
3074198092Srdivacky/// FIXME: what to do about extended qualifiers?
3075193326Sedbool
3076198398SrdivackyBuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3077198398Srdivacky                                             const Qualifiers &VisibleQuals) {
3078198092Srdivacky
3079193326Sed  // Insert this type.
3080193326Sed  if (!PointerTypes.insert(Ty))
3081193326Sed    return false;
3082193326Sed
3083198092Srdivacky  const PointerType *PointerTy = Ty->getAs<PointerType>();
3084198092Srdivacky  assert(PointerTy && "type was not a pointer type!");
3085193326Sed
3086198092Srdivacky  QualType PointeeTy = PointerTy->getPointeeType();
3087199512Srdivacky  // Don't add qualified variants of arrays. For one, they're not allowed
3088199512Srdivacky  // (the qualifier would sink to the element type), and for another, the
3089199512Srdivacky  // only overload situation where it matters is subscript or pointer +- int,
3090199512Srdivacky  // and those shouldn't have qualifier variants anyway.
3091199512Srdivacky  if (PointeeTy->isArrayType())
3092199512Srdivacky    return true;
3093198092Srdivacky  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3094199482Srdivacky  if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
3095199482Srdivacky    BaseCVR = Array->getElementType().getCVRQualifiers();
3096198398Srdivacky  bool hasVolatile = VisibleQuals.hasVolatile();
3097198398Srdivacky  bool hasRestrict = VisibleQuals.hasRestrict();
3098198398Srdivacky
3099198092Srdivacky  // Iterate through all strict supersets of BaseCVR.
3100198092Srdivacky  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3101198092Srdivacky    if ((CVR | BaseCVR) != CVR) continue;
3102198398Srdivacky    // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3103198398Srdivacky    // in the types.
3104198398Srdivacky    if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3105198398Srdivacky    if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
3106198092Srdivacky    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3107198092Srdivacky    PointerTypes.insert(Context.getPointerType(QPointeeTy));
3108193326Sed  }
3109193326Sed
3110193326Sed  return true;
3111193326Sed}
3112193326Sed
3113193326Sed/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3114193326Sed/// to the set of pointer types along with any more-qualified variants of
3115193326Sed/// that type. For example, if @p Ty is "int const *", this routine
3116193326Sed/// will add "int const *", "int const volatile *", "int const
3117193326Sed/// restrict *", and "int const volatile restrict *" to the set of
3118193326Sed/// pointer types. Returns true if the add of @p Ty itself succeeded,
3119193326Sed/// false otherwise.
3120198092Srdivacky///
3121198092Srdivacky/// FIXME: what to do about extended qualifiers?
3122193326Sedbool
3123193326SedBuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3124193326Sed    QualType Ty) {
3125193326Sed  // Insert this type.
3126193326Sed  if (!MemberPointerTypes.insert(Ty))
3127193326Sed    return false;
3128193326Sed
3129198092Srdivacky  const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3130198092Srdivacky  assert(PointerTy && "type was not a member pointer type!");
3131193326Sed
3132198092Srdivacky  QualType PointeeTy = PointerTy->getPointeeType();
3133199512Srdivacky  // Don't add qualified variants of arrays. For one, they're not allowed
3134199512Srdivacky  // (the qualifier would sink to the element type), and for another, the
3135199512Srdivacky  // only overload situation where it matters is subscript or pointer +- int,
3136199512Srdivacky  // and those shouldn't have qualifier variants anyway.
3137199512Srdivacky  if (PointeeTy->isArrayType())
3138199512Srdivacky    return true;
3139198092Srdivacky  const Type *ClassTy = PointerTy->getClass();
3140198092Srdivacky
3141198092Srdivacky  // Iterate through all strict supersets of the pointee type's CVR
3142198092Srdivacky  // qualifiers.
3143198092Srdivacky  unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3144198092Srdivacky  for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3145198092Srdivacky    if ((CVR | BaseCVR) != CVR) continue;
3146198092Srdivacky
3147198092Srdivacky    QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3148198092Srdivacky    MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
3149193326Sed  }
3150193326Sed
3151193326Sed  return true;
3152193326Sed}
3153193326Sed
3154193326Sed/// AddTypesConvertedFrom - Add each of the types to which the type @p
3155193326Sed/// Ty can be implicit converted to the given set of @p Types. We're
3156193326Sed/// primarily interested in pointer types and enumeration types. We also
3157193326Sed/// take member pointer types, for the conditional operator.
3158193326Sed/// AllowUserConversions is true if we should look at the conversion
3159193326Sed/// functions of a class type, and AllowExplicitConversions if we
3160193326Sed/// should also include the explicit conversion functions of a class
3161193326Sed/// type.
3162198092Srdivackyvoid
3163193326SedBuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
3164198398Srdivacky                                               SourceLocation Loc,
3165193326Sed                                               bool AllowUserConversions,
3166198398Srdivacky                                               bool AllowExplicitConversions,
3167198398Srdivacky                                               const Qualifiers &VisibleQuals) {
3168193326Sed  // Only deal with canonical types.
3169193326Sed  Ty = Context.getCanonicalType(Ty);
3170193326Sed
3171193326Sed  // Look through reference types; they aren't part of the type of an
3172193326Sed  // expression for the purposes of conversions.
3173198092Srdivacky  if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
3174193326Sed    Ty = RefTy->getPointeeType();
3175193326Sed
3176193326Sed  // We don't care about qualifiers on the type.
3177199482Srdivacky  Ty = Ty.getLocalUnqualifiedType();
3178193326Sed
3179198954Srdivacky  // If we're dealing with an array type, decay to the pointer.
3180198954Srdivacky  if (Ty->isArrayType())
3181198954Srdivacky    Ty = SemaRef.Context.getArrayDecayedType(Ty);
3182198954Srdivacky
3183198092Srdivacky  if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
3184193326Sed    QualType PointeeTy = PointerTy->getPointeeType();
3185193326Sed
3186193326Sed    // Insert our type, and its more-qualified variants, into the set
3187193326Sed    // of types.
3188198398Srdivacky    if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
3189193326Sed      return;
3190193326Sed  } else if (Ty->isMemberPointerType()) {
3191193326Sed    // Member pointers are far easier, since the pointee can't be converted.
3192193326Sed    if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3193193326Sed      return;
3194193326Sed  } else if (Ty->isEnumeralType()) {
3195193326Sed    EnumerationTypes.insert(Ty);
3196193326Sed  } else if (AllowUserConversions) {
3197198092Srdivacky    if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
3198198398Srdivacky      if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
3199198092Srdivacky        // No conversion functions in incomplete types.
3200198092Srdivacky        return;
3201198092Srdivacky      }
3202198092Srdivacky
3203193326Sed      CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3204199990Srdivacky      const UnresolvedSet *Conversions
3205198092Srdivacky        = ClassDecl->getVisibleConversionFunctions();
3206199990Srdivacky      for (UnresolvedSet::iterator I = Conversions->begin(),
3207199990Srdivacky             E = Conversions->end(); I != E; ++I) {
3208198092Srdivacky
3209198092Srdivacky        // Skip conversion function templates; they don't tell us anything
3210198092Srdivacky        // about which builtin types we can convert to.
3211199990Srdivacky        if (isa<FunctionTemplateDecl>(*I))
3212198092Srdivacky          continue;
3213198092Srdivacky
3214199990Srdivacky        CXXConversionDecl *Conv = cast<CXXConversionDecl>(*I);
3215198398Srdivacky        if (AllowExplicitConversions || !Conv->isExplicit()) {
3216198398Srdivacky          AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
3217198398Srdivacky                                VisibleQuals);
3218198398Srdivacky        }
3219193326Sed      }
3220193326Sed    }
3221193326Sed  }
3222193326Sed}
3223193326Sed
3224198092Srdivacky/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3225198092Srdivacky/// the volatile- and non-volatile-qualified assignment operators for the
3226198092Srdivacky/// given type to the candidate set.
3227198092Srdivackystatic void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3228198092Srdivacky                                                   QualType T,
3229198092Srdivacky                                                   Expr **Args,
3230198092Srdivacky                                                   unsigned NumArgs,
3231198092Srdivacky                                    OverloadCandidateSet &CandidateSet) {
3232198092Srdivacky  QualType ParamTypes[2];
3233198092Srdivacky
3234198092Srdivacky  // T& operator=(T&, T)
3235198092Srdivacky  ParamTypes[0] = S.Context.getLValueReferenceType(T);
3236198092Srdivacky  ParamTypes[1] = T;
3237198092Srdivacky  S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3238198092Srdivacky                        /*IsAssignmentOperator=*/true);
3239198092Srdivacky
3240198092Srdivacky  if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3241198092Srdivacky    // volatile T& operator=(volatile T&, T)
3242198092Srdivacky    ParamTypes[0]
3243198092Srdivacky      = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
3244198092Srdivacky    ParamTypes[1] = T;
3245198092Srdivacky    S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3246198092Srdivacky                          /*IsAssignmentOperator=*/true);
3247198092Srdivacky  }
3248198092Srdivacky}
3249198092Srdivacky
3250198893Srdivacky/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3251198893Srdivacky/// if any, found in visible type conversion functions found in ArgExpr's type.
3252198398Srdivackystatic  Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3253198398Srdivacky    Qualifiers VRQuals;
3254198398Srdivacky    const RecordType *TyRec;
3255198398Srdivacky    if (const MemberPointerType *RHSMPType =
3256198398Srdivacky        ArgExpr->getType()->getAs<MemberPointerType>())
3257198398Srdivacky      TyRec = cast<RecordType>(RHSMPType->getClass());
3258198398Srdivacky    else
3259198398Srdivacky      TyRec = ArgExpr->getType()->getAs<RecordType>();
3260198398Srdivacky    if (!TyRec) {
3261198398Srdivacky      // Just to be safe, assume the worst case.
3262198398Srdivacky      VRQuals.addVolatile();
3263198398Srdivacky      VRQuals.addRestrict();
3264198398Srdivacky      return VRQuals;
3265198398Srdivacky    }
3266198398Srdivacky
3267198398Srdivacky    CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3268199990Srdivacky    const UnresolvedSet *Conversions =
3269198893Srdivacky      ClassDecl->getVisibleConversionFunctions();
3270198398Srdivacky
3271199990Srdivacky    for (UnresolvedSet::iterator I = Conversions->begin(),
3272199990Srdivacky           E = Conversions->end(); I != E; ++I) {
3273199990Srdivacky      if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*I)) {
3274198398Srdivacky        QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3275198398Srdivacky        if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3276198398Srdivacky          CanTy = ResTypeRef->getPointeeType();
3277198398Srdivacky        // Need to go down the pointer/mempointer chain and add qualifiers
3278198398Srdivacky        // as see them.
3279198398Srdivacky        bool done = false;
3280198398Srdivacky        while (!done) {
3281198398Srdivacky          if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3282198398Srdivacky            CanTy = ResTypePtr->getPointeeType();
3283198398Srdivacky          else if (const MemberPointerType *ResTypeMPtr =
3284198398Srdivacky                CanTy->getAs<MemberPointerType>())
3285198398Srdivacky            CanTy = ResTypeMPtr->getPointeeType();
3286198398Srdivacky          else
3287198398Srdivacky            done = true;
3288198398Srdivacky          if (CanTy.isVolatileQualified())
3289198398Srdivacky            VRQuals.addVolatile();
3290198398Srdivacky          if (CanTy.isRestrictQualified())
3291198398Srdivacky            VRQuals.addRestrict();
3292198398Srdivacky          if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3293198398Srdivacky            return VRQuals;
3294198398Srdivacky        }
3295198398Srdivacky      }
3296198398Srdivacky    }
3297198398Srdivacky    return VRQuals;
3298198398Srdivacky}
3299198398Srdivacky
3300193326Sed/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3301193326Sed/// operator overloads to the candidate set (C++ [over.built]), based
3302193326Sed/// on the operator @p Op and the arguments given. For example, if the
3303193326Sed/// operator is a binary '+', this routine might add "int
3304193326Sed/// operator+(int, int)" to cover integer addition.
3305193326Sedvoid
3306198092SrdivackySema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
3307198398Srdivacky                                   SourceLocation OpLoc,
3308193326Sed                                   Expr **Args, unsigned NumArgs,
3309193326Sed                                   OverloadCandidateSet& CandidateSet) {
3310193326Sed  // The set of "promoted arithmetic types", which are the arithmetic
3311193326Sed  // types are that preserved by promotion (C++ [over.built]p2). Note
3312193326Sed  // that the first few of these types are the promoted integral
3313193326Sed  // types; these types need to be first.
3314193326Sed  // FIXME: What about complex?
3315193326Sed  const unsigned FirstIntegralType = 0;
3316193326Sed  const unsigned LastIntegralType = 13;
3317198092Srdivacky  const unsigned FirstPromotedIntegralType = 7,
3318193326Sed                 LastPromotedIntegralType = 13;
3319193326Sed  const unsigned FirstPromotedArithmeticType = 7,
3320193326Sed                 LastPromotedArithmeticType = 16;
3321193326Sed  const unsigned NumArithmeticTypes = 16;
3322193326Sed  QualType ArithmeticTypes[NumArithmeticTypes] = {
3323193326Sed    Context.BoolTy, Context.CharTy, Context.WCharTy,
3324198092Srdivacky// FIXME:   Context.Char16Ty, Context.Char32Ty,
3325193326Sed    Context.SignedCharTy, Context.ShortTy,
3326193326Sed    Context.UnsignedCharTy, Context.UnsignedShortTy,
3327193326Sed    Context.IntTy, Context.LongTy, Context.LongLongTy,
3328193326Sed    Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3329193326Sed    Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3330193326Sed  };
3331198398Srdivacky  assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3332198398Srdivacky         "Invalid first promoted integral type");
3333198398Srdivacky  assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3334198398Srdivacky           == Context.UnsignedLongLongTy &&
3335198398Srdivacky         "Invalid last promoted integral type");
3336198398Srdivacky  assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3337198398Srdivacky         "Invalid first promoted arithmetic type");
3338198398Srdivacky  assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3339198398Srdivacky            == Context.LongDoubleTy &&
3340198398Srdivacky         "Invalid last promoted arithmetic type");
3341198398Srdivacky
3342193326Sed  // Find all of the types that the arguments can convert to, but only
3343193326Sed  // if the operator we're looking at has built-in operator candidates
3344193326Sed  // that make use of these types.
3345198398Srdivacky  Qualifiers VisibleTypeConversionsQuals;
3346198398Srdivacky  VisibleTypeConversionsQuals.addConst();
3347198398Srdivacky  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3348198398Srdivacky    VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3349198398Srdivacky
3350198092Srdivacky  BuiltinCandidateTypeSet CandidateTypes(*this);
3351193326Sed  if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3352193326Sed      Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
3353193326Sed      Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
3354193326Sed      Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
3355193326Sed      Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
3356193326Sed      (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
3357193326Sed    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3358193326Sed      CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3359198398Srdivacky                                           OpLoc,
3360193326Sed                                           true,
3361193326Sed                                           (Op == OO_Exclaim ||
3362193326Sed                                            Op == OO_AmpAmp ||
3363198398Srdivacky                                            Op == OO_PipePipe),
3364198398Srdivacky                                           VisibleTypeConversionsQuals);
3365193326Sed  }
3366193326Sed
3367193326Sed  bool isComparison = false;
3368193326Sed  switch (Op) {
3369193326Sed  case OO_None:
3370193326Sed  case NUM_OVERLOADED_OPERATORS:
3371193326Sed    assert(false && "Expected an overloaded operator");
3372193326Sed    break;
3373193326Sed
3374193326Sed  case OO_Star: // '*' is either unary or binary
3375198092Srdivacky    if (NumArgs == 1)
3376193326Sed      goto UnaryStar;
3377193326Sed    else
3378193326Sed      goto BinaryStar;
3379193326Sed    break;
3380193326Sed
3381193326Sed  case OO_Plus: // '+' is either unary or binary
3382193326Sed    if (NumArgs == 1)
3383193326Sed      goto UnaryPlus;
3384193326Sed    else
3385193326Sed      goto BinaryPlus;
3386193326Sed    break;
3387193326Sed
3388193326Sed  case OO_Minus: // '-' is either unary or binary
3389193326Sed    if (NumArgs == 1)
3390193326Sed      goto UnaryMinus;
3391193326Sed    else
3392193326Sed      goto BinaryMinus;
3393193326Sed    break;
3394193326Sed
3395193326Sed  case OO_Amp: // '&' is either unary or binary
3396193326Sed    if (NumArgs == 1)
3397193326Sed      goto UnaryAmp;
3398193326Sed    else
3399193326Sed      goto BinaryAmp;
3400193326Sed
3401193326Sed  case OO_PlusPlus:
3402193326Sed  case OO_MinusMinus:
3403193326Sed    // C++ [over.built]p3:
3404193326Sed    //
3405193326Sed    //   For every pair (T, VQ), where T is an arithmetic type, and VQ
3406193326Sed    //   is either volatile or empty, there exist candidate operator
3407193326Sed    //   functions of the form
3408193326Sed    //
3409193326Sed    //       VQ T&      operator++(VQ T&);
3410193326Sed    //       T          operator++(VQ T&, int);
3411193326Sed    //
3412193326Sed    // C++ [over.built]p4:
3413193326Sed    //
3414193326Sed    //   For every pair (T, VQ), where T is an arithmetic type other
3415193326Sed    //   than bool, and VQ is either volatile or empty, there exist
3416193326Sed    //   candidate operator functions of the form
3417193326Sed    //
3418193326Sed    //       VQ T&      operator--(VQ T&);
3419193326Sed    //       T          operator--(VQ T&, int);
3420198092Srdivacky    for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
3421193326Sed         Arith < NumArithmeticTypes; ++Arith) {
3422193326Sed      QualType ArithTy = ArithmeticTypes[Arith];
3423198092Srdivacky      QualType ParamTypes[2]
3424193326Sed        = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
3425193326Sed
3426193326Sed      // Non-volatile version.
3427193326Sed      if (NumArgs == 1)
3428193326Sed        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3429193326Sed      else
3430193326Sed        AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3431198398Srdivacky      // heuristic to reduce number of builtin candidates in the set.
3432198398Srdivacky      // Add volatile version only if there are conversions to a volatile type.
3433198398Srdivacky      if (VisibleTypeConversionsQuals.hasVolatile()) {
3434198398Srdivacky        // Volatile version
3435198398Srdivacky        ParamTypes[0]
3436198398Srdivacky          = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3437198398Srdivacky        if (NumArgs == 1)
3438198398Srdivacky          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3439198398Srdivacky        else
3440198398Srdivacky          AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3441198398Srdivacky      }
3442193326Sed    }
3443193326Sed
3444193326Sed    // C++ [over.built]p5:
3445193326Sed    //
3446193326Sed    //   For every pair (T, VQ), where T is a cv-qualified or
3447193326Sed    //   cv-unqualified object type, and VQ is either volatile or
3448193326Sed    //   empty, there exist candidate operator functions of the form
3449193326Sed    //
3450193326Sed    //       T*VQ&      operator++(T*VQ&);
3451193326Sed    //       T*VQ&      operator--(T*VQ&);
3452193326Sed    //       T*         operator++(T*VQ&, int);
3453193326Sed    //       T*         operator--(T*VQ&, int);
3454193326Sed    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3455193326Sed         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3456193326Sed      // Skip pointer types that aren't pointers to object types.
3457198092Srdivacky      if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
3458193326Sed        continue;
3459193326Sed
3460198092Srdivacky      QualType ParamTypes[2] = {
3461198092Srdivacky        Context.getLValueReferenceType(*Ptr), Context.IntTy
3462193326Sed      };
3463198092Srdivacky
3464193326Sed      // Without volatile
3465193326Sed      if (NumArgs == 1)
3466193326Sed        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3467193326Sed      else
3468193326Sed        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3469193326Sed
3470198398Srdivacky      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3471198398Srdivacky          VisibleTypeConversionsQuals.hasVolatile()) {
3472193326Sed        // With volatile
3473198092Srdivacky        ParamTypes[0]
3474198092Srdivacky          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3475193326Sed        if (NumArgs == 1)
3476193326Sed          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3477193326Sed        else
3478193326Sed          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3479193326Sed      }
3480193326Sed    }
3481193326Sed    break;
3482193326Sed
3483193326Sed  UnaryStar:
3484193326Sed    // C++ [over.built]p6:
3485193326Sed    //   For every cv-qualified or cv-unqualified object type T, there
3486193326Sed    //   exist candidate operator functions of the form
3487193326Sed    //
3488193326Sed    //       T&         operator*(T*);
3489193326Sed    //
3490193326Sed    // C++ [over.built]p7:
3491193326Sed    //   For every function type T, there exist candidate operator
3492193326Sed    //   functions of the form
3493193326Sed    //       T&         operator*(T*);
3494193326Sed    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3495193326Sed         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3496193326Sed      QualType ParamTy = *Ptr;
3497198092Srdivacky      QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
3498198092Srdivacky      AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
3499193326Sed                          &ParamTy, Args, 1, CandidateSet);
3500193326Sed    }
3501193326Sed    break;
3502193326Sed
3503193326Sed  UnaryPlus:
3504193326Sed    // C++ [over.built]p8:
3505193326Sed    //   For every type T, there exist candidate operator functions of
3506193326Sed    //   the form
3507193326Sed    //
3508193326Sed    //       T*         operator+(T*);
3509193326Sed    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3510193326Sed         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3511193326Sed      QualType ParamTy = *Ptr;
3512193326Sed      AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3513193326Sed    }
3514198092Srdivacky
3515193326Sed    // Fall through
3516193326Sed
3517193326Sed  UnaryMinus:
3518193326Sed    // C++ [over.built]p9:
3519193326Sed    //  For every promoted arithmetic type T, there exist candidate
3520193326Sed    //  operator functions of the form
3521193326Sed    //
3522193326Sed    //       T         operator+(T);
3523193326Sed    //       T         operator-(T);
3524198092Srdivacky    for (unsigned Arith = FirstPromotedArithmeticType;
3525193326Sed         Arith < LastPromotedArithmeticType; ++Arith) {
3526193326Sed      QualType ArithTy = ArithmeticTypes[Arith];
3527193326Sed      AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3528193326Sed    }
3529193326Sed    break;
3530193326Sed
3531193326Sed  case OO_Tilde:
3532193326Sed    // C++ [over.built]p10:
3533193326Sed    //   For every promoted integral type T, there exist candidate
3534193326Sed    //   operator functions of the form
3535193326Sed    //
3536193326Sed    //        T         operator~(T);
3537198092Srdivacky    for (unsigned Int = FirstPromotedIntegralType;
3538193326Sed         Int < LastPromotedIntegralType; ++Int) {
3539193326Sed      QualType IntTy = ArithmeticTypes[Int];
3540193326Sed      AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3541193326Sed    }
3542193326Sed    break;
3543193326Sed
3544193326Sed  case OO_New:
3545193326Sed  case OO_Delete:
3546193326Sed  case OO_Array_New:
3547193326Sed  case OO_Array_Delete:
3548193326Sed  case OO_Call:
3549193326Sed    assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
3550193326Sed    break;
3551193326Sed
3552193326Sed  case OO_Comma:
3553193326Sed  UnaryAmp:
3554193326Sed  case OO_Arrow:
3555193326Sed    // C++ [over.match.oper]p3:
3556193326Sed    //   -- For the operator ',', the unary operator '&', or the
3557193326Sed    //      operator '->', the built-in candidates set is empty.
3558193326Sed    break;
3559193326Sed
3560198092Srdivacky  case OO_EqualEqual:
3561198092Srdivacky  case OO_ExclaimEqual:
3562198092Srdivacky    // C++ [over.match.oper]p16:
3563198092Srdivacky    //   For every pointer to member type T, there exist candidate operator
3564198092Srdivacky    //   functions of the form
3565198092Srdivacky    //
3566198092Srdivacky    //        bool operator==(T,T);
3567198092Srdivacky    //        bool operator!=(T,T);
3568198092Srdivacky    for (BuiltinCandidateTypeSet::iterator
3569198092Srdivacky           MemPtr = CandidateTypes.member_pointer_begin(),
3570198092Srdivacky           MemPtrEnd = CandidateTypes.member_pointer_end();
3571198092Srdivacky         MemPtr != MemPtrEnd;
3572198092Srdivacky         ++MemPtr) {
3573198092Srdivacky      QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3574198092Srdivacky      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3575198092Srdivacky    }
3576198092Srdivacky
3577198092Srdivacky    // Fall through
3578198092Srdivacky
3579193326Sed  case OO_Less:
3580193326Sed  case OO_Greater:
3581193326Sed  case OO_LessEqual:
3582193326Sed  case OO_GreaterEqual:
3583193326Sed    // C++ [over.built]p15:
3584193326Sed    //
3585193326Sed    //   For every pointer or enumeration type T, there exist
3586193326Sed    //   candidate operator functions of the form
3587198092Srdivacky    //
3588193326Sed    //        bool       operator<(T, T);
3589193326Sed    //        bool       operator>(T, T);
3590193326Sed    //        bool       operator<=(T, T);
3591193326Sed    //        bool       operator>=(T, T);
3592193326Sed    //        bool       operator==(T, T);
3593193326Sed    //        bool       operator!=(T, T);
3594193326Sed    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3595193326Sed         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3596193326Sed      QualType ParamTypes[2] = { *Ptr, *Ptr };
3597193326Sed      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3598193326Sed    }
3599198092Srdivacky    for (BuiltinCandidateTypeSet::iterator Enum
3600193326Sed           = CandidateTypes.enumeration_begin();
3601193326Sed         Enum != CandidateTypes.enumeration_end(); ++Enum) {
3602193326Sed      QualType ParamTypes[2] = { *Enum, *Enum };
3603193326Sed      AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3604193326Sed    }
3605193326Sed
3606193326Sed    // Fall through.
3607193326Sed    isComparison = true;
3608193326Sed
3609193326Sed  BinaryPlus:
3610193326Sed  BinaryMinus:
3611193326Sed    if (!isComparison) {
3612193326Sed      // We didn't fall through, so we must have OO_Plus or OO_Minus.
3613193326Sed
3614193326Sed      // C++ [over.built]p13:
3615193326Sed      //
3616193326Sed      //   For every cv-qualified or cv-unqualified object type T
3617193326Sed      //   there exist candidate operator functions of the form
3618198092Srdivacky      //
3619193326Sed      //      T*         operator+(T*, ptrdiff_t);
3620193326Sed      //      T&         operator[](T*, ptrdiff_t);    [BELOW]
3621193326Sed      //      T*         operator-(T*, ptrdiff_t);
3622193326Sed      //      T*         operator+(ptrdiff_t, T*);
3623193326Sed      //      T&         operator[](ptrdiff_t, T*);    [BELOW]
3624193326Sed      //
3625193326Sed      // C++ [over.built]p14:
3626193326Sed      //
3627193326Sed      //   For every T, where T is a pointer to object type, there
3628193326Sed      //   exist candidate operator functions of the form
3629193326Sed      //
3630193326Sed      //      ptrdiff_t  operator-(T, T);
3631198092Srdivacky      for (BuiltinCandidateTypeSet::iterator Ptr
3632193326Sed             = CandidateTypes.pointer_begin();
3633193326Sed           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3634193326Sed        QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3635193326Sed
3636193326Sed        // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3637193326Sed        AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3638193326Sed
3639193326Sed        if (Op == OO_Plus) {
3640193326Sed          // T* operator+(ptrdiff_t, T*);
3641193326Sed          ParamTypes[0] = ParamTypes[1];
3642193326Sed          ParamTypes[1] = *Ptr;
3643193326Sed          AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3644193326Sed        } else {
3645193326Sed          // ptrdiff_t operator-(T, T);
3646193326Sed          ParamTypes[1] = *Ptr;
3647193326Sed          AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3648193326Sed                              Args, 2, CandidateSet);
3649193326Sed        }
3650193326Sed      }
3651193326Sed    }
3652193326Sed    // Fall through
3653193326Sed
3654193326Sed  case OO_Slash:
3655193326Sed  BinaryStar:
3656193326Sed  Conditional:
3657193326Sed    // C++ [over.built]p12:
3658193326Sed    //
3659193326Sed    //   For every pair of promoted arithmetic types L and R, there
3660193326Sed    //   exist candidate operator functions of the form
3661193326Sed    //
3662193326Sed    //        LR         operator*(L, R);
3663193326Sed    //        LR         operator/(L, R);
3664193326Sed    //        LR         operator+(L, R);
3665193326Sed    //        LR         operator-(L, R);
3666193326Sed    //        bool       operator<(L, R);
3667193326Sed    //        bool       operator>(L, R);
3668193326Sed    //        bool       operator<=(L, R);
3669193326Sed    //        bool       operator>=(L, R);
3670193326Sed    //        bool       operator==(L, R);
3671193326Sed    //        bool       operator!=(L, R);
3672193326Sed    //
3673193326Sed    //   where LR is the result of the usual arithmetic conversions
3674193326Sed    //   between types L and R.
3675193326Sed    //
3676193326Sed    // C++ [over.built]p24:
3677193326Sed    //
3678193326Sed    //   For every pair of promoted arithmetic types L and R, there exist
3679193326Sed    //   candidate operator functions of the form
3680193326Sed    //
3681193326Sed    //        LR       operator?(bool, L, R);
3682193326Sed    //
3683193326Sed    //   where LR is the result of the usual arithmetic conversions
3684193326Sed    //   between types L and R.
3685193326Sed    // Our candidates ignore the first parameter.
3686198092Srdivacky    for (unsigned Left = FirstPromotedArithmeticType;
3687193326Sed         Left < LastPromotedArithmeticType; ++Left) {
3688198092Srdivacky      for (unsigned Right = FirstPromotedArithmeticType;
3689193326Sed           Right < LastPromotedArithmeticType; ++Right) {
3690193326Sed        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3691198092Srdivacky        QualType Result
3692198092Srdivacky          = isComparison
3693198092Srdivacky          ? Context.BoolTy
3694198092Srdivacky          : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3695193326Sed        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3696193326Sed      }
3697193326Sed    }
3698193326Sed    break;
3699193326Sed
3700193326Sed  case OO_Percent:
3701193326Sed  BinaryAmp:
3702193326Sed  case OO_Caret:
3703193326Sed  case OO_Pipe:
3704193326Sed  case OO_LessLess:
3705193326Sed  case OO_GreaterGreater:
3706193326Sed    // C++ [over.built]p17:
3707193326Sed    //
3708193326Sed    //   For every pair of promoted integral types L and R, there
3709193326Sed    //   exist candidate operator functions of the form
3710193326Sed    //
3711193326Sed    //      LR         operator%(L, R);
3712193326Sed    //      LR         operator&(L, R);
3713193326Sed    //      LR         operator^(L, R);
3714193326Sed    //      LR         operator|(L, R);
3715193326Sed    //      L          operator<<(L, R);
3716193326Sed    //      L          operator>>(L, R);
3717193326Sed    //
3718193326Sed    //   where LR is the result of the usual arithmetic conversions
3719193326Sed    //   between types L and R.
3720198092Srdivacky    for (unsigned Left = FirstPromotedIntegralType;
3721193326Sed         Left < LastPromotedIntegralType; ++Left) {
3722198092Srdivacky      for (unsigned Right = FirstPromotedIntegralType;
3723193326Sed           Right < LastPromotedIntegralType; ++Right) {
3724193326Sed        QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3725193326Sed        QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3726193326Sed            ? LandR[0]
3727198092Srdivacky            : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
3728193326Sed        AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3729193326Sed      }
3730193326Sed    }
3731193326Sed    break;
3732193326Sed
3733193326Sed  case OO_Equal:
3734193326Sed    // C++ [over.built]p20:
3735193326Sed    //
3736193326Sed    //   For every pair (T, VQ), where T is an enumeration or
3737198092Srdivacky    //   pointer to member type and VQ is either volatile or
3738193326Sed    //   empty, there exist candidate operator functions of the form
3739193326Sed    //
3740193326Sed    //        VQ T&      operator=(VQ T&, T);
3741198092Srdivacky    for (BuiltinCandidateTypeSet::iterator
3742198092Srdivacky           Enum = CandidateTypes.enumeration_begin(),
3743198092Srdivacky           EnumEnd = CandidateTypes.enumeration_end();
3744198092Srdivacky         Enum != EnumEnd; ++Enum)
3745198092Srdivacky      AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
3746198092Srdivacky                                             CandidateSet);
3747198092Srdivacky    for (BuiltinCandidateTypeSet::iterator
3748198092Srdivacky           MemPtr = CandidateTypes.member_pointer_begin(),
3749198092Srdivacky         MemPtrEnd = CandidateTypes.member_pointer_end();
3750198092Srdivacky         MemPtr != MemPtrEnd; ++MemPtr)
3751198092Srdivacky      AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
3752198092Srdivacky                                             CandidateSet);
3753198092Srdivacky      // Fall through.
3754193326Sed
3755193326Sed  case OO_PlusEqual:
3756193326Sed  case OO_MinusEqual:
3757193326Sed    // C++ [over.built]p19:
3758193326Sed    //
3759193326Sed    //   For every pair (T, VQ), where T is any type and VQ is either
3760193326Sed    //   volatile or empty, there exist candidate operator functions
3761193326Sed    //   of the form
3762193326Sed    //
3763193326Sed    //        T*VQ&      operator=(T*VQ&, T*);
3764193326Sed    //
3765193326Sed    // C++ [over.built]p21:
3766193326Sed    //
3767193326Sed    //   For every pair (T, VQ), where T is a cv-qualified or
3768193326Sed    //   cv-unqualified object type and VQ is either volatile or
3769193326Sed    //   empty, there exist candidate operator functions of the form
3770193326Sed    //
3771193326Sed    //        T*VQ&      operator+=(T*VQ&, ptrdiff_t);
3772193326Sed    //        T*VQ&      operator-=(T*VQ&, ptrdiff_t);
3773193326Sed    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3774193326Sed         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3775193326Sed      QualType ParamTypes[2];
3776193326Sed      ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3777193326Sed
3778193326Sed      // non-volatile version
3779193326Sed      ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
3780193326Sed      AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3781193326Sed                          /*IsAssigmentOperator=*/Op == OO_Equal);
3782193326Sed
3783198398Srdivacky      if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3784198398Srdivacky          VisibleTypeConversionsQuals.hasVolatile()) {
3785193326Sed        // volatile version
3786198092Srdivacky        ParamTypes[0]
3787198092Srdivacky          = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
3788193326Sed        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3789193326Sed                            /*IsAssigmentOperator=*/Op == OO_Equal);
3790193326Sed      }
3791193326Sed    }
3792193326Sed    // Fall through.
3793193326Sed
3794193326Sed  case OO_StarEqual:
3795193326Sed  case OO_SlashEqual:
3796193326Sed    // C++ [over.built]p18:
3797193326Sed    //
3798193326Sed    //   For every triple (L, VQ, R), where L is an arithmetic type,
3799193326Sed    //   VQ is either volatile or empty, and R is a promoted
3800193326Sed    //   arithmetic type, there exist candidate operator functions of
3801193326Sed    //   the form
3802193326Sed    //
3803193326Sed    //        VQ L&      operator=(VQ L&, R);
3804193326Sed    //        VQ L&      operator*=(VQ L&, R);
3805193326Sed    //        VQ L&      operator/=(VQ L&, R);
3806193326Sed    //        VQ L&      operator+=(VQ L&, R);
3807193326Sed    //        VQ L&      operator-=(VQ L&, R);
3808193326Sed    for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
3809198092Srdivacky      for (unsigned Right = FirstPromotedArithmeticType;
3810193326Sed           Right < LastPromotedArithmeticType; ++Right) {
3811193326Sed        QualType ParamTypes[2];
3812193326Sed        ParamTypes[1] = ArithmeticTypes[Right];
3813193326Sed
3814193326Sed        // Add this built-in operator as a candidate (VQ is empty).
3815193326Sed        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3816193326Sed        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3817193326Sed                            /*IsAssigmentOperator=*/Op == OO_Equal);
3818193326Sed
3819193326Sed        // Add this built-in operator as a candidate (VQ is 'volatile').
3820198398Srdivacky        if (VisibleTypeConversionsQuals.hasVolatile()) {
3821198398Srdivacky          ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3822198398Srdivacky          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3823198398Srdivacky          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3824198398Srdivacky                              /*IsAssigmentOperator=*/Op == OO_Equal);
3825198398Srdivacky        }
3826193326Sed      }
3827193326Sed    }
3828193326Sed    break;
3829193326Sed
3830193326Sed  case OO_PercentEqual:
3831193326Sed  case OO_LessLessEqual:
3832193326Sed  case OO_GreaterGreaterEqual:
3833193326Sed  case OO_AmpEqual:
3834193326Sed  case OO_CaretEqual:
3835193326Sed  case OO_PipeEqual:
3836193326Sed    // C++ [over.built]p22:
3837193326Sed    //
3838193326Sed    //   For every triple (L, VQ, R), where L is an integral type, VQ
3839193326Sed    //   is either volatile or empty, and R is a promoted integral
3840193326Sed    //   type, there exist candidate operator functions of the form
3841193326Sed    //
3842193326Sed    //        VQ L&       operator%=(VQ L&, R);
3843193326Sed    //        VQ L&       operator<<=(VQ L&, R);
3844193326Sed    //        VQ L&       operator>>=(VQ L&, R);
3845193326Sed    //        VQ L&       operator&=(VQ L&, R);
3846193326Sed    //        VQ L&       operator^=(VQ L&, R);
3847193326Sed    //        VQ L&       operator|=(VQ L&, R);
3848193326Sed    for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
3849198092Srdivacky      for (unsigned Right = FirstPromotedIntegralType;
3850193326Sed           Right < LastPromotedIntegralType; ++Right) {
3851193326Sed        QualType ParamTypes[2];
3852193326Sed        ParamTypes[1] = ArithmeticTypes[Right];
3853193326Sed
3854193326Sed        // Add this built-in operator as a candidate (VQ is empty).
3855193326Sed        ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
3856193326Sed        AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3857198398Srdivacky        if (VisibleTypeConversionsQuals.hasVolatile()) {
3858198398Srdivacky          // Add this built-in operator as a candidate (VQ is 'volatile').
3859198398Srdivacky          ParamTypes[0] = ArithmeticTypes[Left];
3860198398Srdivacky          ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3861198398Srdivacky          ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3862198398Srdivacky          AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3863198398Srdivacky        }
3864193326Sed      }
3865193326Sed    }
3866193326Sed    break;
3867193326Sed
3868193326Sed  case OO_Exclaim: {
3869193326Sed    // C++ [over.operator]p23:
3870193326Sed    //
3871193326Sed    //   There also exist candidate operator functions of the form
3872193326Sed    //
3873198092Srdivacky    //        bool        operator!(bool);
3874193326Sed    //        bool        operator&&(bool, bool);     [BELOW]
3875193326Sed    //        bool        operator||(bool, bool);     [BELOW]
3876193326Sed    QualType ParamTy = Context.BoolTy;
3877193326Sed    AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3878193326Sed                        /*IsAssignmentOperator=*/false,
3879193326Sed                        /*NumContextualBoolArguments=*/1);
3880193326Sed    break;
3881193326Sed  }
3882193326Sed
3883193326Sed  case OO_AmpAmp:
3884193326Sed  case OO_PipePipe: {
3885193326Sed    // C++ [over.operator]p23:
3886193326Sed    //
3887193326Sed    //   There also exist candidate operator functions of the form
3888193326Sed    //
3889193326Sed    //        bool        operator!(bool);            [ABOVE]
3890193326Sed    //        bool        operator&&(bool, bool);
3891193326Sed    //        bool        operator||(bool, bool);
3892193326Sed    QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
3893193326Sed    AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3894193326Sed                        /*IsAssignmentOperator=*/false,
3895193326Sed                        /*NumContextualBoolArguments=*/2);
3896193326Sed    break;
3897193326Sed  }
3898193326Sed
3899193326Sed  case OO_Subscript:
3900193326Sed    // C++ [over.built]p13:
3901193326Sed    //
3902193326Sed    //   For every cv-qualified or cv-unqualified object type T there
3903193326Sed    //   exist candidate operator functions of the form
3904198092Srdivacky    //
3905193326Sed    //        T*         operator+(T*, ptrdiff_t);     [ABOVE]
3906193326Sed    //        T&         operator[](T*, ptrdiff_t);
3907193326Sed    //        T*         operator-(T*, ptrdiff_t);     [ABOVE]
3908193326Sed    //        T*         operator+(ptrdiff_t, T*);     [ABOVE]
3909193326Sed    //        T&         operator[](ptrdiff_t, T*);
3910193326Sed    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3911193326Sed         Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3912193326Sed      QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3913198092Srdivacky      QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
3914193326Sed      QualType ResultTy = Context.getLValueReferenceType(PointeeType);
3915193326Sed
3916193326Sed      // T& operator[](T*, ptrdiff_t)
3917193326Sed      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3918193326Sed
3919193326Sed      // T& operator[](ptrdiff_t, T*);
3920193326Sed      ParamTypes[0] = ParamTypes[1];
3921193326Sed      ParamTypes[1] = *Ptr;
3922193326Sed      AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3923193326Sed    }
3924193326Sed    break;
3925193326Sed
3926193326Sed  case OO_ArrowStar:
3927198092Srdivacky    // C++ [over.built]p11:
3928198092Srdivacky    //    For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3929198092Srdivacky    //    C1 is the same type as C2 or is a derived class of C2, T is an object
3930198092Srdivacky    //    type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3931198092Srdivacky    //    there exist candidate operator functions of the form
3932198092Srdivacky    //    CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3933198092Srdivacky    //    where CV12 is the union of CV1 and CV2.
3934198092Srdivacky    {
3935198092Srdivacky      for (BuiltinCandidateTypeSet::iterator Ptr =
3936198092Srdivacky             CandidateTypes.pointer_begin();
3937198092Srdivacky           Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3938198092Srdivacky        QualType C1Ty = (*Ptr);
3939198092Srdivacky        QualType C1;
3940198092Srdivacky        QualifierCollector Q1;
3941198092Srdivacky        if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
3942198092Srdivacky          C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
3943198092Srdivacky          if (!isa<RecordType>(C1))
3944198092Srdivacky            continue;
3945198398Srdivacky          // heuristic to reduce number of builtin candidates in the set.
3946198398Srdivacky          // Add volatile/restrict version only if there are conversions to a
3947198398Srdivacky          // volatile/restrict type.
3948198398Srdivacky          if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3949198398Srdivacky            continue;
3950198398Srdivacky          if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3951198398Srdivacky            continue;
3952198092Srdivacky        }
3953198092Srdivacky        for (BuiltinCandidateTypeSet::iterator
3954198092Srdivacky             MemPtr = CandidateTypes.member_pointer_begin(),
3955198092Srdivacky             MemPtrEnd = CandidateTypes.member_pointer_end();
3956198092Srdivacky             MemPtr != MemPtrEnd; ++MemPtr) {
3957198092Srdivacky          const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3958198092Srdivacky          QualType C2 = QualType(mptr->getClass(), 0);
3959198092Srdivacky          C2 = C2.getUnqualifiedType();
3960198092Srdivacky          if (C1 != C2 && !IsDerivedFrom(C1, C2))
3961198092Srdivacky            break;
3962198092Srdivacky          QualType ParamTypes[2] = { *Ptr, *MemPtr };
3963198092Srdivacky          // build CV12 T&
3964198092Srdivacky          QualType T = mptr->getPointeeType();
3965198398Srdivacky          if (!VisibleTypeConversionsQuals.hasVolatile() &&
3966198398Srdivacky              T.isVolatileQualified())
3967198398Srdivacky            continue;
3968198398Srdivacky          if (!VisibleTypeConversionsQuals.hasRestrict() &&
3969198398Srdivacky              T.isRestrictQualified())
3970198398Srdivacky            continue;
3971198092Srdivacky          T = Q1.apply(T);
3972198092Srdivacky          QualType ResultTy = Context.getLValueReferenceType(T);
3973198092Srdivacky          AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3974198092Srdivacky        }
3975198092Srdivacky      }
3976198092Srdivacky    }
3977193326Sed    break;
3978193326Sed
3979193326Sed  case OO_Conditional:
3980193326Sed    // Note that we don't consider the first argument, since it has been
3981193326Sed    // contextually converted to bool long ago. The candidates below are
3982193326Sed    // therefore added as binary.
3983193326Sed    //
3984193326Sed    // C++ [over.built]p24:
3985193326Sed    //   For every type T, where T is a pointer or pointer-to-member type,
3986193326Sed    //   there exist candidate operator functions of the form
3987193326Sed    //
3988193326Sed    //        T        operator?(bool, T, T);
3989193326Sed    //
3990193326Sed    for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3991193326Sed         E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3992193326Sed      QualType ParamTypes[2] = { *Ptr, *Ptr };
3993193326Sed      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3994193326Sed    }
3995193326Sed    for (BuiltinCandidateTypeSet::iterator Ptr =
3996193326Sed           CandidateTypes.member_pointer_begin(),
3997193326Sed         E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3998193326Sed      QualType ParamTypes[2] = { *Ptr, *Ptr };
3999193326Sed      AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4000193326Sed    }
4001193326Sed    goto Conditional;
4002193326Sed  }
4003193326Sed}
4004193326Sed
4005193326Sed/// \brief Add function candidates found via argument-dependent lookup
4006193326Sed/// to the set of overloading candidates.
4007193326Sed///
4008193326Sed/// This routine performs argument-dependent name lookup based on the
4009193326Sed/// given function name (which may also be an operator name) and adds
4010193326Sed/// all of the overload candidates found by ADL to the overload
4011193326Sed/// candidate set (C++ [basic.lookup.argdep]).
4012198092Srdivackyvoid
4013193326SedSema::AddArgumentDependentLookupCandidates(DeclarationName Name,
4014193326Sed                                           Expr **Args, unsigned NumArgs,
4015199990Srdivacky                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4016198092Srdivacky                                           OverloadCandidateSet& CandidateSet,
4017198092Srdivacky                                           bool PartialOverloading) {
4018193326Sed  FunctionSet Functions;
4019193326Sed
4020198092Srdivacky  // FIXME: Should we be trafficking in canonical function decls throughout?
4021198092Srdivacky
4022193326Sed  // Record all of the function candidates that we've already
4023193326Sed  // added to the overload set, so that we don't add those same
4024193326Sed  // candidates a second time.
4025193326Sed  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4026193326Sed                                   CandEnd = CandidateSet.end();
4027193326Sed       Cand != CandEnd; ++Cand)
4028195341Sed    if (Cand->Function) {
4029193326Sed      Functions.insert(Cand->Function);
4030195341Sed      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4031195341Sed        Functions.insert(FunTmpl);
4032195341Sed    }
4033193326Sed
4034198092Srdivacky  // FIXME: Pass in the explicit template arguments?
4035198893Srdivacky  ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
4036193326Sed
4037193326Sed  // Erase all of the candidates we already knew about.
4038193326Sed  // FIXME: This is suboptimal. Is there a better way?
4039193326Sed  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4040193326Sed                                   CandEnd = CandidateSet.end();
4041193326Sed       Cand != CandEnd; ++Cand)
4042195341Sed    if (Cand->Function) {
4043193326Sed      Functions.erase(Cand->Function);
4044195341Sed      if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
4045195341Sed        Functions.erase(FunTmpl);
4046195341Sed    }
4047193326Sed
4048193326Sed  // For each of the ADL candidates we found, add it to the overload
4049193326Sed  // set.
4050193326Sed  for (FunctionSet::iterator Func = Functions.begin(),
4051193326Sed                          FuncEnd = Functions.end();
4052195341Sed       Func != FuncEnd; ++Func) {
4053198092Srdivacky    if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
4054199990Srdivacky      if (ExplicitTemplateArgs)
4055198092Srdivacky        continue;
4056198092Srdivacky
4057198092Srdivacky      AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
4058198092Srdivacky                           false, false, PartialOverloading);
4059198092Srdivacky    } else
4060198092Srdivacky      AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
4061198092Srdivacky                                   ExplicitTemplateArgs,
4062195341Sed                                   Args, NumArgs, CandidateSet);
4063195341Sed  }
4064193326Sed}
4065193326Sed
4066193326Sed/// isBetterOverloadCandidate - Determines whether the first overload
4067193326Sed/// candidate is a better candidate than the second (C++ 13.3.3p1).
4068198092Srdivackybool
4069193326SedSema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
4070198092Srdivacky                                const OverloadCandidate& Cand2) {
4071193326Sed  // Define viable functions to be better candidates than non-viable
4072193326Sed  // functions.
4073193326Sed  if (!Cand2.Viable)
4074193326Sed    return Cand1.Viable;
4075193326Sed  else if (!Cand1.Viable)
4076193326Sed    return false;
4077193326Sed
4078193326Sed  // C++ [over.match.best]p1:
4079193326Sed  //
4080193326Sed  //   -- if F is a static member function, ICS1(F) is defined such
4081193326Sed  //      that ICS1(F) is neither better nor worse than ICS1(G) for
4082193326Sed  //      any function G, and, symmetrically, ICS1(G) is neither
4083193326Sed  //      better nor worse than ICS1(F).
4084193326Sed  unsigned StartArg = 0;
4085193326Sed  if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4086193326Sed    StartArg = 1;
4087193326Sed
4088198092Srdivacky  // C++ [over.match.best]p1:
4089198092Srdivacky  //   A viable function F1 is defined to be a better function than another
4090198092Srdivacky  //   viable function F2 if for all arguments i, ICSi(F1) is not a worse
4091198092Srdivacky  //   conversion sequence than ICSi(F2), and then...
4092193326Sed  unsigned NumArgs = Cand1.Conversions.size();
4093193326Sed  assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4094193326Sed  bool HasBetterConversion = false;
4095193326Sed  for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
4096193326Sed    switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4097193326Sed                                               Cand2.Conversions[ArgIdx])) {
4098193326Sed    case ImplicitConversionSequence::Better:
4099193326Sed      // Cand1 has a better conversion sequence.
4100193326Sed      HasBetterConversion = true;
4101193326Sed      break;
4102193326Sed
4103193326Sed    case ImplicitConversionSequence::Worse:
4104193326Sed      // Cand1 can't be better than Cand2.
4105193326Sed      return false;
4106193326Sed
4107193326Sed    case ImplicitConversionSequence::Indistinguishable:
4108193326Sed      // Do nothing.
4109193326Sed      break;
4110193326Sed    }
4111193326Sed  }
4112193326Sed
4113198092Srdivacky  //    -- for some argument j, ICSj(F1) is a better conversion sequence than
4114198092Srdivacky  //       ICSj(F2), or, if not that,
4115193326Sed  if (HasBetterConversion)
4116193326Sed    return true;
4117193326Sed
4118198092Srdivacky  //     - F1 is a non-template function and F2 is a function template
4119198092Srdivacky  //       specialization, or, if not that,
4120198092Srdivacky  if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4121198092Srdivacky      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4122198092Srdivacky    return true;
4123193326Sed
4124198092Srdivacky  //   -- F1 and F2 are function template specializations, and the function
4125198092Srdivacky  //      template for F1 is more specialized than the template for F2
4126198092Srdivacky  //      according to the partial ordering rules described in 14.5.5.2, or,
4127198092Srdivacky  //      if not that,
4128198092Srdivacky  if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4129198092Srdivacky      Cand2.Function && Cand2.Function->getPrimaryTemplate())
4130198092Srdivacky    if (FunctionTemplateDecl *BetterTemplate
4131198092Srdivacky          = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4132198092Srdivacky                                       Cand2.Function->getPrimaryTemplate(),
4133198092Srdivacky                       isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4134198092Srdivacky                                                             : TPOC_Call))
4135198092Srdivacky      return BetterTemplate == Cand1.Function->getPrimaryTemplate();
4136198092Srdivacky
4137193326Sed  //   -- the context is an initialization by user-defined conversion
4138193326Sed  //      (see 8.5, 13.3.1.5) and the standard conversion sequence
4139193326Sed  //      from the return type of F1 to the destination type (i.e.,
4140193326Sed  //      the type of the entity being initialized) is a better
4141193326Sed  //      conversion sequence than the standard conversion sequence
4142193326Sed  //      from the return type of F2 to the destination type.
4143198092Srdivacky  if (Cand1.Function && Cand2.Function &&
4144198092Srdivacky      isa<CXXConversionDecl>(Cand1.Function) &&
4145193326Sed      isa<CXXConversionDecl>(Cand2.Function)) {
4146193326Sed    switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4147193326Sed                                               Cand2.FinalConversion)) {
4148193326Sed    case ImplicitConversionSequence::Better:
4149193326Sed      // Cand1 has a better conversion sequence.
4150193326Sed      return true;
4151193326Sed
4152193326Sed    case ImplicitConversionSequence::Worse:
4153193326Sed      // Cand1 can't be better than Cand2.
4154193326Sed      return false;
4155193326Sed
4156193326Sed    case ImplicitConversionSequence::Indistinguishable:
4157193326Sed      // Do nothing
4158193326Sed      break;
4159193326Sed    }
4160193326Sed  }
4161193326Sed
4162193326Sed  return false;
4163193326Sed}
4164193326Sed
4165198092Srdivacky/// \brief Computes the best viable function (C++ 13.3.3)
4166194613Sed/// within an overload candidate set.
4167194613Sed///
4168194613Sed/// \param CandidateSet the set of candidate functions.
4169194613Sed///
4170194613Sed/// \param Loc the location of the function name (or operator symbol) for
4171194613Sed/// which overload resolution occurs.
4172194613Sed///
4173198092Srdivacky/// \param Best f overload resolution was successful or found a deleted
4174194613Sed/// function, Best points to the candidate function found.
4175194613Sed///
4176194613Sed/// \returns The result of overload resolution.
4177200583SrdivackyOverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4178200583Srdivacky                                           SourceLocation Loc,
4179200583Srdivacky                                        OverloadCandidateSet::iterator& Best) {
4180193326Sed  // Find the best viable function.
4181193326Sed  Best = CandidateSet.end();
4182193326Sed  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4183193326Sed       Cand != CandidateSet.end(); ++Cand) {
4184193326Sed    if (Cand->Viable) {
4185193326Sed      if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4186193326Sed        Best = Cand;
4187193326Sed    }
4188193326Sed  }
4189193326Sed
4190193326Sed  // If we didn't find any viable functions, abort.
4191193326Sed  if (Best == CandidateSet.end())
4192193326Sed    return OR_No_Viable_Function;
4193193326Sed
4194193326Sed  // Make sure that this function is better than every other viable
4195193326Sed  // function. If not, we have an ambiguity.
4196193326Sed  for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4197193326Sed       Cand != CandidateSet.end(); ++Cand) {
4198198092Srdivacky    if (Cand->Viable &&
4199193326Sed        Cand != Best &&
4200193326Sed        !isBetterOverloadCandidate(*Best, *Cand)) {
4201193326Sed      Best = CandidateSet.end();
4202193326Sed      return OR_Ambiguous;
4203193326Sed    }
4204193326Sed  }
4205198092Srdivacky
4206193326Sed  // Best is the best viable function.
4207193326Sed  if (Best->Function &&
4208198092Srdivacky      (Best->Function->isDeleted() ||
4209195341Sed       Best->Function->getAttr<UnavailableAttr>()))
4210193326Sed    return OR_Deleted;
4211193326Sed
4212194613Sed  // C++ [basic.def.odr]p2:
4213194613Sed  //   An overloaded function is used if it is selected by overload resolution
4214198092Srdivacky  //   when referred to from a potentially-evaluated expression. [Note: this
4215198092Srdivacky  //   covers calls to named functions (5.2.2), operator overloading
4216194613Sed  //   (clause 13), user-defined conversions (12.3.2), allocation function for
4217194613Sed  //   placement new (5.3.4), as well as non-default initialization (8.5).
4218194613Sed  if (Best->Function)
4219194613Sed    MarkDeclarationReferenced(Loc, Best->Function);
4220193326Sed  return OR_Success;
4221193326Sed}
4222193326Sed
4223193326Sed/// PrintOverloadCandidates - When overload resolution fails, prints
4224193326Sed/// diagnostic messages containing the candidates in the candidate
4225193326Sed/// set. If OnlyViable is true, only viable candidates will be printed.
4226198092Srdivackyvoid
4227193326SedSema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
4228198092Srdivacky                              bool OnlyViable,
4229198092Srdivacky                              const char *Opc,
4230198092Srdivacky                              SourceLocation OpLoc) {
4231193326Sed  OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4232193326Sed                             LastCand = CandidateSet.end();
4233198092Srdivacky  bool Reported = false;
4234193326Sed  for (; Cand != LastCand; ++Cand) {
4235193326Sed    if (Cand->Viable || !OnlyViable) {
4236193326Sed      if (Cand->Function) {
4237193326Sed        if (Cand->Function->isDeleted() ||
4238195341Sed            Cand->Function->getAttr<UnavailableAttr>()) {
4239193326Sed          // Deleted or "unavailable" function.
4240193326Sed          Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4241193326Sed            << Cand->Function->isDeleted();
4242198092Srdivacky        } else if (FunctionTemplateDecl *FunTmpl
4243198092Srdivacky                     = Cand->Function->getPrimaryTemplate()) {
4244198092Srdivacky          // Function template specialization
4245198092Srdivacky          // FIXME: Give a better reason!
4246198092Srdivacky          Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4247198092Srdivacky            << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4248198092Srdivacky                              *Cand->Function->getTemplateSpecializationArgs());
4249193326Sed        } else {
4250193326Sed          // Normal function
4251198092Srdivacky          bool errReported = false;
4252198092Srdivacky          if (!Cand->Viable && Cand->Conversions.size() > 0) {
4253198092Srdivacky            for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4254198092Srdivacky              const ImplicitConversionSequence &Conversion =
4255198092Srdivacky                                                        Cand->Conversions[i];
4256198092Srdivacky              if ((Conversion.ConversionKind !=
4257198092Srdivacky                   ImplicitConversionSequence::BadConversion) ||
4258198092Srdivacky                  Conversion.ConversionFunctionSet.size() == 0)
4259198092Srdivacky                continue;
4260198092Srdivacky              Diag(Cand->Function->getLocation(),
4261198092Srdivacky                   diag::err_ovl_candidate_not_viable) << (i+1);
4262198092Srdivacky              errReported = true;
4263198092Srdivacky              for (int j = Conversion.ConversionFunctionSet.size()-1;
4264198092Srdivacky                   j >= 0; j--) {
4265198092Srdivacky                FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4266198092Srdivacky                Diag(Func->getLocation(), diag::err_ovl_candidate);
4267198092Srdivacky              }
4268198092Srdivacky            }
4269198092Srdivacky          }
4270198092Srdivacky          if (!errReported)
4271198092Srdivacky            Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
4272193326Sed        }
4273193326Sed      } else if (Cand->IsSurrogate) {
4274193326Sed        // Desugar the type of the surrogate down to a function type,
4275193326Sed        // retaining as many typedefs as possible while still showing
4276193326Sed        // the function type (and, therefore, its parameter types).
4277193326Sed        QualType FnType = Cand->Surrogate->getConversionType();
4278193326Sed        bool isLValueReference = false;
4279193326Sed        bool isRValueReference = false;
4280193326Sed        bool isPointer = false;
4281193326Sed        if (const LValueReferenceType *FnTypeRef =
4282198092Srdivacky              FnType->getAs<LValueReferenceType>()) {
4283193326Sed          FnType = FnTypeRef->getPointeeType();
4284193326Sed          isLValueReference = true;
4285193326Sed        } else if (const RValueReferenceType *FnTypeRef =
4286198092Srdivacky                     FnType->getAs<RValueReferenceType>()) {
4287193326Sed          FnType = FnTypeRef->getPointeeType();
4288193326Sed          isRValueReference = true;
4289193326Sed        }
4290198092Srdivacky        if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
4291193326Sed          FnType = FnTypePtr->getPointeeType();
4292193326Sed          isPointer = true;
4293193326Sed        }
4294193326Sed        // Desugar down to a function type.
4295198092Srdivacky        FnType = QualType(FnType->getAs<FunctionType>(), 0);
4296193326Sed        // Reconstruct the pointer/reference as appropriate.
4297193326Sed        if (isPointer) FnType = Context.getPointerType(FnType);
4298193326Sed        if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4299193326Sed        if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
4300193326Sed
4301193326Sed        Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
4302193326Sed          << FnType;
4303198092Srdivacky      } else if (OnlyViable) {
4304198092Srdivacky        assert(Cand->Conversions.size() <= 2 &&
4305198092Srdivacky               "builtin-binary-operator-not-binary");
4306198398Srdivacky        std::string TypeStr("operator");
4307198398Srdivacky        TypeStr += Opc;
4308198398Srdivacky        TypeStr += "(";
4309198398Srdivacky        TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4310198398Srdivacky        if (Cand->Conversions.size() == 1) {
4311198398Srdivacky          TypeStr += ")";
4312198398Srdivacky          Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4313198398Srdivacky        }
4314198398Srdivacky        else {
4315198398Srdivacky          TypeStr += ", ";
4316198398Srdivacky          TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4317198398Srdivacky          TypeStr += ")";
4318198398Srdivacky          Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4319198398Srdivacky        }
4320193326Sed      }
4321198092Srdivacky      else if (!Cand->Viable && !Reported) {
4322198092Srdivacky        // Non-viability might be due to ambiguous user-defined conversions,
4323198092Srdivacky        // needed for built-in operators. Report them as well, but only once
4324198092Srdivacky        // as we have typically many built-in candidates.
4325198092Srdivacky        unsigned NoOperands = Cand->Conversions.size();
4326198092Srdivacky        for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
4327198092Srdivacky          const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4328198092Srdivacky          if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4329198092Srdivacky              ICS.ConversionFunctionSet.empty())
4330198092Srdivacky            continue;
4331198092Srdivacky          if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4332198092Srdivacky                         Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4333198092Srdivacky            QualType FromTy =
4334198092Srdivacky              QualType(
4335198092Srdivacky                     static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4336198092Srdivacky            Diag(OpLoc,diag::note_ambiguous_type_conversion)
4337198092Srdivacky                  << FromTy << Func->getConversionType();
4338198092Srdivacky          }
4339198092Srdivacky          for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4340198092Srdivacky            FunctionDecl *Func =
4341198092Srdivacky              Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4342198092Srdivacky            Diag(Func->getLocation(),diag::err_ovl_candidate);
4343198092Srdivacky          }
4344198092Srdivacky        }
4345198092Srdivacky        Reported = true;
4346198092Srdivacky      }
4347193326Sed    }
4348193326Sed  }
4349193326Sed}
4350193326Sed
4351193326Sed/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4352193326Sed/// an overloaded function (C++ [over.over]), where @p From is an
4353193326Sed/// expression with overloaded function type and @p ToType is the type
4354193326Sed/// we're trying to resolve to. For example:
4355193326Sed///
4356193326Sed/// @code
4357193326Sed/// int f(double);
4358193326Sed/// int f(int);
4359198092Srdivacky///
4360193326Sed/// int (*pfd)(double) = f; // selects f(double)
4361193326Sed/// @endcode
4362193326Sed///
4363193326Sed/// This routine returns the resulting FunctionDecl if it could be
4364193326Sed/// resolved, and NULL otherwise. When @p Complain is true, this
4365193326Sed/// routine will emit diagnostics if there is an error.
4366193326SedFunctionDecl *
4367193326SedSema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
4368193326Sed                                         bool Complain) {
4369193326Sed  QualType FunctionType = ToType;
4370193326Sed  bool IsMember = false;
4371198092Srdivacky  if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
4372193326Sed    FunctionType = ToTypePtr->getPointeeType();
4373198092Srdivacky  else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
4374193326Sed    FunctionType = ToTypeRef->getPointeeType();
4375193326Sed  else if (const MemberPointerType *MemTypePtr =
4376198092Srdivacky                    ToType->getAs<MemberPointerType>()) {
4377193326Sed    FunctionType = MemTypePtr->getPointeeType();
4378193326Sed    IsMember = true;
4379193326Sed  }
4380193326Sed
4381193326Sed  // We only look at pointers or references to functions.
4382198092Srdivacky  FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
4383198092Srdivacky  if (!FunctionType->isFunctionType())
4384193326Sed    return 0;
4385193326Sed
4386193326Sed  // Find the actual overloaded function declaration.
4387198092Srdivacky
4388193326Sed  // C++ [over.over]p1:
4389193326Sed  //   [...] [Note: any redundant set of parentheses surrounding the
4390193326Sed  //   overloaded function name is ignored (5.1). ]
4391193326Sed  Expr *OvlExpr = From->IgnoreParens();
4392193326Sed
4393193326Sed  // C++ [over.over]p1:
4394193326Sed  //   [...] The overloaded function name can be preceded by the &
4395193326Sed  //   operator.
4396193326Sed  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4397193326Sed    if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4398193326Sed      OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4399193326Sed  }
4400193326Sed
4401198398Srdivacky  bool HasExplicitTemplateArgs = false;
4402199990Srdivacky  TemplateArgumentListInfo ExplicitTemplateArgs;
4403199990Srdivacky
4404199990Srdivacky  llvm::SmallVector<NamedDecl*,8> Fns;
4405198398Srdivacky
4406199990Srdivacky  // Look into the overloaded expression.
4407199990Srdivacky  if (UnresolvedLookupExpr *UL
4408199990Srdivacky               = dyn_cast<UnresolvedLookupExpr>(OvlExpr)) {
4409199990Srdivacky    Fns.append(UL->decls_begin(), UL->decls_end());
4410199990Srdivacky    if (UL->hasExplicitTemplateArgs()) {
4411199990Srdivacky      HasExplicitTemplateArgs = true;
4412199990Srdivacky      UL->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4413199990Srdivacky    }
4414199990Srdivacky  } else if (UnresolvedMemberExpr *ME
4415199990Srdivacky               = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) {
4416199990Srdivacky    Fns.append(ME->decls_begin(), ME->decls_end());
4417199990Srdivacky    if (ME->hasExplicitTemplateArgs()) {
4418199990Srdivacky      HasExplicitTemplateArgs = true;
4419199990Srdivacky      ME->copyTemplateArgumentsInto(ExplicitTemplateArgs);
4420199990Srdivacky    }
4421198092Srdivacky  }
4422199990Srdivacky
4423199990Srdivacky  // If we didn't actually find anything, we're done.
4424199990Srdivacky  if (Fns.empty())
4425193326Sed    return 0;
4426198092Srdivacky
4427193326Sed  // Look through all of the overloaded functions, searching for one
4428193326Sed  // whose type matches exactly.
4429198092Srdivacky  llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
4430198092Srdivacky  bool FoundNonTemplateFunction = false;
4431199990Srdivacky  for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4432199990Srdivacky         E = Fns.end(); I != E; ++I) {
4433193326Sed    // C++ [over.over]p3:
4434193326Sed    //   Non-member functions and static member functions match
4435193326Sed    //   targets of type "pointer-to-function" or "reference-to-function."
4436193326Sed    //   Nonstatic member functions match targets of
4437193326Sed    //   type "pointer-to-member-function."
4438193326Sed    // Note that according to DR 247, the containing class does not matter.
4439198092Srdivacky
4440198092Srdivacky    if (FunctionTemplateDecl *FunctionTemplate
4441199990Srdivacky          = dyn_cast<FunctionTemplateDecl>(*I)) {
4442198092Srdivacky      if (CXXMethodDecl *Method
4443198092Srdivacky            = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
4444198092Srdivacky        // Skip non-static function templates when converting to pointer, and
4445198092Srdivacky        // static when converting to member pointer.
4446198092Srdivacky        if (Method->isStatic() == IsMember)
4447198092Srdivacky          continue;
4448198092Srdivacky      } else if (IsMember)
4449198092Srdivacky        continue;
4450198092Srdivacky
4451198092Srdivacky      // C++ [over.over]p2:
4452198092Srdivacky      //   If the name is a function template, template argument deduction is
4453198092Srdivacky      //   done (14.8.2.2), and if the argument deduction succeeds, the
4454198092Srdivacky      //   resulting template argument list is used to generate a single
4455198092Srdivacky      //   function template specialization, which is added to the set of
4456198092Srdivacky      //   overloaded functions considered.
4457198092Srdivacky      // FIXME: We don't really want to build the specialization here, do we?
4458198092Srdivacky      FunctionDecl *Specialization = 0;
4459198092Srdivacky      TemplateDeductionInfo Info(Context);
4460198092Srdivacky      if (TemplateDeductionResult Result
4461199990Srdivacky            = DeduceTemplateArguments(FunctionTemplate,
4462199990Srdivacky                       (HasExplicitTemplateArgs ? &ExplicitTemplateArgs : 0),
4463198092Srdivacky                                      FunctionType, Specialization, Info)) {
4464198092Srdivacky        // FIXME: make a note of the failed deduction for diagnostics.
4465198092Srdivacky        (void)Result;
4466198092Srdivacky      } else {
4467198092Srdivacky        // FIXME: If the match isn't exact, shouldn't we just drop this as
4468198092Srdivacky        // a candidate? Find a testcase before changing the code.
4469198092Srdivacky        assert(FunctionType
4470198092Srdivacky                 == Context.getCanonicalType(Specialization->getType()));
4471198092Srdivacky        Matches.insert(
4472198092Srdivacky                cast<FunctionDecl>(Specialization->getCanonicalDecl()));
4473198092Srdivacky      }
4474199990Srdivacky
4475199990Srdivacky      continue;
4476198092Srdivacky    }
4477198092Srdivacky
4478199990Srdivacky    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*I)) {
4479193326Sed      // Skip non-static functions when converting to pointer, and static
4480193326Sed      // when converting to member pointer.
4481193326Sed      if (Method->isStatic() == IsMember)
4482193326Sed        continue;
4483198893Srdivacky
4484198893Srdivacky      // If we have explicit template arguments, skip non-templates.
4485198893Srdivacky      if (HasExplicitTemplateArgs)
4486198893Srdivacky        continue;
4487193326Sed    } else if (IsMember)
4488193326Sed      continue;
4489193326Sed
4490199990Srdivacky    if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*I)) {
4491200583Srdivacky      QualType ResultTy;
4492200583Srdivacky      if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
4493200583Srdivacky          IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
4494200583Srdivacky                               ResultTy)) {
4495199990Srdivacky        Matches.insert(cast<FunctionDecl>(FunDecl->getCanonicalDecl()));
4496198092Srdivacky        FoundNonTemplateFunction = true;
4497198092Srdivacky      }
4498195099Sed    }
4499193326Sed  }
4500193326Sed
4501198092Srdivacky  // If there were 0 or 1 matches, we're done.
4502198092Srdivacky  if (Matches.empty())
4503198092Srdivacky    return 0;
4504198398Srdivacky  else if (Matches.size() == 1) {
4505198398Srdivacky    FunctionDecl *Result = *Matches.begin();
4506198398Srdivacky    MarkDeclarationReferenced(From->getLocStart(), Result);
4507198398Srdivacky    return Result;
4508198398Srdivacky  }
4509198092Srdivacky
4510198092Srdivacky  // C++ [over.over]p4:
4511198092Srdivacky  //   If more than one function is selected, [...]
4512198092Srdivacky  typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
4513198092Srdivacky  if (!FoundNonTemplateFunction) {
4514198092Srdivacky    //   [...] and any given function template specialization F1 is
4515198092Srdivacky    //   eliminated if the set contains a second function template
4516198092Srdivacky    //   specialization whose function template is more specialized
4517198092Srdivacky    //   than the function template of F1 according to the partial
4518198092Srdivacky    //   ordering rules of 14.5.5.2.
4519198092Srdivacky
4520198092Srdivacky    // The algorithm specified above is quadratic. We instead use a
4521198092Srdivacky    // two-pass algorithm (similar to the one used to identify the
4522198092Srdivacky    // best viable function in an overload set) that identifies the
4523198092Srdivacky    // best function template (if it exists).
4524198398Srdivacky    llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4525198092Srdivacky                                                         Matches.end());
4526198398Srdivacky    FunctionDecl *Result =
4527198398Srdivacky        getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4528198398Srdivacky                           TPOC_Other, From->getLocStart(),
4529198398Srdivacky                           PDiag(),
4530198398Srdivacky                           PDiag(diag::err_addr_ovl_ambiguous)
4531198398Srdivacky                               << TemplateMatches[0]->getDeclName(),
4532198398Srdivacky                           PDiag(diag::err_ovl_template_candidate));
4533198398Srdivacky    MarkDeclarationReferenced(From->getLocStart(), Result);
4534198398Srdivacky    return Result;
4535198092Srdivacky  }
4536198092Srdivacky
4537198092Srdivacky  //   [...] any function template specializations in the set are
4538198092Srdivacky  //   eliminated if the set also contains a non-template function, [...]
4539198092Srdivacky  llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4540198092Srdivacky  for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4541198092Srdivacky    if ((*M)->getPrimaryTemplate() == 0)
4542198092Srdivacky      RemainingMatches.push_back(*M);
4543198092Srdivacky
4544198092Srdivacky  // [...] After such eliminations, if any, there shall remain exactly one
4545198092Srdivacky  // selected function.
4546198398Srdivacky  if (RemainingMatches.size() == 1) {
4547198398Srdivacky    FunctionDecl *Result = RemainingMatches.front();
4548198398Srdivacky    MarkDeclarationReferenced(From->getLocStart(), Result);
4549198398Srdivacky    return Result;
4550198398Srdivacky  }
4551198092Srdivacky
4552198092Srdivacky  // FIXME: We should probably return the same thing that BestViableFunction
4553198092Srdivacky  // returns (even if we issue the diagnostics here).
4554198092Srdivacky  Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4555198092Srdivacky    << RemainingMatches[0]->getDeclName();
4556198092Srdivacky  for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4557198092Srdivacky    Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
4558193326Sed  return 0;
4559193326Sed}
4560193326Sed
4561198092Srdivacky/// \brief Add a single candidate to the overload set.
4562198092Srdivackystatic void AddOverloadedCallCandidate(Sema &S,
4563199990Srdivacky                                       NamedDecl *Callee,
4564199990Srdivacky                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4565198092Srdivacky                                       Expr **Args, unsigned NumArgs,
4566198092Srdivacky                                       OverloadCandidateSet &CandidateSet,
4567198092Srdivacky                                       bool PartialOverloading) {
4568199990Srdivacky  if (isa<UsingShadowDecl>(Callee))
4569199990Srdivacky    Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
4570199990Srdivacky
4571198092Srdivacky  if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4572199990Srdivacky    assert(!ExplicitTemplateArgs && "Explicit template arguments?");
4573198092Srdivacky    S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4574198092Srdivacky                           PartialOverloading);
4575198092Srdivacky    return;
4576199990Srdivacky  }
4577199990Srdivacky
4578199990Srdivacky  if (FunctionTemplateDecl *FuncTemplate
4579199990Srdivacky      = dyn_cast<FunctionTemplateDecl>(Callee)) {
4580199990Srdivacky    S.AddTemplateOverloadCandidate(FuncTemplate, ExplicitTemplateArgs,
4581199990Srdivacky                                   Args, NumArgs, CandidateSet);
4582199990Srdivacky    return;
4583199990Srdivacky  }
4584199990Srdivacky
4585199990Srdivacky  assert(false && "unhandled case in overloaded call candidate");
4586199990Srdivacky
4587199990Srdivacky  // do nothing?
4588198092Srdivacky}
4589198092Srdivacky
4590198092Srdivacky/// \brief Add the overload candidates named by callee and/or found by argument
4591198092Srdivacky/// dependent lookup to the given overload set.
4592199990Srdivackyvoid Sema::AddOverloadedCallCandidates(llvm::SmallVectorImpl<NamedDecl*> &Fns,
4593198092Srdivacky                                       DeclarationName &UnqualifiedName,
4594199990Srdivacky                                       bool ArgumentDependentLookup,
4595199990Srdivacky                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
4596198092Srdivacky                                       Expr **Args, unsigned NumArgs,
4597198092Srdivacky                                       OverloadCandidateSet &CandidateSet,
4598198092Srdivacky                                       bool PartialOverloading) {
4599199990Srdivacky
4600199990Srdivacky#ifndef NDEBUG
4601199990Srdivacky  // Verify that ArgumentDependentLookup is consistent with the rules
4602199990Srdivacky  // in C++0x [basic.lookup.argdep]p3:
4603193326Sed  //
4604193326Sed  //   Let X be the lookup set produced by unqualified lookup (3.4.1)
4605193326Sed  //   and let Y be the lookup set produced by argument dependent
4606193326Sed  //   lookup (defined as follows). If X contains
4607193326Sed  //
4608198092Srdivacky  //     -- a declaration of a class member, or
4609193326Sed  //
4610193326Sed  //     -- a block-scope function declaration that is not a
4611199990Srdivacky  //        using-declaration, or
4612198092Srdivacky  //
4613193326Sed  //     -- a declaration that is neither a function or a function
4614193326Sed  //        template
4615193326Sed  //
4616198092Srdivacky  //   then Y is empty.
4617199990Srdivacky
4618199990Srdivacky  if (ArgumentDependentLookup) {
4619199990Srdivacky    for (unsigned I = 0; I < Fns.size(); ++I) {
4620199990Srdivacky      assert(!Fns[I]->getDeclContext()->isRecord());
4621199990Srdivacky      assert(isa<UsingShadowDecl>(Fns[I]) ||
4622199990Srdivacky             !Fns[I]->getDeclContext()->isFunctionOrMethod());
4623199990Srdivacky      assert(Fns[I]->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
4624199990Srdivacky    }
4625199990Srdivacky  }
4626199990Srdivacky#endif
4627199990Srdivacky
4628199990Srdivacky  for (llvm::SmallVectorImpl<NamedDecl*>::iterator I = Fns.begin(),
4629199990Srdivacky         E = Fns.end(); I != E; ++I)
4630199990Srdivacky    AddOverloadedCallCandidate(*this, *I, ExplicitTemplateArgs,
4631199990Srdivacky                               Args, NumArgs, CandidateSet,
4632198092Srdivacky                               PartialOverloading);
4633199990Srdivacky
4634193326Sed  if (ArgumentDependentLookup)
4635193326Sed    AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4636198092Srdivacky                                         ExplicitTemplateArgs,
4637198092Srdivacky                                         CandidateSet,
4638198092Srdivacky                                         PartialOverloading);
4639198092Srdivacky}
4640198092Srdivacky
4641198092Srdivacky/// ResolveOverloadedCallFn - Given the call expression that calls Fn
4642198092Srdivacky/// (which eventually refers to the declaration Func) and the call
4643198092Srdivacky/// arguments Args/NumArgs, attempt to resolve the function call down
4644198092Srdivacky/// to a specific function. If overload resolution succeeds, returns
4645198092Srdivacky/// the function declaration produced by overload
4646198092Srdivacky/// resolution. Otherwise, emits diagnostics, deletes all of the
4647198092Srdivacky/// arguments and Fn, and returns NULL.
4648199990SrdivackyFunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn,
4649199990Srdivacky                                     llvm::SmallVectorImpl<NamedDecl*> &Fns,
4650198092Srdivacky                                            DeclarationName UnqualifiedName,
4651199990Srdivacky                       const TemplateArgumentListInfo *ExplicitTemplateArgs,
4652198092Srdivacky                                            SourceLocation LParenLoc,
4653198092Srdivacky                                            Expr **Args, unsigned NumArgs,
4654198092Srdivacky                                            SourceLocation *CommaLocs,
4655198092Srdivacky                                            SourceLocation RParenLoc,
4656199990Srdivacky                                            bool ArgumentDependentLookup) {
4657198092Srdivacky  OverloadCandidateSet CandidateSet;
4658193326Sed
4659198092Srdivacky  // Add the functions denoted by Callee to the set of candidate
4660198092Srdivacky  // functions.
4661199990Srdivacky  AddOverloadedCallCandidates(Fns, UnqualifiedName, ArgumentDependentLookup,
4662199990Srdivacky                              ExplicitTemplateArgs, Args, NumArgs,
4663198092Srdivacky                              CandidateSet);
4664193326Sed  OverloadCandidateSet::iterator Best;
4665194613Sed  switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
4666193326Sed  case OR_Success:
4667193326Sed    return Best->Function;
4668193326Sed
4669193326Sed  case OR_No_Viable_Function:
4670193326Sed    Diag(Fn->getSourceRange().getBegin(),
4671193326Sed         diag::err_ovl_no_viable_function_in_call)
4672193326Sed      << UnqualifiedName << Fn->getSourceRange();
4673193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4674193326Sed    break;
4675193326Sed
4676193326Sed  case OR_Ambiguous:
4677193326Sed    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
4678193326Sed      << UnqualifiedName << Fn->getSourceRange();
4679193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4680193326Sed    break;
4681193326Sed
4682193326Sed  case OR_Deleted:
4683193326Sed    Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4684193326Sed      << Best->Function->isDeleted()
4685193326Sed      << UnqualifiedName
4686193326Sed      << Fn->getSourceRange();
4687193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4688193326Sed    break;
4689193326Sed  }
4690193326Sed
4691193326Sed  // Overload resolution failed. Destroy all of the subexpressions and
4692193326Sed  // return NULL.
4693193326Sed  Fn->Destroy(Context);
4694193326Sed  for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4695193326Sed    Args[Arg]->Destroy(Context);
4696193326Sed  return 0;
4697193326Sed}
4698193326Sed
4699199990Srdivackystatic bool IsOverloaded(const Sema::FunctionSet &Functions) {
4700199990Srdivacky  return Functions.size() > 1 ||
4701199990Srdivacky    (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
4702199990Srdivacky}
4703199990Srdivacky
4704193326Sed/// \brief Create a unary operation that may resolve to an overloaded
4705193326Sed/// operator.
4706193326Sed///
4707193326Sed/// \param OpLoc The location of the operator itself (e.g., '*').
4708193326Sed///
4709193326Sed/// \param OpcIn The UnaryOperator::Opcode that describes this
4710193326Sed/// operator.
4711193326Sed///
4712193326Sed/// \param Functions The set of non-member functions that will be
4713193326Sed/// considered by overload resolution. The caller needs to build this
4714193326Sed/// set based on the context using, e.g.,
4715193326Sed/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4716193326Sed/// set should not contain any member functions; those will be added
4717193326Sed/// by CreateOverloadedUnaryOp().
4718193326Sed///
4719193326Sed/// \param input The input argument.
4720193326SedSema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4721193326Sed                                                     unsigned OpcIn,
4722193326Sed                                                     FunctionSet &Functions,
4723198092Srdivacky                                                     ExprArg input) {
4724193326Sed  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4725193326Sed  Expr *Input = (Expr *)input.get();
4726193326Sed
4727193326Sed  OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4728193326Sed  assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4729193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4730193326Sed
4731193326Sed  Expr *Args[2] = { Input, 0 };
4732193326Sed  unsigned NumArgs = 1;
4733198092Srdivacky
4734193326Sed  // For post-increment and post-decrement, add the implicit '0' as
4735193326Sed  // the second argument, so that we know this is a post-increment or
4736193326Sed  // post-decrement.
4737193326Sed  if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4738193326Sed    llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
4739198092Srdivacky    Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
4740193326Sed                                           SourceLocation());
4741193326Sed    NumArgs = 2;
4742193326Sed  }
4743193326Sed
4744193326Sed  if (Input->isTypeDependent()) {
4745199990Srdivacky    UnresolvedLookupExpr *Fn
4746199990Srdivacky      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4747199990Srdivacky                                     0, SourceRange(), OpName, OpLoc,
4748199990Srdivacky                                     /*ADL*/ true, IsOverloaded(Functions));
4749198092Srdivacky    for (FunctionSet::iterator Func = Functions.begin(),
4750193326Sed                            FuncEnd = Functions.end();
4751193326Sed         Func != FuncEnd; ++Func)
4752199990Srdivacky      Fn->addDecl(*Func);
4753193326Sed
4754193326Sed    input.release();
4755193326Sed    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4756193326Sed                                                   &Args[0], NumArgs,
4757193326Sed                                                   Context.DependentTy,
4758193326Sed                                                   OpLoc));
4759193326Sed  }
4760193326Sed
4761193326Sed  // Build an empty overload set.
4762193326Sed  OverloadCandidateSet CandidateSet;
4763193326Sed
4764193326Sed  // Add the candidates from the given function set.
4765193326Sed  AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4766193326Sed
4767193326Sed  // Add operator candidates that are member functions.
4768193326Sed  AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4769193326Sed
4770193326Sed  // Add builtin operator candidates.
4771198398Srdivacky  AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4772193326Sed
4773193326Sed  // Perform overload resolution.
4774193326Sed  OverloadCandidateSet::iterator Best;
4775194613Sed  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4776193326Sed  case OR_Success: {
4777193326Sed    // We found a built-in operator or an overloaded operator.
4778193326Sed    FunctionDecl *FnDecl = Best->Function;
4779198092Srdivacky
4780193326Sed    if (FnDecl) {
4781193326Sed      // We matched an overloaded operator. Build a call to that
4782193326Sed      // operator.
4783198092Srdivacky
4784193326Sed      // Convert the arguments.
4785193326Sed      if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4786193326Sed        if (PerformObjectArgumentInitialization(Input, Method))
4787193326Sed          return ExprError();
4788193326Sed      } else {
4789193326Sed        // Convert the arguments.
4790193326Sed        if (PerformCopyInitialization(Input,
4791193326Sed                                      FnDecl->getParamDecl(0)->getType(),
4792193326Sed                                      "passing"))
4793193326Sed          return ExprError();
4794193326Sed      }
4795193326Sed
4796193326Sed      // Determine the result type
4797198092Srdivacky      QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
4798198092Srdivacky
4799193326Sed      // Build the actual expression node.
4800193326Sed      Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4801193326Sed                                               SourceLocation());
4802193326Sed      UsualUnaryConversions(FnExpr);
4803198092Srdivacky
4804198092Srdivacky      input.release();
4805199482Srdivacky      Args[0] = Input;
4806198092Srdivacky      ExprOwningPtr<CallExpr> TheCall(this,
4807198092Srdivacky        new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4808199482Srdivacky                                          Args, NumArgs, ResultTy, OpLoc));
4809193326Sed
4810198092Srdivacky      if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4811198092Srdivacky                              FnDecl))
4812198092Srdivacky        return ExprError();
4813198092Srdivacky
4814198092Srdivacky      return MaybeBindToTemporary(TheCall.release());
4815193326Sed    } else {
4816193326Sed      // We matched a built-in operator. Convert the arguments, then
4817193326Sed      // break out so that we will build the appropriate built-in
4818193326Sed      // operator node.
4819193326Sed        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4820193326Sed                                      Best->Conversions[0], "passing"))
4821193326Sed          return ExprError();
4822193326Sed
4823193326Sed        break;
4824193326Sed      }
4825193326Sed    }
4826193326Sed
4827193326Sed    case OR_No_Viable_Function:
4828193326Sed      // No viable function; fall through to handling this as a
4829193326Sed      // built-in operator, which will produce an error message for us.
4830193326Sed      break;
4831193326Sed
4832193326Sed    case OR_Ambiguous:
4833193326Sed      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4834193326Sed          << UnaryOperator::getOpcodeStr(Opc)
4835193326Sed          << Input->getSourceRange();
4836198092Srdivacky      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4837198092Srdivacky                              UnaryOperator::getOpcodeStr(Opc), OpLoc);
4838193326Sed      return ExprError();
4839193326Sed
4840193326Sed    case OR_Deleted:
4841193326Sed      Diag(OpLoc, diag::err_ovl_deleted_oper)
4842193326Sed        << Best->Function->isDeleted()
4843193326Sed        << UnaryOperator::getOpcodeStr(Opc)
4844193326Sed        << Input->getSourceRange();
4845193326Sed      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4846193326Sed      return ExprError();
4847193326Sed    }
4848193326Sed
4849193326Sed  // Either we found no viable overloaded operator or we matched a
4850193326Sed  // built-in operator. In either case, fall through to trying to
4851193326Sed  // build a built-in operation.
4852193326Sed  input.release();
4853193326Sed  return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4854193326Sed}
4855193326Sed
4856193326Sed/// \brief Create a binary operation that may resolve to an overloaded
4857193326Sed/// operator.
4858193326Sed///
4859193326Sed/// \param OpLoc The location of the operator itself (e.g., '+').
4860193326Sed///
4861193326Sed/// \param OpcIn The BinaryOperator::Opcode that describes this
4862193326Sed/// operator.
4863193326Sed///
4864193326Sed/// \param Functions The set of non-member functions that will be
4865193326Sed/// considered by overload resolution. The caller needs to build this
4866193326Sed/// set based on the context using, e.g.,
4867193326Sed/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4868193326Sed/// set should not contain any member functions; those will be added
4869193326Sed/// by CreateOverloadedBinOp().
4870193326Sed///
4871193326Sed/// \param LHS Left-hand argument.
4872193326Sed/// \param RHS Right-hand argument.
4873198092SrdivackySema::OwningExprResult
4874193326SedSema::CreateOverloadedBinOp(SourceLocation OpLoc,
4875198092Srdivacky                            unsigned OpcIn,
4876193326Sed                            FunctionSet &Functions,
4877193326Sed                            Expr *LHS, Expr *RHS) {
4878193326Sed  Expr *Args[2] = { LHS, RHS };
4879198092Srdivacky  LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
4880193326Sed
4881193326Sed  BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4882193326Sed  OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4883193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4884193326Sed
4885193326Sed  // If either side is type-dependent, create an appropriate dependent
4886193326Sed  // expression.
4887198092Srdivacky  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4888198954Srdivacky    if (Functions.empty()) {
4889198954Srdivacky      // If there are no functions to store, just build a dependent
4890198954Srdivacky      // BinaryOperator or CompoundAssignment.
4891198954Srdivacky      if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4892198954Srdivacky        return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4893198954Srdivacky                                                  Context.DependentTy, OpLoc));
4894198954Srdivacky
4895198954Srdivacky      return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4896198954Srdivacky                                                        Context.DependentTy,
4897198954Srdivacky                                                        Context.DependentTy,
4898198954Srdivacky                                                        Context.DependentTy,
4899198954Srdivacky                                                        OpLoc));
4900198954Srdivacky    }
4901198954Srdivacky
4902199990Srdivacky    UnresolvedLookupExpr *Fn
4903199990Srdivacky      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
4904199990Srdivacky                                     0, SourceRange(), OpName, OpLoc,
4905199990Srdivacky                                     /* ADL */ true, IsOverloaded(Functions));
4906199990Srdivacky
4907198092Srdivacky    for (FunctionSet::iterator Func = Functions.begin(),
4908193326Sed                            FuncEnd = Functions.end();
4909193326Sed         Func != FuncEnd; ++Func)
4910199990Srdivacky      Fn->addDecl(*Func);
4911193326Sed
4912193326Sed    return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4913198092Srdivacky                                                   Args, 2,
4914193326Sed                                                   Context.DependentTy,
4915193326Sed                                                   OpLoc));
4916193326Sed  }
4917193326Sed
4918193326Sed  // If this is the .* operator, which is not overloadable, just
4919193326Sed  // create a built-in binary operator.
4920193326Sed  if (Opc == BinaryOperator::PtrMemD)
4921198092Srdivacky    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4922193326Sed
4923199512Srdivacky  // If this is the assignment operator, we only perform overload resolution
4924199512Srdivacky  // if the left-hand side is a class or enumeration type. This is actually
4925199512Srdivacky  // a hack. The standard requires that we do overload resolution between the
4926199512Srdivacky  // various built-in candidates, but as DR507 points out, this can lead to
4927199512Srdivacky  // problems. So we do it this way, which pretty much follows what GCC does.
4928199512Srdivacky  // Note that we go the traditional code path for compound assignment forms.
4929199512Srdivacky  if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
4930198092Srdivacky    return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
4931193326Sed
4932193326Sed  // Build an empty overload set.
4933193326Sed  OverloadCandidateSet CandidateSet;
4934193326Sed
4935193326Sed  // Add the candidates from the given function set.
4936193326Sed  AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4937193326Sed
4938193326Sed  // Add operator candidates that are member functions.
4939193326Sed  AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4940193326Sed
4941193326Sed  // Add builtin operator candidates.
4942198398Srdivacky  AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4943193326Sed
4944193326Sed  // Perform overload resolution.
4945193326Sed  OverloadCandidateSet::iterator Best;
4946194613Sed  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
4947193326Sed    case OR_Success: {
4948193326Sed      // We found a built-in operator or an overloaded operator.
4949193326Sed      FunctionDecl *FnDecl = Best->Function;
4950193326Sed
4951193326Sed      if (FnDecl) {
4952193326Sed        // We matched an overloaded operator. Build a call to that
4953193326Sed        // operator.
4954193326Sed
4955193326Sed        // Convert the arguments.
4956193326Sed        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4957198092Srdivacky          if (PerformObjectArgumentInitialization(Args[0], Method) ||
4958198092Srdivacky              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
4959193326Sed                                        "passing"))
4960193326Sed            return ExprError();
4961193326Sed        } else {
4962193326Sed          // Convert the arguments.
4963198092Srdivacky          if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
4964193326Sed                                        "passing") ||
4965198092Srdivacky              PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
4966193326Sed                                        "passing"))
4967193326Sed            return ExprError();
4968193326Sed        }
4969193326Sed
4970193326Sed        // Determine the result type
4971193326Sed        QualType ResultTy
4972198092Srdivacky          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
4973193326Sed        ResultTy = ResultTy.getNonReferenceType();
4974193326Sed
4975193326Sed        // Build the actual expression node.
4976193326Sed        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4977198092Srdivacky                                                 OpLoc);
4978193326Sed        UsualUnaryConversions(FnExpr);
4979193326Sed
4980198092Srdivacky        ExprOwningPtr<CXXOperatorCallExpr>
4981198092Srdivacky          TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4982198092Srdivacky                                                          Args, 2, ResultTy,
4983198092Srdivacky                                                          OpLoc));
4984198092Srdivacky
4985198092Srdivacky        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4986198092Srdivacky                                FnDecl))
4987198092Srdivacky          return ExprError();
4988198092Srdivacky
4989198092Srdivacky        return MaybeBindToTemporary(TheCall.release());
4990193326Sed      } else {
4991193326Sed        // We matched a built-in operator. Convert the arguments, then
4992193326Sed        // break out so that we will build the appropriate built-in
4993193326Sed        // operator node.
4994198092Srdivacky        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
4995193326Sed                                      Best->Conversions[0], "passing") ||
4996198092Srdivacky            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
4997193326Sed                                      Best->Conversions[1], "passing"))
4998193326Sed          return ExprError();
4999193326Sed
5000193326Sed        break;
5001193326Sed      }
5002193326Sed    }
5003193326Sed
5004198092Srdivacky    case OR_No_Viable_Function: {
5005198092Srdivacky      // C++ [over.match.oper]p9:
5006198092Srdivacky      //   If the operator is the operator , [...] and there are no
5007198092Srdivacky      //   viable functions, then the operator is assumed to be the
5008198092Srdivacky      //   built-in operator and interpreted according to clause 5.
5009198092Srdivacky      if (Opc == BinaryOperator::Comma)
5010198092Srdivacky        break;
5011198092Srdivacky
5012193326Sed      // For class as left operand for assignment or compound assigment operator
5013193326Sed      // do not fall through to handling in built-in, but report that no overloaded
5014193326Sed      // assignment operator found
5015198092Srdivacky      OwningExprResult Result = ExprError();
5016198092Srdivacky      if (Args[0]->getType()->isRecordType() &&
5017198092Srdivacky          Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
5018193326Sed        Diag(OpLoc,  diag::err_ovl_no_viable_oper)
5019193326Sed             << BinaryOperator::getOpcodeStr(Opc)
5020198092Srdivacky             << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5021198092Srdivacky      } else {
5022198092Srdivacky        // No viable function; try to create a built-in operation, which will
5023198092Srdivacky        // produce an error. Then, show the non-viable candidates.
5024198092Srdivacky        Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5025193326Sed      }
5026198092Srdivacky      assert(Result.isInvalid() &&
5027198092Srdivacky             "C++ binary operator overloading is missing candidates!");
5028198092Srdivacky      if (Result.isInvalid())
5029198092Srdivacky        PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5030198092Srdivacky                                BinaryOperator::getOpcodeStr(Opc), OpLoc);
5031198092Srdivacky      return move(Result);
5032198092Srdivacky    }
5033193326Sed
5034193326Sed    case OR_Ambiguous:
5035193326Sed      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5036193326Sed          << BinaryOperator::getOpcodeStr(Opc)
5037198092Srdivacky          << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5038198092Srdivacky      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5039198092Srdivacky                              BinaryOperator::getOpcodeStr(Opc), OpLoc);
5040193326Sed      return ExprError();
5041193326Sed
5042193326Sed    case OR_Deleted:
5043193326Sed      Diag(OpLoc, diag::err_ovl_deleted_oper)
5044193326Sed        << Best->Function->isDeleted()
5045193326Sed        << BinaryOperator::getOpcodeStr(Opc)
5046198092Srdivacky        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5047193326Sed      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5048193326Sed      return ExprError();
5049193326Sed    }
5050193326Sed
5051198092Srdivacky  // We matched a built-in operator; build it.
5052198092Srdivacky  return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
5053193326Sed}
5054193326Sed
5055198893SrdivackyAction::OwningExprResult
5056198893SrdivackySema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
5057198893Srdivacky                                         SourceLocation RLoc,
5058198893Srdivacky                                         ExprArg Base, ExprArg Idx) {
5059198893Srdivacky  Expr *Args[2] = { static_cast<Expr*>(Base.get()),
5060198893Srdivacky                    static_cast<Expr*>(Idx.get()) };
5061198893Srdivacky  DeclarationName OpName =
5062198893Srdivacky      Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
5063198893Srdivacky
5064198893Srdivacky  // If either side is type-dependent, create an appropriate dependent
5065198893Srdivacky  // expression.
5066198893Srdivacky  if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
5067198893Srdivacky
5068199990Srdivacky    UnresolvedLookupExpr *Fn
5069199990Srdivacky      = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true,
5070199990Srdivacky                                     0, SourceRange(), OpName, LLoc,
5071199990Srdivacky                                     /*ADL*/ true, /*Overloaded*/ false);
5072199990Srdivacky    // Can't add any actual overloads yet
5073198893Srdivacky
5074198893Srdivacky    Base.release();
5075198893Srdivacky    Idx.release();
5076198893Srdivacky    return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
5077198893Srdivacky                                                   Args, 2,
5078198893Srdivacky                                                   Context.DependentTy,
5079198893Srdivacky                                                   RLoc));
5080198893Srdivacky  }
5081198893Srdivacky
5082198893Srdivacky  // Build an empty overload set.
5083198893Srdivacky  OverloadCandidateSet CandidateSet;
5084198893Srdivacky
5085198893Srdivacky  // Subscript can only be overloaded as a member function.
5086198893Srdivacky
5087198893Srdivacky  // Add operator candidates that are member functions.
5088198893Srdivacky  AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5089198893Srdivacky
5090198893Srdivacky  // Add builtin operator candidates.
5091198893Srdivacky  AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
5092198893Srdivacky
5093198893Srdivacky  // Perform overload resolution.
5094198893Srdivacky  OverloadCandidateSet::iterator Best;
5095198893Srdivacky  switch (BestViableFunction(CandidateSet, LLoc, Best)) {
5096198893Srdivacky    case OR_Success: {
5097198893Srdivacky      // We found a built-in operator or an overloaded operator.
5098198893Srdivacky      FunctionDecl *FnDecl = Best->Function;
5099198893Srdivacky
5100198893Srdivacky      if (FnDecl) {
5101198893Srdivacky        // We matched an overloaded operator. Build a call to that
5102198893Srdivacky        // operator.
5103198893Srdivacky
5104198893Srdivacky        // Convert the arguments.
5105198893Srdivacky        CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5106198893Srdivacky        if (PerformObjectArgumentInitialization(Args[0], Method) ||
5107198893Srdivacky            PerformCopyInitialization(Args[1],
5108198893Srdivacky                                      FnDecl->getParamDecl(0)->getType(),
5109198893Srdivacky                                      "passing"))
5110198893Srdivacky          return ExprError();
5111198893Srdivacky
5112198893Srdivacky        // Determine the result type
5113198893Srdivacky        QualType ResultTy
5114198893Srdivacky          = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5115198893Srdivacky        ResultTy = ResultTy.getNonReferenceType();
5116198893Srdivacky
5117198893Srdivacky        // Build the actual expression node.
5118198893Srdivacky        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5119198893Srdivacky                                                 LLoc);
5120198893Srdivacky        UsualUnaryConversions(FnExpr);
5121198893Srdivacky
5122198893Srdivacky        Base.release();
5123198893Srdivacky        Idx.release();
5124198893Srdivacky        ExprOwningPtr<CXXOperatorCallExpr>
5125198893Srdivacky          TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5126198893Srdivacky                                                          FnExpr, Args, 2,
5127198893Srdivacky                                                          ResultTy, RLoc));
5128198893Srdivacky
5129198893Srdivacky        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5130198893Srdivacky                                FnDecl))
5131198893Srdivacky          return ExprError();
5132198893Srdivacky
5133198893Srdivacky        return MaybeBindToTemporary(TheCall.release());
5134198893Srdivacky      } else {
5135198893Srdivacky        // We matched a built-in operator. Convert the arguments, then
5136198893Srdivacky        // break out so that we will build the appropriate built-in
5137198893Srdivacky        // operator node.
5138198893Srdivacky        if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5139198893Srdivacky                                      Best->Conversions[0], "passing") ||
5140198893Srdivacky            PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5141198893Srdivacky                                      Best->Conversions[1], "passing"))
5142198893Srdivacky          return ExprError();
5143198893Srdivacky
5144198893Srdivacky        break;
5145198893Srdivacky      }
5146198893Srdivacky    }
5147198893Srdivacky
5148198893Srdivacky    case OR_No_Viable_Function: {
5149198893Srdivacky      // No viable function; try to create a built-in operation, which will
5150198893Srdivacky      // produce an error. Then, show the non-viable candidates.
5151198893Srdivacky      OwningExprResult Result =
5152198893Srdivacky          CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5153198893Srdivacky      assert(Result.isInvalid() &&
5154198893Srdivacky             "C++ subscript operator overloading is missing candidates!");
5155198893Srdivacky      if (Result.isInvalid())
5156198893Srdivacky        PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5157198893Srdivacky                                "[]", LLoc);
5158198893Srdivacky      return move(Result);
5159198893Srdivacky    }
5160198893Srdivacky
5161198893Srdivacky    case OR_Ambiguous:
5162198893Srdivacky      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
5163198893Srdivacky          << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5164198893Srdivacky      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5165198893Srdivacky                              "[]", LLoc);
5166198893Srdivacky      return ExprError();
5167198893Srdivacky
5168198893Srdivacky    case OR_Deleted:
5169198893Srdivacky      Diag(LLoc, diag::err_ovl_deleted_oper)
5170198893Srdivacky        << Best->Function->isDeleted() << "[]"
5171198893Srdivacky        << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5172198893Srdivacky      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5173198893Srdivacky      return ExprError();
5174198893Srdivacky    }
5175198893Srdivacky
5176198893Srdivacky  // We matched a built-in operator; build it.
5177198893Srdivacky  Base.release();
5178198893Srdivacky  Idx.release();
5179198893Srdivacky  return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5180198893Srdivacky                                         Owned(Args[1]), RLoc);
5181198893Srdivacky}
5182198893Srdivacky
5183193326Sed/// BuildCallToMemberFunction - Build a call to a member
5184193326Sed/// function. MemExpr is the expression that refers to the member
5185193326Sed/// function (and includes the object parameter), Args/NumArgs are the
5186193326Sed/// arguments to the function call (not including the object
5187193326Sed/// parameter). The caller needs to validate that the member
5188193326Sed/// expression refers to a member function or an overloaded member
5189193326Sed/// function.
5190200583SrdivackySema::OwningExprResult
5191198092SrdivackySema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5192198092Srdivacky                                SourceLocation LParenLoc, Expr **Args,
5193193326Sed                                unsigned NumArgs, SourceLocation *CommaLocs,
5194193326Sed                                SourceLocation RParenLoc) {
5195193326Sed  // Dig out the member expression. This holds both the object
5196193326Sed  // argument and the member function we're referring to.
5197199990Srdivacky  Expr *NakedMemExpr = MemExprE->IgnoreParens();
5198199990Srdivacky
5199199990Srdivacky  MemberExpr *MemExpr;
5200193326Sed  CXXMethodDecl *Method = 0;
5201199990Srdivacky  if (isa<MemberExpr>(NakedMemExpr)) {
5202199990Srdivacky    MemExpr = cast<MemberExpr>(NakedMemExpr);
5203199990Srdivacky    Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5204199990Srdivacky  } else {
5205199990Srdivacky    UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
5206199990Srdivacky
5207200583Srdivacky    QualType ObjectType = UnresExpr->getBaseType();
5208200583Srdivacky
5209193326Sed    // Add overload candidates
5210193326Sed    OverloadCandidateSet CandidateSet;
5211198092Srdivacky
5212200583Srdivacky    // FIXME: avoid copy.
5213200583Srdivacky    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5214200583Srdivacky    if (UnresExpr->hasExplicitTemplateArgs()) {
5215200583Srdivacky      UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5216200583Srdivacky      TemplateArgs = &TemplateArgsBuffer;
5217200583Srdivacky    }
5218200583Srdivacky
5219199990Srdivacky    for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
5220199990Srdivacky           E = UnresExpr->decls_end(); I != E; ++I) {
5221199990Srdivacky
5222200583Srdivacky      NamedDecl *Func = *I;
5223200583Srdivacky      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
5224200583Srdivacky      if (isa<UsingShadowDecl>(Func))
5225200583Srdivacky        Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
5226200583Srdivacky
5227199990Srdivacky      if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
5228198893Srdivacky        // If explicit template arguments were provided, we can't call a
5229198893Srdivacky        // non-template member function.
5230200583Srdivacky        if (TemplateArgs)
5231198893Srdivacky          continue;
5232198893Srdivacky
5233200583Srdivacky        AddMethodCandidate(Method, ActingDC, ObjectType, Args, NumArgs,
5234200583Srdivacky                           CandidateSet, /*SuppressUserConversions=*/false);
5235199990Srdivacky      } else {
5236199990Srdivacky        AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
5237200583Srdivacky                                   ActingDC, TemplateArgs,
5238200583Srdivacky                                   ObjectType, Args, NumArgs,
5239198092Srdivacky                                   CandidateSet,
5240198092Srdivacky                                   /*SuppressUsedConversions=*/false);
5241199990Srdivacky      }
5242193326Sed    }
5243193326Sed
5244199990Srdivacky    DeclarationName DeclName = UnresExpr->getMemberName();
5245199990Srdivacky
5246193326Sed    OverloadCandidateSet::iterator Best;
5247199990Srdivacky    switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
5248193326Sed    case OR_Success:
5249193326Sed      Method = cast<CXXMethodDecl>(Best->Function);
5250193326Sed      break;
5251193326Sed
5252193326Sed    case OR_No_Viable_Function:
5253199990Srdivacky      Diag(UnresExpr->getMemberLoc(),
5254193326Sed           diag::err_ovl_no_viable_member_function_in_call)
5255198092Srdivacky        << DeclName << MemExprE->getSourceRange();
5256193326Sed      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5257193326Sed      // FIXME: Leaking incoming expressions!
5258200583Srdivacky      return ExprError();
5259193326Sed
5260193326Sed    case OR_Ambiguous:
5261199990Srdivacky      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
5262198092Srdivacky        << DeclName << MemExprE->getSourceRange();
5263193326Sed      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5264193326Sed      // FIXME: Leaking incoming expressions!
5265200583Srdivacky      return ExprError();
5266193326Sed
5267193326Sed    case OR_Deleted:
5268199990Srdivacky      Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
5269193326Sed        << Best->Function->isDeleted()
5270198092Srdivacky        << DeclName << MemExprE->getSourceRange();
5271193326Sed      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5272193326Sed      // FIXME: Leaking incoming expressions!
5273200583Srdivacky      return ExprError();
5274193326Sed    }
5275193326Sed
5276199990Srdivacky    MemExprE = FixOverloadedFunctionReference(MemExprE, Method);
5277200583Srdivacky
5278200583Srdivacky    // If overload resolution picked a static member, build a
5279200583Srdivacky    // non-member call based on that function.
5280200583Srdivacky    if (Method->isStatic()) {
5281200583Srdivacky      return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
5282200583Srdivacky                                   Args, NumArgs, RParenLoc);
5283200583Srdivacky    }
5284200583Srdivacky
5285199990Srdivacky    MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
5286193326Sed  }
5287193326Sed
5288193326Sed  assert(Method && "Member call to something that isn't a method?");
5289198092Srdivacky  ExprOwningPtr<CXXMemberCallExpr>
5290200583Srdivacky    TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
5291198092Srdivacky                                                  NumArgs,
5292193326Sed                                  Method->getResultType().getNonReferenceType(),
5293193326Sed                                  RParenLoc));
5294193326Sed
5295198092Srdivacky  // Check for a valid return type.
5296198092Srdivacky  if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5297198092Srdivacky                          TheCall.get(), Method))
5298200583Srdivacky    return ExprError();
5299198092Srdivacky
5300193326Sed  // Convert the object argument (for a non-static member function call).
5301200583Srdivacky  Expr *ObjectArg = MemExpr->getBase();
5302198092Srdivacky  if (!Method->isStatic() &&
5303193326Sed      PerformObjectArgumentInitialization(ObjectArg, Method))
5304200583Srdivacky    return ExprError();
5305193326Sed  MemExpr->setBase(ObjectArg);
5306193326Sed
5307193326Sed  // Convert the rest of the arguments
5308193326Sed  const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
5309198092Srdivacky  if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
5310193326Sed                              RParenLoc))
5311200583Srdivacky    return ExprError();
5312193326Sed
5313198092Srdivacky  if (CheckFunctionCall(Method, TheCall.get()))
5314200583Srdivacky    return ExprError();
5315198092Srdivacky
5316200583Srdivacky  return MaybeBindToTemporary(TheCall.release());
5317193326Sed}
5318193326Sed
5319193326Sed/// BuildCallToObjectOfClassType - Build a call to an object of class
5320193326Sed/// type (C++ [over.call.object]), which can end up invoking an
5321193326Sed/// overloaded function call operator (@c operator()) or performing a
5322193326Sed/// user-defined conversion on the object argument.
5323198092SrdivackySema::ExprResult
5324198092SrdivackySema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
5325193326Sed                                   SourceLocation LParenLoc,
5326193326Sed                                   Expr **Args, unsigned NumArgs,
5327198092Srdivacky                                   SourceLocation *CommaLocs,
5328193326Sed                                   SourceLocation RParenLoc) {
5329193326Sed  assert(Object->getType()->isRecordType() && "Requires object type argument");
5330198092Srdivacky  const RecordType *Record = Object->getType()->getAs<RecordType>();
5331198092Srdivacky
5332193326Sed  // C++ [over.call.object]p1:
5333193326Sed  //  If the primary-expression E in the function call syntax
5334198092Srdivacky  //  evaluates to a class object of type "cv T", then the set of
5335193326Sed  //  candidate functions includes at least the function call
5336193326Sed  //  operators of T. The function call operators of T are obtained by
5337193326Sed  //  ordinary lookup of the name operator() in the context of
5338193326Sed  //  (E).operator().
5339193326Sed  OverloadCandidateSet CandidateSet;
5340193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
5341193326Sed
5342198398Srdivacky  if (RequireCompleteType(LParenLoc, Object->getType(),
5343198398Srdivacky                          PartialDiagnostic(diag::err_incomplete_object_call)
5344199482Srdivacky                          << Object->getSourceRange()))
5345198398Srdivacky    return true;
5346198398Srdivacky
5347199482Srdivacky  LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
5348199482Srdivacky  LookupQualifiedName(R, Record->getDecl());
5349199482Srdivacky  R.suppressDiagnostics();
5350199482Srdivacky
5351199482Srdivacky  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5352199482Srdivacky       Oper != OperEnd; ++Oper) {
5353200583Srdivacky    AddMethodCandidate(*Oper, Object->getType(), Args, NumArgs, CandidateSet,
5354199482Srdivacky                       /*SuppressUserConversions=*/ false);
5355199482Srdivacky  }
5356199482Srdivacky
5357193326Sed  // C++ [over.call.object]p2:
5358193326Sed  //   In addition, for each conversion function declared in T of the
5359193326Sed  //   form
5360193326Sed  //
5361193326Sed  //        operator conversion-type-id () cv-qualifier;
5362193326Sed  //
5363193326Sed  //   where cv-qualifier is the same cv-qualification as, or a
5364193326Sed  //   greater cv-qualification than, cv, and where conversion-type-id
5365193326Sed  //   denotes the type "pointer to function of (P1,...,Pn) returning
5366193326Sed  //   R", or the type "reference to pointer to function of
5367193326Sed  //   (P1,...,Pn) returning R", or the type "reference to function
5368193326Sed  //   of (P1,...,Pn) returning R", a surrogate call function [...]
5369193326Sed  //   is also considered as a candidate function. Similarly,
5370193326Sed  //   surrogate call functions are added to the set of candidate
5371193326Sed  //   functions for each conversion function declared in an
5372193326Sed  //   accessible base class provided the function is not hidden
5373193326Sed  //   within T by another intervening declaration.
5374198398Srdivacky  // FIXME: Look in base classes for more conversion operators!
5375199990Srdivacky  const UnresolvedSet *Conversions
5376198398Srdivacky    = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5377199990Srdivacky  for (UnresolvedSet::iterator I = Conversions->begin(),
5378199990Srdivacky         E = Conversions->end(); I != E; ++I) {
5379200583Srdivacky    NamedDecl *D = *I;
5380200583Srdivacky    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5381200583Srdivacky    if (isa<UsingShadowDecl>(D))
5382200583Srdivacky      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5383200583Srdivacky
5384198398Srdivacky    // Skip over templated conversion functions; they aren't
5385198398Srdivacky    // surrogates.
5386200583Srdivacky    if (isa<FunctionTemplateDecl>(D))
5387198398Srdivacky      continue;
5388193326Sed
5389200583Srdivacky    CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5390199990Srdivacky
5391198398Srdivacky    // Strip the reference type (if any) and then the pointer type (if
5392198398Srdivacky    // any) to get down to what might be a function type.
5393198398Srdivacky    QualType ConvType = Conv->getConversionType().getNonReferenceType();
5394198398Srdivacky    if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5395198398Srdivacky      ConvType = ConvPtrType->getPointeeType();
5396198092Srdivacky
5397198398Srdivacky    if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5398200583Srdivacky      AddSurrogateCandidate(Conv, ActingContext, Proto,
5399200583Srdivacky                            Object->getType(), Args, NumArgs,
5400200583Srdivacky                            CandidateSet);
5401193326Sed  }
5402193326Sed
5403193326Sed  // Perform overload resolution.
5404193326Sed  OverloadCandidateSet::iterator Best;
5405194613Sed  switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
5406193326Sed  case OR_Success:
5407193326Sed    // Overload resolution succeeded; we'll build the appropriate call
5408193326Sed    // below.
5409193326Sed    break;
5410193326Sed
5411193326Sed  case OR_No_Viable_Function:
5412198092Srdivacky    Diag(Object->getSourceRange().getBegin(),
5413193326Sed         diag::err_ovl_no_viable_object_call)
5414193326Sed      << Object->getType() << Object->getSourceRange();
5415193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5416193326Sed    break;
5417193326Sed
5418193326Sed  case OR_Ambiguous:
5419193326Sed    Diag(Object->getSourceRange().getBegin(),
5420193326Sed         diag::err_ovl_ambiguous_object_call)
5421193326Sed      << Object->getType() << Object->getSourceRange();
5422193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5423193326Sed    break;
5424193326Sed
5425193326Sed  case OR_Deleted:
5426193326Sed    Diag(Object->getSourceRange().getBegin(),
5427193326Sed         diag::err_ovl_deleted_object_call)
5428193326Sed      << Best->Function->isDeleted()
5429193326Sed      << Object->getType() << Object->getSourceRange();
5430193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5431193326Sed    break;
5432198092Srdivacky  }
5433193326Sed
5434193326Sed  if (Best == CandidateSet.end()) {
5435193326Sed    // We had an error; delete all of the subexpressions and return
5436193326Sed    // the error.
5437193326Sed    Object->Destroy(Context);
5438193326Sed    for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5439193326Sed      Args[ArgIdx]->Destroy(Context);
5440193326Sed    return true;
5441193326Sed  }
5442193326Sed
5443193326Sed  if (Best->Function == 0) {
5444193326Sed    // Since there is no function declaration, this is one of the
5445193326Sed    // surrogate candidates. Dig out the conversion function.
5446198092Srdivacky    CXXConversionDecl *Conv
5447193326Sed      = cast<CXXConversionDecl>(
5448193326Sed                         Best->Conversions[0].UserDefined.ConversionFunction);
5449193326Sed
5450193326Sed    // We selected one of the surrogate functions that converts the
5451193326Sed    // object parameter to a function pointer. Perform the conversion
5452193326Sed    // on the object argument, then let ActOnCallExpr finish the job.
5453198092Srdivacky
5454198092Srdivacky    // Create an implicit member expr to refer to the conversion operator.
5455198092Srdivacky    // and then call it.
5456200583Srdivacky    CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Conv);
5457198092Srdivacky
5458198092Srdivacky    return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
5459193326Sed                         MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5460193326Sed                         CommaLocs, RParenLoc).release();
5461193326Sed  }
5462193326Sed
5463193326Sed  // We found an overloaded operator(). Build a CXXOperatorCallExpr
5464193326Sed  // that calls this method, using Object for the implicit object
5465193326Sed  // parameter and passing along the remaining arguments.
5466193326Sed  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5467198092Srdivacky  const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
5468193326Sed
5469193326Sed  unsigned NumArgsInProto = Proto->getNumArgs();
5470193326Sed  unsigned NumArgsToCheck = NumArgs;
5471193326Sed
5472193326Sed  // Build the full argument list for the method call (the
5473193326Sed  // implicit object parameter is placed at the beginning of the
5474193326Sed  // list).
5475193326Sed  Expr **MethodArgs;
5476193326Sed  if (NumArgs < NumArgsInProto) {
5477193326Sed    NumArgsToCheck = NumArgsInProto;
5478193326Sed    MethodArgs = new Expr*[NumArgsInProto + 1];
5479193326Sed  } else {
5480193326Sed    MethodArgs = new Expr*[NumArgs + 1];
5481193326Sed  }
5482193326Sed  MethodArgs[0] = Object;
5483193326Sed  for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5484193326Sed    MethodArgs[ArgIdx + 1] = Args[ArgIdx];
5485198092Srdivacky
5486198092Srdivacky  Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
5487193326Sed                                          SourceLocation());
5488193326Sed  UsualUnaryConversions(NewFn);
5489193326Sed
5490193326Sed  // Once we've built TheCall, all of the expressions are properly
5491193326Sed  // owned.
5492193326Sed  QualType ResultTy = Method->getResultType().getNonReferenceType();
5493198092Srdivacky  ExprOwningPtr<CXXOperatorCallExpr>
5494198092Srdivacky    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
5495193326Sed                                                    MethodArgs, NumArgs + 1,
5496193326Sed                                                    ResultTy, RParenLoc));
5497193326Sed  delete [] MethodArgs;
5498193326Sed
5499198092Srdivacky  if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5500198092Srdivacky                          Method))
5501198092Srdivacky    return true;
5502198092Srdivacky
5503193326Sed  // We may have default arguments. If so, we need to allocate more
5504193326Sed  // slots in the call for them.
5505193326Sed  if (NumArgs < NumArgsInProto)
5506193326Sed    TheCall->setNumArgs(Context, NumArgsInProto + 1);
5507193326Sed  else if (NumArgs > NumArgsInProto)
5508193326Sed    NumArgsToCheck = NumArgsInProto;
5509193326Sed
5510193326Sed  bool IsError = false;
5511193326Sed
5512193326Sed  // Initialize the implicit object parameter.
5513193326Sed  IsError |= PerformObjectArgumentInitialization(Object, Method);
5514193326Sed  TheCall->setArg(0, Object);
5515193326Sed
5516193326Sed
5517193326Sed  // Check the argument types.
5518193326Sed  for (unsigned i = 0; i != NumArgsToCheck; i++) {
5519193326Sed    Expr *Arg;
5520193326Sed    if (i < NumArgs) {
5521193326Sed      Arg = Args[i];
5522198092Srdivacky
5523193326Sed      // Pass the argument.
5524193326Sed      QualType ProtoArgType = Proto->getArgType(i);
5525193326Sed      IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
5526193326Sed    } else {
5527199482Srdivacky      OwningExprResult DefArg
5528199482Srdivacky        = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
5529199482Srdivacky      if (DefArg.isInvalid()) {
5530199482Srdivacky        IsError = true;
5531199482Srdivacky        break;
5532199482Srdivacky      }
5533199482Srdivacky
5534199482Srdivacky      Arg = DefArg.takeAs<Expr>();
5535193326Sed    }
5536193326Sed
5537193326Sed    TheCall->setArg(i + 1, Arg);
5538193326Sed  }
5539193326Sed
5540193326Sed  // If this is a variadic call, handle args passed through "...".
5541193326Sed  if (Proto->isVariadic()) {
5542193326Sed    // Promote the arguments (C99 6.5.2.2p7).
5543193326Sed    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5544193326Sed      Expr *Arg = Args[i];
5545193326Sed      IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
5546193326Sed      TheCall->setArg(i + 1, Arg);
5547193326Sed    }
5548193326Sed  }
5549193326Sed
5550193326Sed  if (IsError) return true;
5551193326Sed
5552198092Srdivacky  if (CheckFunctionCall(Method, TheCall.get()))
5553198092Srdivacky    return true;
5554198092Srdivacky
5555198092Srdivacky  return MaybeBindToTemporary(TheCall.release()).release();
5556193326Sed}
5557193326Sed
5558193326Sed/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
5559198092Srdivacky///  (if one exists), where @c Base is an expression of class type and
5560193326Sed/// @c Member is the name of the member we're trying to find.
5561198092SrdivackySema::OwningExprResult
5562198092SrdivackySema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5563198092Srdivacky  Expr *Base = static_cast<Expr *>(BaseIn.get());
5564193326Sed  assert(Base->getType()->isRecordType() && "left-hand side must have class type");
5565198092Srdivacky
5566193326Sed  // C++ [over.ref]p1:
5567193326Sed  //
5568193326Sed  //   [...] An expression x->m is interpreted as (x.operator->())->m
5569193326Sed  //   for a class object x of type T if T::operator->() exists and if
5570193326Sed  //   the operator is selected as the best match function by the
5571193326Sed  //   overload resolution mechanism (13.3).
5572193326Sed  DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5573193326Sed  OverloadCandidateSet CandidateSet;
5574198092Srdivacky  const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
5575198092Srdivacky
5576199482Srdivacky  if (RequireCompleteType(Base->getLocStart(), Base->getType(),
5577199482Srdivacky                          PDiag(diag::err_typecheck_incomplete_tag)
5578199482Srdivacky                            << Base->getSourceRange()))
5579199482Srdivacky    return ExprError();
5580198092Srdivacky
5581199482Srdivacky  LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
5582199482Srdivacky  LookupQualifiedName(R, BaseRecord->getDecl());
5583199482Srdivacky  R.suppressDiagnostics();
5584199482Srdivacky
5585198092Srdivacky  for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5586200583Srdivacky       Oper != OperEnd; ++Oper) {
5587200583Srdivacky    NamedDecl *D = *Oper;
5588200583Srdivacky    CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5589200583Srdivacky    if (isa<UsingShadowDecl>(D))
5590200583Srdivacky      D = cast<UsingShadowDecl>(D)->getTargetDecl();
5591200583Srdivacky
5592200583Srdivacky    AddMethodCandidate(cast<CXXMethodDecl>(D), ActingContext,
5593200583Srdivacky                       Base->getType(), 0, 0, CandidateSet,
5594193326Sed                       /*SuppressUserConversions=*/false);
5595200583Srdivacky  }
5596193326Sed
5597193326Sed  // Perform overload resolution.
5598193326Sed  OverloadCandidateSet::iterator Best;
5599194613Sed  switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
5600193326Sed  case OR_Success:
5601193326Sed    // Overload resolution succeeded; we'll build the call below.
5602193326Sed    break;
5603193326Sed
5604193326Sed  case OR_No_Viable_Function:
5605193326Sed    if (CandidateSet.empty())
5606193326Sed      Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5607198092Srdivacky        << Base->getType() << Base->getSourceRange();
5608193326Sed    else
5609193326Sed      Diag(OpLoc, diag::err_ovl_no_viable_oper)
5610198092Srdivacky        << "operator->" << Base->getSourceRange();
5611193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5612198092Srdivacky    return ExprError();
5613193326Sed
5614193326Sed  case OR_Ambiguous:
5615193326Sed    Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
5616198092Srdivacky      << "->" << Base->getSourceRange();
5617193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5618198092Srdivacky    return ExprError();
5619193326Sed
5620193326Sed  case OR_Deleted:
5621193326Sed    Diag(OpLoc,  diag::err_ovl_deleted_oper)
5622193326Sed      << Best->Function->isDeleted()
5623198092Srdivacky      << "->" << Base->getSourceRange();
5624193326Sed    PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5625198092Srdivacky    return ExprError();
5626193326Sed  }
5627193326Sed
5628193326Sed  // Convert the object parameter.
5629193326Sed  CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
5630193326Sed  if (PerformObjectArgumentInitialization(Base, Method))
5631198092Srdivacky    return ExprError();
5632193326Sed
5633193326Sed  // No concerns about early exits now.
5634198092Srdivacky  BaseIn.release();
5635193326Sed
5636193326Sed  // Build the operator call.
5637193326Sed  Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5638193326Sed                                           SourceLocation());
5639193326Sed  UsualUnaryConversions(FnExpr);
5640198092Srdivacky
5641198092Srdivacky  QualType ResultTy = Method->getResultType().getNonReferenceType();
5642198092Srdivacky  ExprOwningPtr<CXXOperatorCallExpr>
5643198092Srdivacky    TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5644198092Srdivacky                                                    &Base, 1, ResultTy, OpLoc));
5645198092Srdivacky
5646198092Srdivacky  if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5647198092Srdivacky                          Method))
5648198092Srdivacky          return ExprError();
5649198092Srdivacky  return move(TheCall);
5650193326Sed}
5651193326Sed
5652193326Sed/// FixOverloadedFunctionReference - E is an expression that refers to
5653193326Sed/// a C++ overloaded function (possibly with some parentheses and
5654193326Sed/// perhaps a '&' around it). We have resolved the overloaded function
5655193326Sed/// to the function declaration Fn, so patch up the expression E to
5656198398Srdivacky/// refer (possibly indirectly) to Fn. Returns the new expr.
5657198398SrdivackyExpr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5658193326Sed  if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5659199990Srdivacky    Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5660199990Srdivacky    if (SubExpr == PE->getSubExpr())
5661199990Srdivacky      return PE->Retain();
5662199990Srdivacky
5663199990Srdivacky    return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
5664199990Srdivacky  }
5665199990Srdivacky
5666199990Srdivacky  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5667199990Srdivacky    Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5668198893Srdivacky    assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5669199990Srdivacky                               SubExpr->getType()) &&
5670198893Srdivacky           "Implicit cast type cannot be determined from overload");
5671199990Srdivacky    if (SubExpr == ICE->getSubExpr())
5672199990Srdivacky      return ICE->Retain();
5673199990Srdivacky
5674199990Srdivacky    return new (Context) ImplicitCastExpr(ICE->getType(),
5675199990Srdivacky                                          ICE->getCastKind(),
5676199990Srdivacky                                          SubExpr,
5677199990Srdivacky                                          ICE->isLvalueCast());
5678199990Srdivacky  }
5679199990Srdivacky
5680199990Srdivacky  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
5681198092Srdivacky    assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
5682193326Sed           "Can only take the address of an overloaded function");
5683193326Sed    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5684193326Sed      if (Method->isStatic()) {
5685193326Sed        // Do nothing: static member functions aren't any different
5686193326Sed        // from non-member functions.
5687199990Srdivacky      } else {
5688199990Srdivacky        // Fix the sub expression, which really has to be an
5689199990Srdivacky        // UnresolvedLookupExpr holding an overloaded member function
5690199990Srdivacky        // or template.
5691199990Srdivacky        Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5692199990Srdivacky        if (SubExpr == UnOp->getSubExpr())
5693199990Srdivacky          return UnOp->Retain();
5694199990Srdivacky
5695199990Srdivacky        assert(isa<DeclRefExpr>(SubExpr)
5696199990Srdivacky               && "fixed to something other than a decl ref");
5697199990Srdivacky        assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
5698199990Srdivacky               && "fixed to a member ref with no nested name qualifier");
5699199990Srdivacky
5700199990Srdivacky        // We have taken the address of a pointer to member
5701199990Srdivacky        // function. Perform the computation here so that we get the
5702199990Srdivacky        // appropriate pointer to member type.
5703199990Srdivacky        QualType ClassType
5704199990Srdivacky          = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5705199990Srdivacky        QualType MemPtrType
5706199990Srdivacky          = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
5707199990Srdivacky
5708199990Srdivacky        return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5709199990Srdivacky                                           MemPtrType, UnOp->getOperatorLoc());
5710193326Sed      }
5711193326Sed    }
5712199990Srdivacky    Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5713199990Srdivacky    if (SubExpr == UnOp->getSubExpr())
5714199990Srdivacky      return UnOp->Retain();
5715198398Srdivacky
5716199990Srdivacky    return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
5717199990Srdivacky                                     Context.getPointerType(SubExpr->getType()),
5718199990Srdivacky                                       UnOp->getOperatorLoc());
5719199990Srdivacky  }
5720199990Srdivacky
5721199990Srdivacky  if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
5722200583Srdivacky    // FIXME: avoid copy.
5723200583Srdivacky    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5724199990Srdivacky    if (ULE->hasExplicitTemplateArgs()) {
5725200583Srdivacky      ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
5726200583Srdivacky      TemplateArgs = &TemplateArgsBuffer;
5727199990Srdivacky    }
5728199990Srdivacky
5729199990Srdivacky    return DeclRefExpr::Create(Context,
5730199990Srdivacky                               ULE->getQualifier(),
5731199990Srdivacky                               ULE->getQualifierRange(),
5732199990Srdivacky                               Fn,
5733199990Srdivacky                               ULE->getNameLoc(),
5734200583Srdivacky                               Fn->getType(),
5735200583Srdivacky                               TemplateArgs);
5736193326Sed  }
5737199990Srdivacky
5738199990Srdivacky  if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
5739199990Srdivacky    // FIXME: avoid copy.
5740200583Srdivacky    TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
5741200583Srdivacky    if (MemExpr->hasExplicitTemplateArgs()) {
5742200583Srdivacky      MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
5743200583Srdivacky      TemplateArgs = &TemplateArgsBuffer;
5744200583Srdivacky    }
5745199990Srdivacky
5746200583Srdivacky    Expr *Base;
5747200583Srdivacky
5748200583Srdivacky    // If we're filling in
5749200583Srdivacky    if (MemExpr->isImplicitAccess()) {
5750200583Srdivacky      if (cast<CXXMethodDecl>(Fn)->isStatic()) {
5751200583Srdivacky        return DeclRefExpr::Create(Context,
5752200583Srdivacky                                   MemExpr->getQualifier(),
5753200583Srdivacky                                   MemExpr->getQualifierRange(),
5754200583Srdivacky                                   Fn,
5755200583Srdivacky                                   MemExpr->getMemberLoc(),
5756200583Srdivacky                                   Fn->getType(),
5757200583Srdivacky                                   TemplateArgs);
5758200583Srdivacky      } else
5759200583Srdivacky        Base = new (Context) CXXThisExpr(SourceLocation(),
5760200583Srdivacky                                         MemExpr->getBaseType());
5761200583Srdivacky    } else
5762200583Srdivacky      Base = MemExpr->getBase()->Retain();
5763200583Srdivacky
5764200583Srdivacky    return MemberExpr::Create(Context, Base,
5765199990Srdivacky                              MemExpr->isArrow(),
5766199990Srdivacky                              MemExpr->getQualifier(),
5767199990Srdivacky                              MemExpr->getQualifierRange(),
5768199990Srdivacky                              Fn,
5769199990Srdivacky                              MemExpr->getMemberLoc(),
5770200583Srdivacky                              TemplateArgs,
5771199990Srdivacky                              Fn->getType());
5772199990Srdivacky  }
5773198398Srdivacky
5774199990Srdivacky  assert(false && "Invalid reference to overloaded function");
5775199990Srdivacky  return E->Retain();
5776193326Sed}
5777193326Sed
5778200583SrdivackySema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
5779200583Srdivacky                                                            FunctionDecl *Fn) {
5780200583Srdivacky  return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Fn));
5781200583Srdivacky}
5782200583Srdivacky
5783193326Sed} // end namespace clang
5784