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