blob: c3f330e371077fbb6489014f8c144cf85cac5ffe [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
John McCall7decc9e2010-11-18 06:31:45 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
John Wiegley01296292011-04-08 18:41:53 +000042 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
43 E = S.DefaultFunctionArrayConversion(E.take());
44 if (E.isInvalid())
45 return ExprError();
46 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000047}
48
John McCall5c32be02010-08-24 20:38:10 +000049static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
50 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000051 StandardConversionSequence &SCS,
52 bool CStyle);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000053
54static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
55 QualType &ToType,
56 bool InOverloadResolution,
57 StandardConversionSequence &SCS,
58 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000059static OverloadingResult
60IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
61 UserDefinedConversionSequence& User,
62 OverloadCandidateSet& Conversions,
63 bool AllowExplicit);
64
65
66static ImplicitConversionSequence::CompareKind
67CompareStandardConversionSequences(Sema &S,
68 const StandardConversionSequence& SCS1,
69 const StandardConversionSequence& SCS2);
70
71static ImplicitConversionSequence::CompareKind
72CompareQualificationConversions(Sema &S,
73 const StandardConversionSequence& SCS1,
74 const StandardConversionSequence& SCS2);
75
76static ImplicitConversionSequence::CompareKind
77CompareDerivedToBaseConversions(Sema &S,
78 const StandardConversionSequence& SCS1,
79 const StandardConversionSequence& SCS2);
80
81
82
Douglas Gregor5251f1b2008-10-21 16:13:35 +000083/// GetConversionCategory - Retrieve the implicit conversion
84/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000085ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086GetConversionCategory(ImplicitConversionKind Kind) {
87 static const ImplicitConversionCategory
88 Category[(int)ICK_Num_Conversion_Kinds] = {
89 ICC_Identity,
90 ICC_Lvalue_Transformation,
91 ICC_Lvalue_Transformation,
92 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000093 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000094 ICC_Qualification_Adjustment,
95 ICC_Promotion,
96 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000097 ICC_Promotion,
98 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Conversion,
101 ICC_Conversion,
102 ICC_Conversion,
103 ICC_Conversion,
104 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000107 ICC_Conversion,
108 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 ICC_Conversion
110 };
111 return Category[(int)Kind];
112}
113
114/// GetConversionRank - Retrieve the implicit conversion rank
115/// corresponding to the given implicit conversion kind.
116ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
117 static const ImplicitConversionRank
118 Rank[(int)ICK_Num_Conversion_Kinds] = {
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000124 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125 ICR_Promotion,
126 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000127 ICR_Promotion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000135 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000136 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000137 ICR_Conversion,
138 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000139 ICR_Complex_Real_Conversion,
140 ICR_Conversion,
141 ICR_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142 };
143 return Rank[(int)Kind];
144}
145
146/// GetImplicitConversionName - Return the name of this kind of
147/// implicit conversion.
148const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000149 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 "No conversion",
151 "Lvalue-to-rvalue",
152 "Array-to-pointer",
153 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000154 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 "Qualification",
156 "Integral promotion",
157 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000158 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "Integral conversion",
160 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000161 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000162 "Floating-integral conversion",
163 "Pointer conversion",
164 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000165 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000166 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000167 "Derived-to-base conversion",
168 "Vector conversion",
169 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000170 "Complex-real conversion",
171 "Block Pointer conversion",
172 "Transparent Union Conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000184 ReferenceBinding = false;
185 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000186 IsLvalueReference = true;
187 BindsToFunctionLvalue = false;
188 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000189 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000190 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191}
192
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000193/// getRank - Retrieve the rank of this standard conversion sequence
194/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
195/// implicit conversions.
196ImplicitConversionRank StandardConversionSequence::getRank() const {
197 ImplicitConversionRank Rank = ICR_Exact_Match;
198 if (GetConversionRank(First) > Rank)
199 Rank = GetConversionRank(First);
200 if (GetConversionRank(Second) > Rank)
201 Rank = GetConversionRank(Second);
202 if (GetConversionRank(Third) > Rank)
203 Rank = GetConversionRank(Third);
204 return Rank;
205}
206
207/// isPointerConversionToBool - Determines whether this conversion is
208/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000209/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000210/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000211bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000212 // Note that FromType has not necessarily been transformed by the
213 // array-to-pointer or function-to-pointer implicit conversions, so
214 // check for their presence as well as checking whether FromType is
215 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000216 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000217 (getFromType()->isPointerType() ||
218 getFromType()->isObjCObjectPointerType() ||
219 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000220 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
222 return true;
223
224 return false;
225}
226
Douglas Gregor5c407d92008-10-23 00:40:37 +0000227/// isPointerConversionToVoidPointer - Determines whether this
228/// conversion is a conversion of a pointer to a void pointer. This is
229/// used as part of the ranking of standard conversion sequences (C++
230/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000231bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000232StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000233isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000234 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000235 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000236
237 // Note that FromType has not necessarily been transformed by the
238 // array-to-pointer implicit conversion, so check for its presence
239 // and redo the conversion to get a pointer.
240 if (First == ICK_Array_To_Pointer)
241 FromType = Context.getArrayDecayedType(FromType);
242
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000243 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000244 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000245 return ToPtrType->getPointeeType()->isVoidType();
246
247 return false;
248}
249
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000250/// DebugPrint - Print this standard conversion sequence to standard
251/// error. Useful for debugging overloading issues.
252void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000254 bool PrintedSomething = false;
255 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 PrintedSomething = true;
258 }
259
260 if (Second != ICK_Identity) {
261 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000262 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000265
266 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000268 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000269 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000270 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000271 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000272 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273 PrintedSomething = true;
274 }
275
276 if (Third != ICK_Identity) {
277 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000285 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000286 }
287}
288
289/// DebugPrint - Print this user-defined conversion sequence to standard
290/// error. Useful for debugging overloading issues.
291void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000292 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000293 if (Before.First || Before.Second || Before.Third) {
294 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000295 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000297 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000298 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000299 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000300 After.DebugPrint();
301 }
302}
303
304/// DebugPrint - Print this implicit conversion sequence to standard
305/// error. Useful for debugging overloading issues.
306void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 switch (ConversionKind) {
309 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000310 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 Standard.DebugPrint();
312 break;
313 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000314 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000315 UserDefined.DebugPrint();
316 break;
317 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000318 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000319 break;
John McCall0d1da222010-01-12 00:44:57 +0000320 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000321 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000322 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000323 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000324 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000325 break;
326 }
327
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000328 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329}
330
John McCall0d1da222010-01-12 00:44:57 +0000331void AmbiguousConversionSequence::construct() {
332 new (&conversions()) ConversionSet();
333}
334
335void AmbiguousConversionSequence::destruct() {
336 conversions().~ConversionSet();
337}
338
339void
340AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
341 FromTypePtr = O.FromTypePtr;
342 ToTypePtr = O.ToTypePtr;
343 new (&conversions()) ConversionSet(O.conversions());
344}
345
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346namespace {
347 // Structure used by OverloadCandidate::DeductionFailureInfo to store
348 // template parameter and template argument information.
349 struct DFIParamWithArguments {
350 TemplateParameter Param;
351 TemplateArgument FirstArg;
352 TemplateArgument SecondArg;
353 };
354}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000356/// \brief Convert from Sema's representation of template deduction information
357/// to the form used in overload-candidate information.
358OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000359static MakeDeductionFailureInfo(ASTContext &Context,
360 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000361 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 OverloadCandidate::DeductionFailureInfo Result;
363 Result.Result = static_cast<unsigned>(TDK);
364 Result.Data = 0;
365 switch (TDK) {
366 case Sema::TDK_Success:
367 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000368 case Sema::TDK_TooManyArguments:
369 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000372 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000373 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000374 Result.Data = Info.Param.getOpaqueValue();
375 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000376
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000377 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000378 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000379 // FIXME: Should allocate from normal heap so that we can free this later.
380 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 Saved->Param = Info.Param;
382 Saved->FirstArg = Info.FirstArg;
383 Saved->SecondArg = Info.SecondArg;
384 Result.Data = Saved;
385 break;
386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000389 Result.Data = Info.take();
390 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000391
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000396
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000397 return Result;
398}
John McCall0d1da222010-01-12 00:44:57 +0000399
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000400void OverloadCandidate::DeductionFailureInfo::Destroy() {
401 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
402 case Sema::TDK_Success:
403 case Sema::TDK_InstantiationDepth:
404 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000407 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000409
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000410 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000411 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000412 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000413 Data = 0;
414 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000415
416 case Sema::TDK_SubstitutionFailure:
417 // FIXME: Destroy the template arugment list?
418 Data = 0;
419 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420
Douglas Gregor461761d2010-05-08 18:20:53 +0000421 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000423 case Sema::TDK_FailedOverloadResolution:
424 break;
425 }
426}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427
428TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000435 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000438 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000439 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000441
442 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000443 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000444 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000446 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000447 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000448 case Sema::TDK_FailedOverloadResolution:
449 break;
450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 return TemplateParameter();
453}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454
Douglas Gregord09efd42010-05-08 20:07:26 +0000455TemplateArgumentList *
456OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
457 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
458 case Sema::TDK_Success:
459 case Sema::TDK_InstantiationDepth:
460 case Sema::TDK_TooManyArguments:
461 case Sema::TDK_TooFewArguments:
462 case Sema::TDK_Incomplete:
463 case Sema::TDK_InvalidExplicitArguments:
464 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000466 return 0;
467
468 case Sema::TDK_SubstitutionFailure:
469 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
Douglas Gregord09efd42010-05-08 20:07:26 +0000471 // Unhandled
472 case Sema::TDK_NonDeducedMismatch:
473 case Sema::TDK_FailedOverloadResolution:
474 break;
475 }
476
477 return 0;
478}
479
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000480const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
481 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
482 case Sema::TDK_Success:
483 case Sema::TDK_InstantiationDepth:
484 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000485 case Sema::TDK_TooManyArguments:
486 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000487 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000488 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 return 0;
490
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000491 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000492 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494
Douglas Gregor461761d2010-05-08 18:20:53 +0000495 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000496 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000497 case Sema::TDK_FailedOverloadResolution:
498 break;
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000501 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503
504const TemplateArgument *
505OverloadCandidate::DeductionFailureInfo::getSecondArg() {
506 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
507 case Sema::TDK_Success:
508 case Sema::TDK_InstantiationDepth:
509 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000510 case Sema::TDK_TooManyArguments:
511 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000512 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000513 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514 return 0;
515
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000516 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000517 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000518 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
519
Douglas Gregor461761d2010-05-08 18:20:53 +0000520 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000521 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000522 case Sema::TDK_FailedOverloadResolution:
523 break;
524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000526 return 0;
527}
528
529void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 inherited::clear();
531 Functions.clear();
532}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000535// overload of the declarations in Old. This routine returns false if
536// New and Old cannot be overloaded, e.g., if New has the same
537// signature as some function in Old (C++ 1.3.10) or if the Old
538// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000539// it does return false, MatchedDecl will point to the decl that New
540// cannot be overloaded with. This decl may be a UsingShadowDecl on
541// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542//
543// Example: Given the following input:
544//
545// void f(int, float); // #1
546// void f(int, int); // #2
547// int f(int, int); // #3
548//
549// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000550// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551//
John McCall3d988d92009-12-02 08:47:38 +0000552// When we process #2, Old contains only the FunctionDecl for #1. By
553// comparing the parameter types, we see that #1 and #2 are overloaded
554// (since they have different signatures), so this routine returns
555// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000556//
John McCall3d988d92009-12-02 08:47:38 +0000557// When we process #3, Old is an overload set containing #1 and #2. We
558// compare the signatures of #3 to #1 (they're overloaded, so we do
559// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
560// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000561// signature), IsOverload returns false and MatchedDecl will be set to
562// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000563//
564// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
565// into a class by a using declaration. The rules for whether to hide
566// shadow declarations ignore some properties which otherwise figure
567// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000568Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000569Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
570 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000571 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000572 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000573 NamedDecl *OldD = *I;
574
575 bool OldIsUsingDecl = false;
576 if (isa<UsingShadowDecl>(OldD)) {
577 OldIsUsingDecl = true;
578
579 // We can always introduce two using declarations into the same
580 // context, even if they have identical signatures.
581 if (NewIsUsingDecl) continue;
582
583 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
584 }
585
586 // If either declaration was introduced by a using declaration,
587 // we'll need to use slightly different rules for matching.
588 // Essentially, these rules are the normal rules, except that
589 // function templates hide function templates with different
590 // return types or template parameter lists.
591 bool UseMemberUsingDeclRules =
592 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
593
John McCall3d988d92009-12-02 08:47:38 +0000594 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000595 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
596 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
597 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
598 continue;
599 }
600
John McCalldaa3d6b2009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 }
John McCall3d988d92009-12-02 08:47:38 +0000604 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000605 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
606 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
607 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
608 continue;
609 }
610
John McCalldaa3d6b2009-12-09 03:35:25 +0000611 Match = *I;
612 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000613 }
John McCalla8987a2942010-11-10 03:01:53 +0000614 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000615 // We can overload with these, which can show up when doing
616 // redeclaration checks for UsingDecls.
617 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000618 } else if (isa<TagDecl>(OldD)) {
619 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000620 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
621 // Optimistically assume that an unresolved using decl will
622 // overload; if it doesn't, we'll have to diagnose during
623 // template instantiation.
624 } else {
John McCall1f82f242009-11-18 22:49:29 +0000625 // (C++ 13p1):
626 // Only function declarations can be overloaded; object and type
627 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000628 Match = *I;
629 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000630 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000631 }
John McCall1f82f242009-11-18 22:49:29 +0000632
John McCalldaa3d6b2009-12-09 03:35:25 +0000633 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000634}
635
John McCalle9cccd82010-06-16 08:42:20 +0000636bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
637 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000638 // If both of the functions are extern "C", then they are not
639 // overloads.
640 if (Old->isExternC() && New->isExternC())
641 return false;
642
John McCall1f82f242009-11-18 22:49:29 +0000643 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
644 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
645
646 // C++ [temp.fct]p2:
647 // A function template can be overloaded with other function templates
648 // and with normal (non-template) functions.
649 if ((OldTemplate == 0) != (NewTemplate == 0))
650 return true;
651
652 // Is the function New an overload of the function Old?
653 QualType OldQType = Context.getCanonicalType(Old->getType());
654 QualType NewQType = Context.getCanonicalType(New->getType());
655
656 // Compare the signatures (C++ 1.3.10) of the two functions to
657 // determine whether they are overloads. If we find any mismatch
658 // in the signature, they are overloads.
659
660 // If either of these functions is a K&R-style function (no
661 // prototype), then we consider them to have matching signatures.
662 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
663 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
664 return false;
665
John McCall424cec92011-01-19 06:33:43 +0000666 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
667 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000668
669 // The signature of a function includes the types of its
670 // parameters (C++ 1.3.10), which includes the presence or absence
671 // of the ellipsis; see C++ DR 357).
672 if (OldQType != NewQType &&
673 (OldType->getNumArgs() != NewType->getNumArgs() ||
674 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000675 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000676 return true;
677
678 // C++ [temp.over.link]p4:
679 // The signature of a function template consists of its function
680 // signature, its return type and its template parameter list. The names
681 // of the template parameters are significant only for establishing the
682 // relationship between the template parameters and the rest of the
683 // signature.
684 //
685 // We check the return type and template parameter lists for function
686 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000687 //
688 // However, we don't consider either of these when deciding whether
689 // a member introduced by a shadow declaration is hidden.
690 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000691 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
692 OldTemplate->getTemplateParameters(),
693 false, TPL_TemplateMatch) ||
694 OldType->getResultType() != NewType->getResultType()))
695 return true;
696
697 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000698 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000699 //
700 // As part of this, also check whether one of the member functions
701 // is static, in which case they are not overloads (C++
702 // 13.1p2). While not part of the definition of the signature,
703 // this check is important to determine whether these functions
704 // can be overloaded.
705 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
706 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
707 if (OldMethod && NewMethod &&
708 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000709 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000710 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
711 if (!UseUsingDeclRules &&
712 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
713 (OldMethod->getRefQualifier() == RQ_None ||
714 NewMethod->getRefQualifier() == RQ_None)) {
715 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716 // - Member function declarations with the same name and the same
717 // parameter-type-list as well as member function template
718 // declarations with the same name, the same parameter-type-list, and
719 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000720 // them, but not all, have a ref-qualifier (8.3.5).
721 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
722 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
723 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
John McCall1f82f242009-11-18 22:49:29 +0000726 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
John McCall1f82f242009-11-18 22:49:29 +0000729 // The signatures match; this is not an overload.
730 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000731}
732
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000733/// TryImplicitConversion - Attempt to perform an implicit conversion
734/// from the given expression (Expr) to the given type (ToType). This
735/// function returns an implicit conversion sequence that can be used
736/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737///
738/// void f(float f);
739/// void g(int i) { f(i); }
740///
741/// this routine would produce an implicit conversion sequence to
742/// describe the initialization of f from i, which will be a standard
743/// conversion sequence containing an lvalue-to-rvalue conversion (C++
744/// 4.1) followed by a floating-integral conversion (C++ 4.9).
745//
746/// Note that this routine only determines how the conversion can be
747/// performed; it does not actually perform the conversion. As such,
748/// it will not produce any diagnostics if no conversion is available,
749/// but will instead return an implicit conversion sequence of kind
750/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000751///
752/// If @p SuppressUserConversions, then user-defined conversions are
753/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000754/// If @p AllowExplicit, then explicit user-defined conversions are
755/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000756static ImplicitConversionSequence
757TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
758 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000760 bool InOverloadResolution,
761 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000762 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000763 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +0000764 ICS.Standard, CStyle)) {
John McCall0d1da222010-01-12 00:44:57 +0000765 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000766 return ICS;
767 }
768
John McCall5c32be02010-08-24 20:38:10 +0000769 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000770 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000771 return ICS;
772 }
773
Douglas Gregor836a7e82010-08-11 02:15:33 +0000774 // C++ [over.ics.user]p4:
775 // A conversion of an expression of class type to the same class
776 // type is given Exact Match rank, and a conversion of an
777 // expression of class type to a base class of that type is
778 // given Conversion rank, in spite of the fact that a copy/move
779 // constructor (i.e., a user-defined conversion function) is
780 // called for those cases.
781 QualType FromType = From->getType();
782 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000783 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
784 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000785 ICS.setStandard();
786 ICS.Standard.setAsIdentityConversion();
787 ICS.Standard.setFromType(FromType);
788 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789
Douglas Gregor5ab11652010-04-17 22:01:05 +0000790 // We don't actually check at this point whether there is a valid
791 // copy/move constructor, since overloading just assumes that it
792 // exists. When we actually perform initialization, we'll find the
793 // appropriate constructor to copy the returned object, if needed.
794 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor5ab11652010-04-17 22:01:05 +0000796 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000797 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000798 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799
Douglas Gregor836a7e82010-08-11 02:15:33 +0000800 return ICS;
801 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802
Douglas Gregor836a7e82010-08-11 02:15:33 +0000803 if (SuppressUserConversions) {
804 // We're not in the case above, so there is no conversion that
805 // we can perform.
806 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000807 return ICS;
808 }
809
810 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000811 OverloadCandidateSet Conversions(From->getExprLoc());
812 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000813 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000814 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000815
816 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000817 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000818 // C++ [over.ics.user]p4:
819 // A conversion of an expression of class type to the same class
820 // type is given Exact Match rank, and a conversion of an
821 // expression of class type to a base class of that type is
822 // given Conversion rank, in spite of the fact that a copy
823 // constructor (i.e., a user-defined conversion function) is
824 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000825 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000826 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000827 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000828 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
829 QualType ToCanon
830 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000831 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000832 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000833 // Turn this into a "standard" conversion sequence, so that it
834 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000835 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000836 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000837 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000838 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000839 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000840 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000841 ICS.Standard.Second = ICK_Derived_To_Base;
842 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000843 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000844
845 // C++ [over.best.ics]p4:
846 // However, when considering the argument of a user-defined
847 // conversion function that is a candidate by 13.3.1.3 when
848 // invoked for the copying of the temporary in the second step
849 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
850 // 13.3.1.6 in all cases, only standard conversion sequences and
851 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000852 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000853 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000854 }
John McCalle8c8cd22010-01-13 22:30:33 +0000855 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000856 ICS.setAmbiguous();
857 ICS.Ambiguous.setFromType(From->getType());
858 ICS.Ambiguous.setToType(ToType);
859 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
860 Cand != Conversions.end(); ++Cand)
861 if (Cand->Viable)
862 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000863 } else {
John McCall65eb8792010-02-25 01:37:24 +0000864 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000865 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000866
867 return ICS;
868}
869
John McCall5c32be02010-08-24 20:38:10 +0000870bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
871 const InitializedEntity &Entity,
872 Expr *Initializer,
873 bool SuppressUserConversions,
874 bool AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000875 bool InOverloadResolution,
876 bool CStyle) {
John McCall5c32be02010-08-24 20:38:10 +0000877 ImplicitConversionSequence ICS
878 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
879 SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000880 AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000881 InOverloadResolution,
882 CStyle);
John McCall5c32be02010-08-24 20:38:10 +0000883 if (ICS.isBad()) return true;
884
885 // Perform the actual conversion.
886 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
887 return false;
888}
889
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000890/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000891/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000892/// converted expression. Flavor is the kind of conversion we're
893/// performing, used in the error message. If @p AllowExplicit,
894/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000895ExprResult
896Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000897 AssignmentAction Action, bool AllowExplicit) {
898 ImplicitConversionSequence ICS;
899 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
900}
901
John Wiegley01296292011-04-08 18:41:53 +0000902ExprResult
903Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000904 AssignmentAction Action, bool AllowExplicit,
905 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000906 ICS = clang::TryImplicitConversion(*this, From, ToType,
907 /*SuppressUserConversions=*/false,
908 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000909 /*InOverloadResolution=*/false,
910 /*CStyle=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000911 return PerformImplicitConversion(From, ToType, ICS, Action);
912}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
914/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000915/// conversion that strips "noreturn" off the nested function type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000917 QualType ToType, QualType &ResultTy) {
918 if (Context.hasSameUnqualifiedType(FromType, ToType))
919 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920
John McCall991eb4b2010-12-21 00:44:39 +0000921 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
922 // where F adds one of the following at most once:
923 // - a pointer
924 // - a member pointer
925 // - a block pointer
926 CanQualType CanTo = Context.getCanonicalType(ToType);
927 CanQualType CanFrom = Context.getCanonicalType(FromType);
928 Type::TypeClass TyClass = CanTo->getTypeClass();
929 if (TyClass != CanFrom->getTypeClass()) return false;
930 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
931 if (TyClass == Type::Pointer) {
932 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
933 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
934 } else if (TyClass == Type::BlockPointer) {
935 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
936 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
937 } else if (TyClass == Type::MemberPointer) {
938 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
939 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
940 } else {
941 return false;
942 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000943
John McCall991eb4b2010-12-21 00:44:39 +0000944 TyClass = CanTo->getTypeClass();
945 if (TyClass != CanFrom->getTypeClass()) return false;
946 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
947 return false;
948 }
949
950 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
951 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
952 if (!EInfo.getNoReturn()) return false;
953
954 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
955 assert(QualType(FromFn, 0).isCanonical());
956 if (QualType(FromFn, 0) != CanTo) return false;
957
958 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000959 return true;
960}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
Douglas Gregor46188682010-05-18 22:42:18 +0000962/// \brief Determine whether the conversion from FromType to ToType is a valid
963/// vector conversion.
964///
965/// \param ICK Will be set to the vector conversion kind, if this is a vector
966/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967static bool IsVectorConversion(ASTContext &Context, QualType FromType,
968 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000969 // We need at least one of these types to be a vector type to have a vector
970 // conversion.
971 if (!ToType->isVectorType() && !FromType->isVectorType())
972 return false;
973
974 // Identical types require no conversions.
975 if (Context.hasSameUnqualifiedType(FromType, ToType))
976 return false;
977
978 // There are no conversions between extended vector types, only identity.
979 if (ToType->isExtVectorType()) {
980 // There are no conversions between extended vector types other than the
981 // identity conversion.
982 if (FromType->isExtVectorType())
983 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000984
Douglas Gregor46188682010-05-18 22:42:18 +0000985 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000986 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000987 ICK = ICK_Vector_Splat;
988 return true;
989 }
990 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000991
992 // We can perform the conversion between vector types in the following cases:
993 // 1)vector types are equivalent AltiVec and GCC vector types
994 // 2)lax vector conversions are permitted and the vector types are of the
995 // same size
996 if (ToType->isVectorType() && FromType->isVectorType()) {
997 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000998 (Context.getLangOptions().LaxVectorConversions &&
999 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001000 ICK = ICK_Vector_Conversion;
1001 return true;
1002 }
Douglas Gregor46188682010-05-18 22:42:18 +00001003 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001004
Douglas Gregor46188682010-05-18 22:42:18 +00001005 return false;
1006}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001008/// IsStandardConversion - Determines whether there is a standard
1009/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1010/// expression From to the type ToType. Standard conversion sequences
1011/// only consider non-class types; for conversions that involve class
1012/// types, use TryImplicitConversion. If a conversion exists, SCS will
1013/// contain the standard conversion sequence required to perform this
1014/// conversion and this routine will return true. Otherwise, this
1015/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001016static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1017 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001018 StandardConversionSequence &SCS,
1019 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001020 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001022 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001023 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001024 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001025 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001026 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001027 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001029 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001030 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001031 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001032 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001033 return false;
1034
Mike Stump11289f42009-09-09 15:08:12 +00001035 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001036 }
1037
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038 // The first conversion can be an lvalue-to-rvalue conversion,
1039 // array-to-pointer conversion, or function-to-pointer conversion
1040 // (C++ 4p1).
1041
John McCall5c32be02010-08-24 20:38:10 +00001042 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001043 DeclAccessPair AccessPair;
1044 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001046 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001047 // We were able to resolve the address of the overloaded function,
1048 // so we can convert to the type of that function.
1049 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001050
1051 // we can sometimes resolve &foo<int> regardless of ToType, so check
1052 // if the type matches (identity) or we are converting to bool
1053 if (!S.Context.hasSameUnqualifiedType(
1054 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1055 QualType resultTy;
1056 // if the function type matches except for [[noreturn]], it's ok
1057 if (!IsNoReturnConversion(S.Context, FromType,
1058 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1059 // otherwise, only a boolean conversion is standard
1060 if (!ToType->isBooleanType())
1061 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001063
Chandler Carruthffce2452011-03-29 08:08:18 +00001064 // Check if the "from" expression is taking the address of an overloaded
1065 // function and recompute the FromType accordingly. Take advantage of the
1066 // fact that non-static member functions *must* have such an address-of
1067 // expression.
1068 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1069 if (Method && !Method->isStatic()) {
1070 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1071 "Non-unary operator on non-static member address");
1072 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1073 == UO_AddrOf &&
1074 "Non-address-of operator on non-static member address");
1075 const Type *ClassType
1076 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1077 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001078 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1079 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1080 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001081 "Non-address-of operator for overloaded function expression");
1082 FromType = S.Context.getPointerType(FromType);
1083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
Douglas Gregor980fb162010-04-29 18:24:40 +00001085 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001086 assert(S.Context.hasSameType(
1087 FromType,
1088 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001089 } else {
1090 return false;
1091 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001092 }
Mike Stump11289f42009-09-09 15:08:12 +00001093 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001094 // An lvalue (3.10) of a non-function, non-array type T can be
1095 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001096 bool argIsLValue = From->isLValue();
1097 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001098 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001099 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001100 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001101
1102 // If T is a non-class type, the type of the rvalue is the
1103 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001104 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1105 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001106 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001107 } else if (FromType->isArrayType()) {
1108 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001109 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110
1111 // An lvalue or rvalue of type "array of N T" or "array of unknown
1112 // bound of T" can be converted to an rvalue of type "pointer to
1113 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001114 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115
John McCall5c32be02010-08-24 20:38:10 +00001116 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001117 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001118 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119
1120 // For the purpose of ranking in overload resolution
1121 // (13.3.3.1.1), this conversion is considered an
1122 // array-to-pointer conversion followed by a qualification
1123 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001124 SCS.Second = ICK_Identity;
1125 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001126 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001127 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128 }
John McCall086a4642010-11-24 05:12:34 +00001129 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001130 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001131 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132
1133 // An lvalue of function type T can be converted to an rvalue of
1134 // type "pointer to T." The result is a pointer to the
1135 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001136 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001137 } else {
1138 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001139 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001141 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142
1143 // The second conversion can be an integral promotion, floating
1144 // point promotion, integral conversion, floating point conversion,
1145 // floating-integral conversion, pointer conversion,
1146 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001147 // For overloading in C, this can also be a "compatible-type"
1148 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001149 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001150 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001151 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 // The unqualified versions of the types are the same: there's no
1153 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001154 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001155 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001156 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001157 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001159 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001160 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001161 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001163 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001164 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001165 SCS.Second = ICK_Complex_Promotion;
1166 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001167 } else if (ToType->isBooleanType() &&
1168 (FromType->isArithmeticType() ||
1169 FromType->isAnyPointerType() ||
1170 FromType->isBlockPointerType() ||
1171 FromType->isMemberPointerType() ||
1172 FromType->isNullPtrType())) {
1173 // Boolean conversions (C++ 4.12).
1174 SCS.Second = ICK_Boolean_Conversion;
1175 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001176 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001177 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001178 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001179 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001181 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001182 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001183 SCS.Second = ICK_Complex_Conversion;
1184 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001185 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1186 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001187 // Complex-real conversions (C99 6.3.1.7)
1188 SCS.Second = ICK_Complex_Real;
1189 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001190 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001191 // Floating point conversions (C++ 4.8).
1192 SCS.Second = ICK_Floating_Conversion;
1193 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001195 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001196 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001197 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001198 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001199 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001201 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1202 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001203 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1204 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001205 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001206 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001207 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001208 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001210 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001211 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001212 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001213 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001214 SCS.Second = SecondICK;
1215 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001216 } else if (!S.getLangOptions().CPlusPlus &&
1217 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001218 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001219 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001220 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001221 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001222 // Treat a conversion that strips "noreturn" as an identity conversion.
1223 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001224 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1225 InOverloadResolution,
1226 SCS, CStyle)) {
1227 SCS.Second = ICK_TransparentUnionConversion;
1228 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229 } else {
1230 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001231 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001232 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001233 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001234
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001235 QualType CanonFrom;
1236 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001237 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001238 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001239 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001241 CanonFrom = S.Context.getCanonicalType(FromType);
1242 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001243 } else {
1244 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001245 SCS.Third = ICK_Identity;
1246
Mike Stump11289f42009-09-09 15:08:12 +00001247 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001248 // [...] Any difference in top-level cv-qualification is
1249 // subsumed by the initialization itself and does not constitute
1250 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001251 CanonFrom = S.Context.getCanonicalType(FromType);
1252 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001253 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001254 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001255 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1256 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001257 FromType = ToType;
1258 CanonFrom = CanonTo;
1259 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001260 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001261 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001262
1263 // If we have not converted the argument type to the parameter type,
1264 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001265 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001266 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001267
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001268 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001269}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001270
1271static bool
1272IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1273 QualType &ToType,
1274 bool InOverloadResolution,
1275 StandardConversionSequence &SCS,
1276 bool CStyle) {
1277
1278 const RecordType *UT = ToType->getAsUnionType();
1279 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1280 return false;
1281 // The field to initialize within the transparent union.
1282 RecordDecl *UD = UT->getDecl();
1283 // It's compatible if the expression matches any of the fields.
1284 for (RecordDecl::field_iterator it = UD->field_begin(),
1285 itend = UD->field_end();
1286 it != itend; ++it) {
1287 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, CStyle)) {
1288 ToType = it->getType();
1289 return true;
1290 }
1291 }
1292 return false;
1293}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001294
1295/// IsIntegralPromotion - Determines whether the conversion from the
1296/// expression From (whose potentially-adjusted type is FromType) to
1297/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1298/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001299bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001300 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001301 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001302 if (!To) {
1303 return false;
1304 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001305
1306 // An rvalue of type char, signed char, unsigned char, short int, or
1307 // unsigned short int can be converted to an rvalue of type int if
1308 // int can represent all the values of the source type; otherwise,
1309 // the source rvalue can be converted to an rvalue of type unsigned
1310 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001311 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1312 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001313 if (// We can promote any signed, promotable integer type to an int
1314 (FromType->isSignedIntegerType() ||
1315 // We can promote any unsigned integer type whose size is
1316 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001317 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001318 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001319 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001320 }
1321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001322 return To->getKind() == BuiltinType::UInt;
1323 }
1324
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001325 // C++0x [conv.prom]p3:
1326 // A prvalue of an unscoped enumeration type whose underlying type is not
1327 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1328 // following types that can represent all the values of the enumeration
1329 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1330 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001331 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001332 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001333 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334 // with lowest integer conversion rank (4.13) greater than the rank of long
1335 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001336 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001337 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1338 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1339 // provided for a scoped enumeration.
1340 if (FromEnumType->getDecl()->isScoped())
1341 return false;
1342
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001343 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001344 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001345 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001346 return Context.hasSameUnqualifiedType(ToType,
1347 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001348 }
John McCall56774992009-12-09 09:09:27 +00001349
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001350 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001351 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1352 // to an rvalue a prvalue of the first of the following types that can
1353 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001354 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001356 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001358 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001360 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001361 // Determine whether the type we're converting from is signed or
1362 // unsigned.
1363 bool FromIsSigned;
1364 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001365
John McCall56774992009-12-09 09:09:27 +00001366 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1367 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001368
1369 // The types we'll try to promote to, in the appropriate
1370 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001371 QualType PromoteTypes[6] = {
1372 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001373 Context.LongTy, Context.UnsignedLongTy ,
1374 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001375 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001376 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001377 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1378 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001379 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001380 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1381 // We found the type that we can promote to. If this is the
1382 // type we wanted, we have a promotion. Otherwise, no
1383 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001384 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001385 }
1386 }
1387 }
1388
1389 // An rvalue for an integral bit-field (9.6) can be converted to an
1390 // rvalue of type int if int can represent all the values of the
1391 // bit-field; otherwise, it can be converted to unsigned int if
1392 // unsigned int can represent all the values of the bit-field. If
1393 // the bit-field is larger yet, no integral promotion applies to
1394 // it. If the bit-field has an enumerated type, it is treated as any
1395 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001396 // FIXME: We should delay checking of bit-fields until we actually perform the
1397 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001398 using llvm::APSInt;
1399 if (From)
1400 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001401 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001402 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001403 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1404 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1405 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001406
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001407 // Are we promoting to an int from a bitfield that fits in an int?
1408 if (BitWidth < ToSize ||
1409 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1410 return To->getKind() == BuiltinType::Int;
1411 }
Mike Stump11289f42009-09-09 15:08:12 +00001412
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001413 // Are we promoting to an unsigned int from an unsigned bitfield
1414 // that fits into an unsigned int?
1415 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1416 return To->getKind() == BuiltinType::UInt;
1417 }
Mike Stump11289f42009-09-09 15:08:12 +00001418
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001419 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001420 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421 }
Mike Stump11289f42009-09-09 15:08:12 +00001422
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001423 // An rvalue of type bool can be converted to an rvalue of type int,
1424 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001425 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001426 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001427 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001428
1429 return false;
1430}
1431
1432/// IsFloatingPointPromotion - Determines whether the conversion from
1433/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1434/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001435bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001436 /// An rvalue of type float can be converted to an rvalue of type
1437 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001438 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1439 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001440 if (FromBuiltin->getKind() == BuiltinType::Float &&
1441 ToBuiltin->getKind() == BuiltinType::Double)
1442 return true;
1443
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001444 // C99 6.3.1.5p1:
1445 // When a float is promoted to double or long double, or a
1446 // double is promoted to long double [...].
1447 if (!getLangOptions().CPlusPlus &&
1448 (FromBuiltin->getKind() == BuiltinType::Float ||
1449 FromBuiltin->getKind() == BuiltinType::Double) &&
1450 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1451 return true;
1452 }
1453
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001454 return false;
1455}
1456
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001457/// \brief Determine if a conversion is a complex promotion.
1458///
1459/// A complex promotion is defined as a complex -> complex conversion
1460/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001461/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001462bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001463 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001464 if (!FromComplex)
1465 return false;
1466
John McCall9dd450b2009-09-21 23:43:11 +00001467 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001468 if (!ToComplex)
1469 return false;
1470
1471 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001472 ToComplex->getElementType()) ||
1473 IsIntegralPromotion(0, FromComplex->getElementType(),
1474 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001475}
1476
Douglas Gregor237f96c2008-11-26 23:31:11 +00001477/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1478/// the pointer type FromPtr to a pointer to type ToPointee, with the
1479/// same type qualifiers as FromPtr has on its pointee type. ToType,
1480/// if non-empty, will be a pointer to ToType that may or may not have
1481/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001482static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001483BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001484 QualType ToPointee, QualType ToType,
1485 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001486 assert((FromPtr->getTypeClass() == Type::Pointer ||
1487 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1488 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001490 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1491 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1492 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001493
1494 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001495 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001496 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001497 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001498
1499 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001500 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001501 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001502 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001503 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001504
1505 // Build a pointer to ToPointee. It has the right qualifiers
1506 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001507 if (isa<ObjCObjectPointerType>(ToType))
1508 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001509 return Context.getPointerType(ToPointee);
1510 }
1511
1512 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001513 QualType QualifiedCanonToPointee
1514 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001515
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001516 if (isa<ObjCObjectPointerType>(ToType))
1517 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1518 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001519}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520
Mike Stump11289f42009-09-09 15:08:12 +00001521static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001522 bool InOverloadResolution,
1523 ASTContext &Context) {
1524 // Handle value-dependent integral null pointer constants correctly.
1525 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1526 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001527 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001528 return !InOverloadResolution;
1529
Douglas Gregor56751b52009-09-25 04:25:58 +00001530 return Expr->isNullPointerConstant(Context,
1531 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1532 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001533}
Mike Stump11289f42009-09-09 15:08:12 +00001534
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001535/// IsPointerConversion - Determines whether the conversion of the
1536/// expression From, which has the (possibly adjusted) type FromType,
1537/// can be converted to the type ToType via a pointer conversion (C++
1538/// 4.10). If so, returns true and places the converted type (that
1539/// might differ from ToType in its cv-qualifiers at some level) into
1540/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001541///
Douglas Gregora29dc052008-11-27 01:19:21 +00001542/// This routine also supports conversions to and from block pointers
1543/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1544/// pointers to interfaces. FIXME: Once we've determined the
1545/// appropriate overloading rules for Objective-C, we may want to
1546/// split the Objective-C checks into a different routine; however,
1547/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001548/// conversions, so for now they live here. IncompatibleObjC will be
1549/// set if the conversion is an allowed Objective-C conversion that
1550/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001552 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001553 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001554 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001555 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001556 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1557 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001558 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001559
Mike Stump11289f42009-09-09 15:08:12 +00001560 // Conversion from a null pointer constant to any Objective-C pointer type.
1561 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001562 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001563 ConvertedType = ToType;
1564 return true;
1565 }
1566
Douglas Gregor231d1c62008-11-27 00:15:41 +00001567 // Blocks: Block pointers can be converted to void*.
1568 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001569 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001570 ConvertedType = ToType;
1571 return true;
1572 }
1573 // Blocks: A null pointer constant can be converted to a block
1574 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001575 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001576 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001577 ConvertedType = ToType;
1578 return true;
1579 }
1580
Sebastian Redl576fd422009-05-10 18:38:11 +00001581 // If the left-hand-side is nullptr_t, the right side can be a null
1582 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001583 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001584 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001585 ConvertedType = ToType;
1586 return true;
1587 }
1588
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001589 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 if (!ToTypePtr)
1591 return false;
1592
1593 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001594 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001595 ConvertedType = ToType;
1596 return true;
1597 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001598
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001599 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001600 // , including objective-c pointers.
1601 QualType ToPointeeType = ToTypePtr->getPointeeType();
1602 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001603 ConvertedType = BuildSimilarlyQualifiedPointerType(
1604 FromType->getAs<ObjCObjectPointerType>(),
1605 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001606 ToType, Context);
1607 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001608 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001609 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001610 if (!FromTypePtr)
1611 return false;
1612
1613 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001614
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001615 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001616 // pointer conversion, so don't do all of the work below.
1617 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1618 return false;
1619
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001620 // An rvalue of type "pointer to cv T," where T is an object type,
1621 // can be converted to an rvalue of type "pointer to cv void" (C++
1622 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001623 if (FromPointeeType->isIncompleteOrObjectType() &&
1624 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001625 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001626 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001627 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 return true;
1629 }
1630
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001631 // MSVC allows implicit function to void* type conversion.
1632 if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() &&
1633 ToPointeeType->isVoidType()) {
1634 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1635 ToPointeeType,
1636 ToType, Context);
1637 return true;
1638 }
1639
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001640 // When we're overloading in C, we allow a special kind of pointer
1641 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001642 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001643 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001644 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001645 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001646 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001647 return true;
1648 }
1649
Douglas Gregor5c407d92008-10-23 00:40:37 +00001650 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001651 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001652 // An rvalue of type "pointer to cv D," where D is a class type,
1653 // can be converted to an rvalue of type "pointer to cv B," where
1654 // B is a base class (clause 10) of D. If B is an inaccessible
1655 // (clause 11) or ambiguous (10.2) base class of D, a program that
1656 // necessitates this conversion is ill-formed. The result of the
1657 // conversion is a pointer to the base class sub-object of the
1658 // derived class object. The null pointer value is converted to
1659 // the null pointer value of the destination type.
1660 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001661 // Note that we do not check for ambiguity or inaccessibility
1662 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001663 if (getLangOptions().CPlusPlus &&
1664 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001665 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001666 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001667 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001668 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001669 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001670 ToType, Context);
1671 return true;
1672 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001673
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001674 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1675 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1676 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1677 ToPointeeType,
1678 ToType, Context);
1679 return true;
1680 }
1681
Douglas Gregora119f102008-12-19 19:13:09 +00001682 return false;
1683}
Douglas Gregoraec25842011-04-26 23:16:46 +00001684
1685/// \brief Adopt the given qualifiers for the given type.
1686static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1687 Qualifiers TQs = T.getQualifiers();
1688
1689 // Check whether qualifiers already match.
1690 if (TQs == Qs)
1691 return T;
1692
1693 if (Qs.compatiblyIncludes(TQs))
1694 return Context.getQualifiedType(T, Qs);
1695
1696 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1697}
Douglas Gregora119f102008-12-19 19:13:09 +00001698
1699/// isObjCPointerConversion - Determines whether this is an
1700/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1701/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001702bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001703 QualType& ConvertedType,
1704 bool &IncompatibleObjC) {
1705 if (!getLangOptions().ObjC1)
1706 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001707
Douglas Gregoraec25842011-04-26 23:16:46 +00001708 // The set of qualifiers on the type we're converting from.
1709 Qualifiers FromQualifiers = FromType.getQualifiers();
1710
Steve Naroff7cae42b2009-07-10 23:34:53 +00001711 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001712 const ObjCObjectPointerType* ToObjCPtr =
1713 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001714 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001715 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001716
Steve Naroff7cae42b2009-07-10 23:34:53 +00001717 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001718 // If the pointee types are the same (ignoring qualifications),
1719 // then this is not a pointer conversion.
1720 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1721 FromObjCPtr->getPointeeType()))
1722 return false;
1723
Douglas Gregoraec25842011-04-26 23:16:46 +00001724 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001725 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001726 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001727 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001728 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001729 return true;
1730 }
1731 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001732 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001733 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001734 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001735 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001736 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001737 return true;
1738 }
1739 // Objective C++: We're able to convert from a pointer to an
1740 // interface to a pointer to a different interface.
1741 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001742 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1743 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1744 if (getLangOptions().CPlusPlus && LHS && RHS &&
1745 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1746 FromObjCPtr->getPointeeType()))
1747 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001748 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001749 ToObjCPtr->getPointeeType(),
1750 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001751 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001752 return true;
1753 }
1754
1755 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1756 // Okay: this is some kind of implicit downcast of Objective-C
1757 // interfaces, which is permitted. However, we're going to
1758 // complain about it.
1759 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001760 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001761 ToObjCPtr->getPointeeType(),
1762 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001763 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001764 return true;
1765 }
Mike Stump11289f42009-09-09 15:08:12 +00001766 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001767 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001768 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001769 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001770 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001771 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001772 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001773 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001774 // to a block pointer type.
1775 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001776 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001777 return true;
1778 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001779 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001781 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001782 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001783 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001784 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001785 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001786 return true;
1787 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001788 else
Douglas Gregora119f102008-12-19 19:13:09 +00001789 return false;
1790
Douglas Gregor033f56d2008-12-23 00:53:59 +00001791 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001792 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001793 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001794 else if (const BlockPointerType *FromBlockPtr =
1795 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001796 FromPointeeType = FromBlockPtr->getPointeeType();
1797 else
Douglas Gregora119f102008-12-19 19:13:09 +00001798 return false;
1799
Douglas Gregora119f102008-12-19 19:13:09 +00001800 // If we have pointers to pointers, recursively check whether this
1801 // is an Objective-C conversion.
1802 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1803 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1804 IncompatibleObjC)) {
1805 // We always complain about this conversion.
1806 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001807 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001808 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001809 return true;
1810 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001811 // Allow conversion of pointee being objective-c pointer to another one;
1812 // as in I* to id.
1813 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1814 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1815 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1816 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001817 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001818 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001819 return true;
1820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821
Douglas Gregor033f56d2008-12-23 00:53:59 +00001822 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001823 // differences in the argument and result types are in Objective-C
1824 // pointer conversions. If so, we permit the conversion (but
1825 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001826 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001827 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001828 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001829 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001830 if (FromFunctionType && ToFunctionType) {
1831 // If the function types are exactly the same, this isn't an
1832 // Objective-C pointer conversion.
1833 if (Context.getCanonicalType(FromPointeeType)
1834 == Context.getCanonicalType(ToPointeeType))
1835 return false;
1836
1837 // Perform the quick checks that will tell us whether these
1838 // function types are obviously different.
1839 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1840 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1841 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1842 return false;
1843
1844 bool HasObjCConversion = false;
1845 if (Context.getCanonicalType(FromFunctionType->getResultType())
1846 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1847 // Okay, the types match exactly. Nothing to do.
1848 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1849 ToFunctionType->getResultType(),
1850 ConvertedType, IncompatibleObjC)) {
1851 // Okay, we have an Objective-C pointer conversion.
1852 HasObjCConversion = true;
1853 } else {
1854 // Function types are too different. Abort.
1855 return false;
1856 }
Mike Stump11289f42009-09-09 15:08:12 +00001857
Douglas Gregora119f102008-12-19 19:13:09 +00001858 // Check argument types.
1859 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1860 ArgIdx != NumArgs; ++ArgIdx) {
1861 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1862 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1863 if (Context.getCanonicalType(FromArgType)
1864 == Context.getCanonicalType(ToArgType)) {
1865 // Okay, the types match exactly. Nothing to do.
1866 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1867 ConvertedType, IncompatibleObjC)) {
1868 // Okay, we have an Objective-C pointer conversion.
1869 HasObjCConversion = true;
1870 } else {
1871 // Argument types are too different. Abort.
1872 return false;
1873 }
1874 }
1875
1876 if (HasObjCConversion) {
1877 // We had an Objective-C conversion. Allow this pointer
1878 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001879 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001880 IncompatibleObjC = true;
1881 return true;
1882 }
1883 }
1884
Sebastian Redl72b597d2009-01-25 19:43:20 +00001885 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001886}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001888bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1889 QualType& ConvertedType) {
1890 QualType ToPointeeType;
1891 if (const BlockPointerType *ToBlockPtr =
1892 ToType->getAs<BlockPointerType>())
1893 ToPointeeType = ToBlockPtr->getPointeeType();
1894 else
1895 return false;
1896
1897 QualType FromPointeeType;
1898 if (const BlockPointerType *FromBlockPtr =
1899 FromType->getAs<BlockPointerType>())
1900 FromPointeeType = FromBlockPtr->getPointeeType();
1901 else
1902 return false;
1903 // We have pointer to blocks, check whether the only
1904 // differences in the argument and result types are in Objective-C
1905 // pointer conversions. If so, we permit the conversion.
1906
1907 const FunctionProtoType *FromFunctionType
1908 = FromPointeeType->getAs<FunctionProtoType>();
1909 const FunctionProtoType *ToFunctionType
1910 = ToPointeeType->getAs<FunctionProtoType>();
1911
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001912 if (!FromFunctionType || !ToFunctionType)
1913 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001914
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001915 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001916 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001917
1918 // Perform the quick checks that will tell us whether these
1919 // function types are obviously different.
1920 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1921 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1922 return false;
1923
1924 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1925 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1926 if (FromEInfo != ToEInfo)
1927 return false;
1928
1929 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00001930 if (Context.hasSameType(FromFunctionType->getResultType(),
1931 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001932 // Okay, the types match exactly. Nothing to do.
1933 } else {
1934 QualType RHS = FromFunctionType->getResultType();
1935 QualType LHS = ToFunctionType->getResultType();
1936 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1937 !RHS.hasQualifiers() && LHS.hasQualifiers())
1938 LHS = LHS.getUnqualifiedType();
1939
1940 if (Context.hasSameType(RHS,LHS)) {
1941 // OK exact match.
1942 } else if (isObjCPointerConversion(RHS, LHS,
1943 ConvertedType, IncompatibleObjC)) {
1944 if (IncompatibleObjC)
1945 return false;
1946 // Okay, we have an Objective-C pointer conversion.
1947 }
1948 else
1949 return false;
1950 }
1951
1952 // Check argument types.
1953 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1954 ArgIdx != NumArgs; ++ArgIdx) {
1955 IncompatibleObjC = false;
1956 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1957 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1958 if (Context.hasSameType(FromArgType, ToArgType)) {
1959 // Okay, the types match exactly. Nothing to do.
1960 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1961 ConvertedType, IncompatibleObjC)) {
1962 if (IncompatibleObjC)
1963 return false;
1964 // Okay, we have an Objective-C pointer conversion.
1965 } else
1966 // Argument types are too different. Abort.
1967 return false;
1968 }
1969 ConvertedType = ToType;
1970 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001971}
1972
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001973/// FunctionArgTypesAreEqual - This routine checks two function proto types
1974/// for equlity of their argument types. Caller has already checked that
1975/// they have same number of arguments. This routine assumes that Objective-C
1976/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00001978 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001979 if (!getLangOptions().ObjC1)
1980 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1981 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001983 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1984 N = NewType->arg_type_begin(),
1985 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1986 QualType ToType = (*O);
1987 QualType FromType = (*N);
1988 if (ToType != FromType) {
1989 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1990 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001991 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1992 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1993 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1994 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001995 continue;
1996 }
John McCall8b07ec22010-05-15 11:32:37 +00001997 else if (const ObjCObjectPointerType *PTTo =
1998 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001999 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002000 FromType->getAs<ObjCObjectPointerType>())
2001 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2002 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002003 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002004 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002005 }
2006 }
2007 return true;
2008}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002009
Douglas Gregor39c16d42008-10-24 04:54:22 +00002010/// CheckPointerConversion - Check the pointer conversion from the
2011/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002012/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002013/// conversions for which IsPointerConversion has already returned
2014/// true. It returns true and produces a diagnostic if there was an
2015/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002016bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002017 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002018 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002019 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002020 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002021 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002022
John McCall8cb679e2010-11-15 09:13:47 +00002023 Kind = CK_BitCast;
2024
Chandler Carruthffab8732011-04-09 07:32:05 +00002025 if (!IsCStyleOrFunctionalCast &&
2026 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2027 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2028 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002029 PDiag(diag::warn_impcast_bool_to_null_pointer)
2030 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002031
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002032 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2033 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002034 QualType FromPointeeType = FromPtrType->getPointeeType(),
2035 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002036
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002037 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2038 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002039 // We must have a derived-to-base conversion. Check an
2040 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002041 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2042 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002043 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002044 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002045 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002046
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002047 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002048 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002049 }
2050 }
Mike Stump11289f42009-09-09 15:08:12 +00002051 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00002052 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002053 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00002054 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002055 // Objective-C++ conversions are always okay.
2056 // FIXME: We should have a different class of conversions for the
2057 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002058 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002059 return false;
John McCall8cb679e2010-11-15 09:13:47 +00002060 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002061 }
John McCall8cb679e2010-11-15 09:13:47 +00002062
2063 // We shouldn't fall into this case unless it's valid for other
2064 // reasons.
2065 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2066 Kind = CK_NullToPointer;
2067
Douglas Gregor39c16d42008-10-24 04:54:22 +00002068 return false;
2069}
2070
Sebastian Redl72b597d2009-01-25 19:43:20 +00002071/// IsMemberPointerConversion - Determines whether the conversion of the
2072/// expression From, which has the (possibly adjusted) type FromType, can be
2073/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2074/// If so, returns true and places the converted type (that might differ from
2075/// ToType in its cv-qualifiers at some level) into ConvertedType.
2076bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002077 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002078 bool InOverloadResolution,
2079 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002080 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002081 if (!ToTypePtr)
2082 return false;
2083
2084 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002085 if (From->isNullPointerConstant(Context,
2086 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2087 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002088 ConvertedType = ToType;
2089 return true;
2090 }
2091
2092 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002093 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002094 if (!FromTypePtr)
2095 return false;
2096
2097 // A pointer to member of B can be converted to a pointer to member of D,
2098 // where D is derived from B (C++ 4.11p2).
2099 QualType FromClass(FromTypePtr->getClass(), 0);
2100 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002101
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002102 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2103 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2104 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002105 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2106 ToClass.getTypePtr());
2107 return true;
2108 }
2109
2110 return false;
2111}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112
Sebastian Redl72b597d2009-01-25 19:43:20 +00002113/// CheckMemberPointerConversion - Check the member pointer conversion from the
2114/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002115/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002116/// for which IsMemberPointerConversion has already returned true. It returns
2117/// true and produces a diagnostic if there was an error, or returns false
2118/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002119bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002120 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002121 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002122 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002123 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002124 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002125 if (!FromPtrType) {
2126 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002127 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002128 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002129 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002130 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002131 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002132 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002133
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002134 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002135 assert(ToPtrType && "No member pointer cast has a target type "
2136 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002137
Sebastian Redled8f2002009-01-28 18:33:18 +00002138 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2139 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002140
Sebastian Redled8f2002009-01-28 18:33:18 +00002141 // FIXME: What about dependent types?
2142 assert(FromClass->isRecordType() && "Pointer into non-class.");
2143 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002144
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002145 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002146 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002147 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2148 assert(DerivationOkay &&
2149 "Should not have been called if derivation isn't OK.");
2150 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002151
Sebastian Redled8f2002009-01-28 18:33:18 +00002152 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2153 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002154 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2155 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2156 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2157 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002158 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002159
Douglas Gregor89ee6822009-02-28 01:32:25 +00002160 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002161 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2162 << FromClass << ToClass << QualType(VBase, 0)
2163 << From->getSourceRange();
2164 return true;
2165 }
2166
John McCall5b0829a2010-02-10 09:31:12 +00002167 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002168 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2169 Paths.front(),
2170 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002171
Anders Carlssond7923c62009-08-22 23:33:40 +00002172 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002173 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002174 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002175 return false;
2176}
2177
Douglas Gregor9a657932008-10-21 23:43:52 +00002178/// IsQualificationConversion - Determines whether the conversion from
2179/// an rvalue of type FromType to ToType is a qualification conversion
2180/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00002181bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002182Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor58281352011-01-27 00:58:17 +00002183 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002184 FromType = Context.getCanonicalType(FromType);
2185 ToType = Context.getCanonicalType(ToType);
2186
2187 // If FromType and ToType are the same type, this is not a
2188 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002189 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002190 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002191
Douglas Gregor9a657932008-10-21 23:43:52 +00002192 // (C++ 4.4p4):
2193 // A conversion can add cv-qualifiers at levels other than the first
2194 // in multi-level pointers, subject to the following rules: [...]
2195 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002196 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002197 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002198 // Within each iteration of the loop, we check the qualifiers to
2199 // determine if this still looks like a qualification
2200 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002201 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002202 // until there are no more pointers or pointers-to-members left to
2203 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002204 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002205
Douglas Gregor90609aa2011-04-25 18:40:17 +00002206 Qualifiers FromQuals = FromType.getQualifiers();
2207 Qualifiers ToQuals = ToType.getQualifiers();
2208
Douglas Gregorf30053d2011-05-08 06:09:53 +00002209 // Allow addition/removal of GC attributes but not changing GC attributes.
2210 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2211 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2212 FromQuals.removeObjCGCAttr();
2213 ToQuals.removeObjCGCAttr();
2214 }
2215
Douglas Gregor9a657932008-10-21 23:43:52 +00002216 // -- for every j > 0, if const is in cv 1,j then const is in cv
2217 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002218 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002219 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002220
Douglas Gregor9a657932008-10-21 23:43:52 +00002221 // -- if the cv 1,j and cv 2,j are different, then const is in
2222 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002223 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002224 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002225 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002226
Douglas Gregor9a657932008-10-21 23:43:52 +00002227 // Keep track of whether all prior cv-qualifiers in the "to" type
2228 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002229 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002230 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002231 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002232
2233 // We are left with FromType and ToType being the pointee types
2234 // after unwrapping the original FromType and ToType the same number
2235 // of types. If we unwrapped any pointers, and if FromType and
2236 // ToType have the same unqualified type (since we checked
2237 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002238 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002239}
2240
Douglas Gregor576e98c2009-01-30 23:27:23 +00002241/// Determines whether there is a user-defined conversion sequence
2242/// (C++ [over.ics.user]) that converts expression From to the type
2243/// ToType. If such a conversion exists, User will contain the
2244/// user-defined conversion sequence that performs such a conversion
2245/// and this routine will return true. Otherwise, this routine returns
2246/// false and User is unspecified.
2247///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002248/// \param AllowExplicit true if the conversion should consider C++0x
2249/// "explicit" conversion functions as well as non-explicit conversion
2250/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002251static OverloadingResult
2252IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2253 UserDefinedConversionSequence& User,
2254 OverloadCandidateSet& CandidateSet,
2255 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002256 // Whether we will only visit constructors.
2257 bool ConstructorsOnly = false;
2258
2259 // If the type we are conversion to is a class type, enumerate its
2260 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002261 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002262 // C++ [over.match.ctor]p1:
2263 // When objects of class type are direct-initialized (8.5), or
2264 // copy-initialized from an expression of the same or a
2265 // derived class type (8.5), overload resolution selects the
2266 // constructor. [...] For copy-initialization, the candidate
2267 // functions are all the converting constructors (12.3.1) of
2268 // that class. The argument list is the expression-list within
2269 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002270 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002271 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002272 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002273 ConstructorsOnly = true;
2274
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002275 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2276 // RequireCompleteType may have returned true due to some invalid decl
2277 // during template instantiation, but ToType may be complete enough now
2278 // to try to recover.
2279 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002280 // We're not going to find any constructors.
2281 } else if (CXXRecordDecl *ToRecordDecl
2282 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002283 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002284 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002285 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002286 NamedDecl *D = *Con;
2287 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2288
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002289 // Find the constructor (which may be a template).
2290 CXXConstructorDecl *Constructor = 0;
2291 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002292 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002293 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002294 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002295 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2296 else
John McCalla0296f72010-03-19 07:35:19 +00002297 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002298
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002299 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002300 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002301 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002302 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2303 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002305 /*SuppressUserConversions=*/
2306 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002307 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002308 // Allow one user-defined conversion when user specifies a
2309 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002310 S.AddOverloadCandidate(Constructor, FoundDecl,
2311 &From, 1, CandidateSet,
2312 /*SuppressUserConversions=*/
2313 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002314 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002315 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002316 }
2317 }
2318
Douglas Gregor5ab11652010-04-17 22:01:05 +00002319 // Enumerate conversion functions, if we're allowed to.
2320 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002321 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2322 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002323 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002324 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002325 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002326 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002327 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2328 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002329 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002330 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002331 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002332 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002333 DeclAccessPair FoundDecl = I.getPair();
2334 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002335 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2336 if (isa<UsingShadowDecl>(D))
2337 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2338
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002339 CXXConversionDecl *Conv;
2340 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002341 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2342 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002343 else
John McCallda4458e2010-03-31 01:36:47 +00002344 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002345
2346 if (AllowExplicit || !Conv->isExplicit()) {
2347 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002348 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2349 ActingContext, From, ToType,
2350 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002351 else
John McCall5c32be02010-08-24 20:38:10 +00002352 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2353 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002354 }
2355 }
2356 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002357 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002358
2359 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002360 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002361 case OR_Success:
2362 // Record the standard conversion we used and the conversion function.
2363 if (CXXConstructorDecl *Constructor
2364 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002365 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2366
John McCall5c32be02010-08-24 20:38:10 +00002367 // C++ [over.ics.user]p1:
2368 // If the user-defined conversion is specified by a
2369 // constructor (12.3.1), the initial standard conversion
2370 // sequence converts the source type to the type required by
2371 // the argument of the constructor.
2372 //
2373 QualType ThisType = Constructor->getThisType(S.Context);
2374 if (Best->Conversions[0].isEllipsis())
2375 User.EllipsisConversion = true;
2376 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002377 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002378 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002379 }
John McCall5c32be02010-08-24 20:38:10 +00002380 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002381 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002382 User.After.setAsIdentityConversion();
2383 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2384 User.After.setAllToTypes(ToType);
2385 return OR_Success;
2386 } else if (CXXConversionDecl *Conversion
2387 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002388 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2389
John McCall5c32be02010-08-24 20:38:10 +00002390 // C++ [over.ics.user]p1:
2391 //
2392 // [...] If the user-defined conversion is specified by a
2393 // conversion function (12.3.2), the initial standard
2394 // conversion sequence converts the source type to the
2395 // implicit object parameter of the conversion function.
2396 User.Before = Best->Conversions[0].Standard;
2397 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002398 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002399 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002400
John McCall5c32be02010-08-24 20:38:10 +00002401 // C++ [over.ics.user]p2:
2402 // The second standard conversion sequence converts the
2403 // result of the user-defined conversion to the target type
2404 // for the sequence. Since an implicit conversion sequence
2405 // is an initialization, the special rules for
2406 // initialization by user-defined conversion apply when
2407 // selecting the best user-defined conversion for a
2408 // user-defined conversion sequence (see 13.3.3 and
2409 // 13.3.3.1).
2410 User.After = Best->FinalConversion;
2411 return OR_Success;
2412 } else {
2413 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002414 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002415 }
2416
John McCall5c32be02010-08-24 20:38:10 +00002417 case OR_No_Viable_Function:
2418 return OR_No_Viable_Function;
2419 case OR_Deleted:
2420 // No conversion here! We're done.
2421 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002422
John McCall5c32be02010-08-24 20:38:10 +00002423 case OR_Ambiguous:
2424 return OR_Ambiguous;
2425 }
2426
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002427 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002428}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002429
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002430bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002431Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002432 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002433 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002434 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002435 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002436 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002437 if (OvResult == OR_Ambiguous)
2438 Diag(From->getSourceRange().getBegin(),
2439 diag::err_typecheck_ambiguous_condition)
2440 << From->getType() << ToType << From->getSourceRange();
2441 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2442 Diag(From->getSourceRange().getBegin(),
2443 diag::err_typecheck_nonviable_condition)
2444 << From->getType() << ToType << From->getSourceRange();
2445 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002446 return false;
John McCall5c32be02010-08-24 20:38:10 +00002447 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002448 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002449}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002450
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002451/// CompareImplicitConversionSequences - Compare two implicit
2452/// conversion sequences to determine whether one is better than the
2453/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002454static ImplicitConversionSequence::CompareKind
2455CompareImplicitConversionSequences(Sema &S,
2456 const ImplicitConversionSequence& ICS1,
2457 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002458{
2459 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2460 // conversion sequences (as defined in 13.3.3.1)
2461 // -- a standard conversion sequence (13.3.3.1.1) is a better
2462 // conversion sequence than a user-defined conversion sequence or
2463 // an ellipsis conversion sequence, and
2464 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2465 // conversion sequence than an ellipsis conversion sequence
2466 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002467 //
John McCall0d1da222010-01-12 00:44:57 +00002468 // C++0x [over.best.ics]p10:
2469 // For the purpose of ranking implicit conversion sequences as
2470 // described in 13.3.3.2, the ambiguous conversion sequence is
2471 // treated as a user-defined sequence that is indistinguishable
2472 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002473 if (ICS1.getKindRank() < ICS2.getKindRank())
2474 return ImplicitConversionSequence::Better;
2475 else if (ICS2.getKindRank() < ICS1.getKindRank())
2476 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002477
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002478 // The following checks require both conversion sequences to be of
2479 // the same kind.
2480 if (ICS1.getKind() != ICS2.getKind())
2481 return ImplicitConversionSequence::Indistinguishable;
2482
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002483 // Two implicit conversion sequences of the same form are
2484 // indistinguishable conversion sequences unless one of the
2485 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002486 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002487 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002488 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002489 // User-defined conversion sequence U1 is a better conversion
2490 // sequence than another user-defined conversion sequence U2 if
2491 // they contain the same user-defined conversion function or
2492 // constructor and if the second standard conversion sequence of
2493 // U1 is better than the second standard conversion sequence of
2494 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002495 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002496 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002497 return CompareStandardConversionSequences(S,
2498 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002499 ICS2.UserDefined.After);
2500 }
2501
2502 return ImplicitConversionSequence::Indistinguishable;
2503}
2504
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002505static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2506 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2507 Qualifiers Quals;
2508 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002509 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002511
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002512 return Context.hasSameUnqualifiedType(T1, T2);
2513}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002514
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002515// Per 13.3.3.2p3, compare the given standard conversion sequences to
2516// determine if one is a proper subset of the other.
2517static ImplicitConversionSequence::CompareKind
2518compareStandardConversionSubsets(ASTContext &Context,
2519 const StandardConversionSequence& SCS1,
2520 const StandardConversionSequence& SCS2) {
2521 ImplicitConversionSequence::CompareKind Result
2522 = ImplicitConversionSequence::Indistinguishable;
2523
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002525 // any non-identity conversion sequence
2526 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2527 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2528 return ImplicitConversionSequence::Better;
2529 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2530 return ImplicitConversionSequence::Worse;
2531 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002532
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002533 if (SCS1.Second != SCS2.Second) {
2534 if (SCS1.Second == ICK_Identity)
2535 Result = ImplicitConversionSequence::Better;
2536 else if (SCS2.Second == ICK_Identity)
2537 Result = ImplicitConversionSequence::Worse;
2538 else
2539 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002540 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002541 return ImplicitConversionSequence::Indistinguishable;
2542
2543 if (SCS1.Third == SCS2.Third) {
2544 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2545 : ImplicitConversionSequence::Indistinguishable;
2546 }
2547
2548 if (SCS1.Third == ICK_Identity)
2549 return Result == ImplicitConversionSequence::Worse
2550 ? ImplicitConversionSequence::Indistinguishable
2551 : ImplicitConversionSequence::Better;
2552
2553 if (SCS2.Third == ICK_Identity)
2554 return Result == ImplicitConversionSequence::Better
2555 ? ImplicitConversionSequence::Indistinguishable
2556 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002558 return ImplicitConversionSequence::Indistinguishable;
2559}
2560
Douglas Gregore696ebb2011-01-26 14:52:12 +00002561/// \brief Determine whether one of the given reference bindings is better
2562/// than the other based on what kind of bindings they are.
2563static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2564 const StandardConversionSequence &SCS2) {
2565 // C++0x [over.ics.rank]p3b4:
2566 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2567 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002568 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002569 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002570 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002571 // reference*.
2572 //
2573 // FIXME: Rvalue references. We're going rogue with the above edits,
2574 // because the semantics in the current C++0x working paper (N3225 at the
2575 // time of this writing) break the standard definition of std::forward
2576 // and std::reference_wrapper when dealing with references to functions.
2577 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002578 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2579 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2580 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002581
Douglas Gregore696ebb2011-01-26 14:52:12 +00002582 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2583 SCS2.IsLvalueReference) ||
2584 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2585 !SCS2.IsLvalueReference);
2586}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002587
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002588/// CompareStandardConversionSequences - Compare two standard
2589/// conversion sequences to determine whether one is better than the
2590/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002591static ImplicitConversionSequence::CompareKind
2592CompareStandardConversionSequences(Sema &S,
2593 const StandardConversionSequence& SCS1,
2594 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002595{
2596 // Standard conversion sequence S1 is a better conversion sequence
2597 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2598
2599 // -- S1 is a proper subsequence of S2 (comparing the conversion
2600 // sequences in the canonical form defined by 13.3.3.1.1,
2601 // excluding any Lvalue Transformation; the identity conversion
2602 // sequence is considered to be a subsequence of any
2603 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002604 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002605 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002606 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002607
2608 // -- the rank of S1 is better than the rank of S2 (by the rules
2609 // defined below), or, if not that,
2610 ImplicitConversionRank Rank1 = SCS1.getRank();
2611 ImplicitConversionRank Rank2 = SCS2.getRank();
2612 if (Rank1 < Rank2)
2613 return ImplicitConversionSequence::Better;
2614 else if (Rank2 < Rank1)
2615 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002616
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002617 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2618 // are indistinguishable unless one of the following rules
2619 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002620
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002621 // A conversion that is not a conversion of a pointer, or
2622 // pointer to member, to bool is better than another conversion
2623 // that is such a conversion.
2624 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2625 return SCS2.isPointerConversionToBool()
2626 ? ImplicitConversionSequence::Better
2627 : ImplicitConversionSequence::Worse;
2628
Douglas Gregor5c407d92008-10-23 00:40:37 +00002629 // C++ [over.ics.rank]p4b2:
2630 //
2631 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002632 // conversion of B* to A* is better than conversion of B* to
2633 // void*, and conversion of A* to void* is better than conversion
2634 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002635 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002636 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002637 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002638 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002639 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2640 // Exactly one of the conversion sequences is a conversion to
2641 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002642 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2643 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002644 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2645 // Neither conversion sequence converts to a void pointer; compare
2646 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002647 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002648 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002649 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002650 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2651 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002652 // Both conversion sequences are conversions to void
2653 // pointers. Compare the source types to determine if there's an
2654 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002655 QualType FromType1 = SCS1.getFromType();
2656 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002657
2658 // Adjust the types we're converting from via the array-to-pointer
2659 // conversion, if we need to.
2660 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002661 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002662 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002663 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002664
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002665 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2666 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002667
John McCall5c32be02010-08-24 20:38:10 +00002668 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002669 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002670 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002671 return ImplicitConversionSequence::Worse;
2672
2673 // Objective-C++: If one interface is more specific than the
2674 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002675 const ObjCObjectPointerType* FromObjCPtr1
2676 = FromType1->getAs<ObjCObjectPointerType>();
2677 const ObjCObjectPointerType* FromObjCPtr2
2678 = FromType2->getAs<ObjCObjectPointerType>();
2679 if (FromObjCPtr1 && FromObjCPtr2) {
2680 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2681 FromObjCPtr2);
2682 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2683 FromObjCPtr1);
2684 if (AssignLeft != AssignRight) {
2685 return AssignLeft? ImplicitConversionSequence::Better
2686 : ImplicitConversionSequence::Worse;
2687 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002688 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002689 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002690
2691 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2692 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002693 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002694 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002695 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002696
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002697 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002698 // Check for a better reference binding based on the kind of bindings.
2699 if (isBetterReferenceBindingKind(SCS1, SCS2))
2700 return ImplicitConversionSequence::Better;
2701 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2702 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703
Sebastian Redlb28b4072009-03-22 23:49:27 +00002704 // C++ [over.ics.rank]p3b4:
2705 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2706 // which the references refer are the same type except for
2707 // top-level cv-qualifiers, and the type to which the reference
2708 // initialized by S2 refers is more cv-qualified than the type
2709 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002710 QualType T1 = SCS1.getToType(2);
2711 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002712 T1 = S.Context.getCanonicalType(T1);
2713 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002714 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002715 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2716 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002717 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002718 // If the type is an array type, promote the element qualifiers to the
2719 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002720 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002721 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002722 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002723 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002724 if (T2.isMoreQualifiedThan(T1))
2725 return ImplicitConversionSequence::Better;
2726 else if (T1.isMoreQualifiedThan(T2))
2727 return ImplicitConversionSequence::Worse;
2728 }
2729 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002730
2731 return ImplicitConversionSequence::Indistinguishable;
2732}
2733
2734/// CompareQualificationConversions - Compares two standard conversion
2735/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002736/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2737ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002738CompareQualificationConversions(Sema &S,
2739 const StandardConversionSequence& SCS1,
2740 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002741 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002742 // -- S1 and S2 differ only in their qualification conversion and
2743 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2744 // cv-qualification signature of type T1 is a proper subset of
2745 // the cv-qualification signature of type T2, and S1 is not the
2746 // deprecated string literal array-to-pointer conversion (4.2).
2747 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2748 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2749 return ImplicitConversionSequence::Indistinguishable;
2750
2751 // FIXME: the example in the standard doesn't use a qualification
2752 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002753 QualType T1 = SCS1.getToType(2);
2754 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002755 T1 = S.Context.getCanonicalType(T1);
2756 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002757 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002758 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2759 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002760
2761 // If the types are the same, we won't learn anything by unwrapped
2762 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002763 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002764 return ImplicitConversionSequence::Indistinguishable;
2765
Chandler Carruth607f38e2009-12-29 07:16:59 +00002766 // If the type is an array type, promote the element qualifiers to the type
2767 // for comparison.
2768 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002769 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002770 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002771 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002772
Mike Stump11289f42009-09-09 15:08:12 +00002773 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002774 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002775 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002776 // Within each iteration of the loop, we check the qualifiers to
2777 // determine if this still looks like a qualification
2778 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002779 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002780 // until there are no more pointers or pointers-to-members left
2781 // to unwrap. This essentially mimics what
2782 // IsQualificationConversion does, but here we're checking for a
2783 // strict subset of qualifiers.
2784 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2785 // The qualifiers are the same, so this doesn't tell us anything
2786 // about how the sequences rank.
2787 ;
2788 else if (T2.isMoreQualifiedThan(T1)) {
2789 // T1 has fewer qualifiers, so it could be the better sequence.
2790 if (Result == ImplicitConversionSequence::Worse)
2791 // Neither has qualifiers that are a subset of the other's
2792 // qualifiers.
2793 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002794
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002795 Result = ImplicitConversionSequence::Better;
2796 } else if (T1.isMoreQualifiedThan(T2)) {
2797 // T2 has fewer qualifiers, so it could be the better sequence.
2798 if (Result == ImplicitConversionSequence::Better)
2799 // Neither has qualifiers that are a subset of the other's
2800 // qualifiers.
2801 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002802
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002803 Result = ImplicitConversionSequence::Worse;
2804 } else {
2805 // Qualifiers are disjoint.
2806 return ImplicitConversionSequence::Indistinguishable;
2807 }
2808
2809 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002810 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002811 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002812 }
2813
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002814 // Check that the winning standard conversion sequence isn't using
2815 // the deprecated string literal array to pointer conversion.
2816 switch (Result) {
2817 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002818 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002819 Result = ImplicitConversionSequence::Indistinguishable;
2820 break;
2821
2822 case ImplicitConversionSequence::Indistinguishable:
2823 break;
2824
2825 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002826 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002827 Result = ImplicitConversionSequence::Indistinguishable;
2828 break;
2829 }
2830
2831 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002832}
2833
Douglas Gregor5c407d92008-10-23 00:40:37 +00002834/// CompareDerivedToBaseConversions - Compares two standard conversion
2835/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002836/// various kinds of derived-to-base conversions (C++
2837/// [over.ics.rank]p4b3). As part of these checks, we also look at
2838/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002839ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002840CompareDerivedToBaseConversions(Sema &S,
2841 const StandardConversionSequence& SCS1,
2842 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002843 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002844 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002845 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002846 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002847
2848 // Adjust the types we're converting from via the array-to-pointer
2849 // conversion, if we need to.
2850 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002851 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002852 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002853 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002854
2855 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002856 FromType1 = S.Context.getCanonicalType(FromType1);
2857 ToType1 = S.Context.getCanonicalType(ToType1);
2858 FromType2 = S.Context.getCanonicalType(FromType2);
2859 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002860
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002861 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002862 //
2863 // If class B is derived directly or indirectly from class A and
2864 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002865 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002866 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002867 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002868 SCS2.Second == ICK_Pointer_Conversion &&
2869 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2870 FromType1->isPointerType() && FromType2->isPointerType() &&
2871 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002872 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002873 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002874 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002875 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002876 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002877 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002878 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002879 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002880
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002881 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002882 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002883 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002884 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002885 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002886 return ImplicitConversionSequence::Worse;
2887 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002888
2889 // -- conversion of B* to A* is better than conversion of C* to A*,
2890 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002891 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002892 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002893 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002894 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00002895 }
2896 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2897 SCS2.Second == ICK_Pointer_Conversion) {
2898 const ObjCObjectPointerType *FromPtr1
2899 = FromType1->getAs<ObjCObjectPointerType>();
2900 const ObjCObjectPointerType *FromPtr2
2901 = FromType2->getAs<ObjCObjectPointerType>();
2902 const ObjCObjectPointerType *ToPtr1
2903 = ToType1->getAs<ObjCObjectPointerType>();
2904 const ObjCObjectPointerType *ToPtr2
2905 = ToType2->getAs<ObjCObjectPointerType>();
2906
2907 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2908 // Apply the same conversion ranking rules for Objective-C pointer types
2909 // that we do for C++ pointers to class types. However, we employ the
2910 // Objective-C pseudo-subtyping relationship used for assignment of
2911 // Objective-C pointer types.
2912 bool FromAssignLeft
2913 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2914 bool FromAssignRight
2915 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2916 bool ToAssignLeft
2917 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2918 bool ToAssignRight
2919 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2920
2921 // A conversion to an a non-id object pointer type or qualified 'id'
2922 // type is better than a conversion to 'id'.
2923 if (ToPtr1->isObjCIdType() &&
2924 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2925 return ImplicitConversionSequence::Worse;
2926 if (ToPtr2->isObjCIdType() &&
2927 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2928 return ImplicitConversionSequence::Better;
2929
2930 // A conversion to a non-id object pointer type is better than a
2931 // conversion to a qualified 'id' type
2932 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2933 return ImplicitConversionSequence::Worse;
2934 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2935 return ImplicitConversionSequence::Better;
2936
2937 // A conversion to an a non-Class object pointer type or qualified 'Class'
2938 // type is better than a conversion to 'Class'.
2939 if (ToPtr1->isObjCClassType() &&
2940 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2941 return ImplicitConversionSequence::Worse;
2942 if (ToPtr2->isObjCClassType() &&
2943 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2944 return ImplicitConversionSequence::Better;
2945
2946 // A conversion to a non-Class object pointer type is better than a
2947 // conversion to a qualified 'Class' type.
2948 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2949 return ImplicitConversionSequence::Worse;
2950 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2951 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00002952
Douglas Gregor058d3de2011-01-31 18:51:41 +00002953 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2954 if (S.Context.hasSameType(FromType1, FromType2) &&
2955 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2956 (ToAssignLeft != ToAssignRight))
2957 return ToAssignLeft? ImplicitConversionSequence::Worse
2958 : ImplicitConversionSequence::Better;
2959
2960 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2961 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2962 (FromAssignLeft != FromAssignRight))
2963 return FromAssignLeft? ImplicitConversionSequence::Better
2964 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002965 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002966 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00002967
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002968 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002969 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2970 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2971 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002972 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002973 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002975 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002976 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002977 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002979 ToType2->getAs<MemberPointerType>();
2980 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2981 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2982 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2983 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2984 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2985 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2986 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2987 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002988 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002989 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002990 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002991 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002992 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002993 return ImplicitConversionSequence::Better;
2994 }
2995 // conversion of B::* to C::* is better than conversion of A::* to C::*
2996 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002997 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002998 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002999 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003000 return ImplicitConversionSequence::Worse;
3001 }
3002 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003003
Douglas Gregor5ab11652010-04-17 22:01:05 +00003004 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003005 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003006 // -- binding of an expression of type C to a reference of type
3007 // B& is better than binding an expression of type C to a
3008 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003009 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3010 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3011 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003012 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003013 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003014 return ImplicitConversionSequence::Worse;
3015 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003016
Douglas Gregor2fe98832008-11-03 19:09:14 +00003017 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003018 // -- binding of an expression of type B to a reference of type
3019 // A& is better than binding an expression of type C to a
3020 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003021 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3022 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3023 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003024 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003025 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003026 return ImplicitConversionSequence::Worse;
3027 }
3028 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003029
Douglas Gregor5c407d92008-10-23 00:40:37 +00003030 return ImplicitConversionSequence::Indistinguishable;
3031}
3032
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003033/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3034/// determine whether they are reference-related,
3035/// reference-compatible, reference-compatible with added
3036/// qualification, or incompatible, for use in C++ initialization by
3037/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3038/// type, and the first type (T1) is the pointee type of the reference
3039/// type being initialized.
3040Sema::ReferenceCompareResult
3041Sema::CompareReferenceRelationship(SourceLocation Loc,
3042 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003043 bool &DerivedToBase,
3044 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003045 assert(!OrigT1->isReferenceType() &&
3046 "T1 must be the pointee type of the reference type");
3047 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3048
3049 QualType T1 = Context.getCanonicalType(OrigT1);
3050 QualType T2 = Context.getCanonicalType(OrigT2);
3051 Qualifiers T1Quals, T2Quals;
3052 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3053 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3054
3055 // C++ [dcl.init.ref]p4:
3056 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3057 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3058 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003059 DerivedToBase = false;
3060 ObjCConversion = false;
3061 if (UnqualT1 == UnqualT2) {
3062 // Nothing to do.
3063 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003064 IsDerivedFrom(UnqualT2, UnqualT1))
3065 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003066 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3067 UnqualT2->isObjCObjectOrInterfaceType() &&
3068 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3069 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003070 else
3071 return Ref_Incompatible;
3072
3073 // At this point, we know that T1 and T2 are reference-related (at
3074 // least).
3075
3076 // If the type is an array type, promote the element qualifiers to the type
3077 // for comparison.
3078 if (isa<ArrayType>(T1) && T1Quals)
3079 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3080 if (isa<ArrayType>(T2) && T2Quals)
3081 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3082
3083 // C++ [dcl.init.ref]p4:
3084 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3085 // reference-related to T2 and cv1 is the same cv-qualification
3086 // as, or greater cv-qualification than, cv2. For purposes of
3087 // overload resolution, cases for which cv1 is greater
3088 // cv-qualification than cv2 are identified as
3089 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003090 //
3091 // Note that we also require equivalence of Objective-C GC and address-space
3092 // qualifiers when performing these computations, so that e.g., an int in
3093 // address space 1 is not reference-compatible with an int in address
3094 // space 2.
3095 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003096 return Ref_Compatible;
3097 else if (T1.isMoreQualifiedThan(T2))
3098 return Ref_Compatible_With_Added_Qualification;
3099 else
3100 return Ref_Related;
3101}
3102
Douglas Gregor836a7e82010-08-11 02:15:33 +00003103/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003104/// with DeclType. Return true if something definite is found.
3105static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003106FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3107 QualType DeclType, SourceLocation DeclLoc,
3108 Expr *Init, QualType T2, bool AllowRvalues,
3109 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003110 assert(T2->isRecordType() && "Can only find conversions of record types.");
3111 CXXRecordDecl *T2RecordDecl
3112 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3113
3114 OverloadCandidateSet CandidateSet(DeclLoc);
3115 const UnresolvedSetImpl *Conversions
3116 = T2RecordDecl->getVisibleConversionFunctions();
3117 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3118 E = Conversions->end(); I != E; ++I) {
3119 NamedDecl *D = *I;
3120 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3121 if (isa<UsingShadowDecl>(D))
3122 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3123
3124 FunctionTemplateDecl *ConvTemplate
3125 = dyn_cast<FunctionTemplateDecl>(D);
3126 CXXConversionDecl *Conv;
3127 if (ConvTemplate)
3128 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3129 else
3130 Conv = cast<CXXConversionDecl>(D);
3131
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003132 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003133 // explicit conversions, skip it.
3134 if (!AllowExplicit && Conv->isExplicit())
3135 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003136
Douglas Gregor836a7e82010-08-11 02:15:33 +00003137 if (AllowRvalues) {
3138 bool DerivedToBase = false;
3139 bool ObjCConversion = false;
3140 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003141 S.CompareReferenceRelationship(
3142 DeclLoc,
3143 Conv->getConversionType().getNonReferenceType()
3144 .getUnqualifiedType(),
3145 DeclType.getNonReferenceType().getUnqualifiedType(),
3146 DerivedToBase, ObjCConversion) ==
3147 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003148 continue;
3149 } else {
3150 // If the conversion function doesn't return a reference type,
3151 // it can't be considered for this conversion. An rvalue reference
3152 // is only acceptable if its referencee is a function type.
3153
3154 const ReferenceType *RefType =
3155 Conv->getConversionType()->getAs<ReferenceType>();
3156 if (!RefType ||
3157 (!RefType->isLValueReferenceType() &&
3158 !RefType->getPointeeType()->isFunctionType()))
3159 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161
Douglas Gregor836a7e82010-08-11 02:15:33 +00003162 if (ConvTemplate)
3163 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003164 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003165 else
3166 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003167 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003168 }
3169
3170 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003171 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003172 case OR_Success:
3173 // C++ [over.ics.ref]p1:
3174 //
3175 // [...] If the parameter binds directly to the result of
3176 // applying a conversion function to the argument
3177 // expression, the implicit conversion sequence is a
3178 // user-defined conversion sequence (13.3.3.1.2), with the
3179 // second standard conversion sequence either an identity
3180 // conversion or, if the conversion function returns an
3181 // entity of a type that is a derived class of the parameter
3182 // type, a derived-to-base Conversion.
3183 if (!Best->FinalConversion.DirectBinding)
3184 return false;
3185
Chandler Carruth30141632011-02-25 19:41:05 +00003186 if (Best->Function)
3187 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003188 ICS.setUserDefined();
3189 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3190 ICS.UserDefined.After = Best->FinalConversion;
3191 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003192 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003193 ICS.UserDefined.EllipsisConversion = false;
3194 assert(ICS.UserDefined.After.ReferenceBinding &&
3195 ICS.UserDefined.After.DirectBinding &&
3196 "Expected a direct reference binding!");
3197 return true;
3198
3199 case OR_Ambiguous:
3200 ICS.setAmbiguous();
3201 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3202 Cand != CandidateSet.end(); ++Cand)
3203 if (Cand->Viable)
3204 ICS.Ambiguous.addConversion(Cand->Function);
3205 return true;
3206
3207 case OR_No_Viable_Function:
3208 case OR_Deleted:
3209 // There was no suitable conversion, or we found a deleted
3210 // conversion; continue with other checks.
3211 return false;
3212 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003213
Eric Christopheraba9fb22010-06-30 18:36:32 +00003214 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003215}
3216
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003217/// \brief Compute an implicit conversion sequence for reference
3218/// initialization.
3219static ImplicitConversionSequence
3220TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3221 SourceLocation DeclLoc,
3222 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003223 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003224 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3225
3226 // Most paths end in a failed conversion.
3227 ImplicitConversionSequence ICS;
3228 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3229
3230 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3231 QualType T2 = Init->getType();
3232
3233 // If the initializer is the address of an overloaded function, try
3234 // to resolve the overloaded function. If all goes well, T2 is the
3235 // type of the resulting function.
3236 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3237 DeclAccessPair Found;
3238 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3239 false, Found))
3240 T2 = Fn->getType();
3241 }
3242
3243 // Compute some basic properties of the types and the initializer.
3244 bool isRValRef = DeclType->isRValueReferenceType();
3245 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003246 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003247 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003248 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003249 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3250 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003251
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003252
Sebastian Redld92badf2010-06-30 18:13:39 +00003253 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003254 // A reference to type "cv1 T1" is initialized by an expression
3255 // of type "cv2 T2" as follows:
3256
Sebastian Redld92badf2010-06-30 18:13:39 +00003257 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003258 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003259 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3260 // reference-compatible with "cv2 T2," or
3261 //
3262 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3263 if (InitCategory.isLValue() &&
3264 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003265 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003266 // When a parameter of reference type binds directly (8.5.3)
3267 // to an argument expression, the implicit conversion sequence
3268 // is the identity conversion, unless the argument expression
3269 // has a type that is a derived class of the parameter type,
3270 // in which case the implicit conversion sequence is a
3271 // derived-to-base Conversion (13.3.3.1).
3272 ICS.setStandard();
3273 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003274 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3275 : ObjCConversion? ICK_Compatible_Conversion
3276 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003277 ICS.Standard.Third = ICK_Identity;
3278 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3279 ICS.Standard.setToType(0, T2);
3280 ICS.Standard.setToType(1, T1);
3281 ICS.Standard.setToType(2, T1);
3282 ICS.Standard.ReferenceBinding = true;
3283 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003284 ICS.Standard.IsLvalueReference = !isRValRef;
3285 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3286 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003287 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003288 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003289
Sebastian Redld92badf2010-06-30 18:13:39 +00003290 // Nothing more to do: the inaccessibility/ambiguity check for
3291 // derived-to-base conversions is suppressed when we're
3292 // computing the implicit conversion sequence (C++
3293 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003294 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003295 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003296
Sebastian Redld92badf2010-06-30 18:13:39 +00003297 // -- has a class type (i.e., T2 is a class type), where T1 is
3298 // not reference-related to T2, and can be implicitly
3299 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3300 // is reference-compatible with "cv3 T3" 92) (this
3301 // conversion is selected by enumerating the applicable
3302 // conversion functions (13.3.1.6) and choosing the best
3303 // one through overload resolution (13.3)),
3304 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003305 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003306 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003307 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3308 Init, T2, /*AllowRvalues=*/false,
3309 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003310 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003311 }
3312 }
3313
Sebastian Redld92badf2010-06-30 18:13:39 +00003314 // -- Otherwise, the reference shall be an lvalue reference to a
3315 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003316 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003317 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003318 // We actually handle one oddity of C++ [over.ics.ref] at this
3319 // point, which is that, due to p2 (which short-circuits reference
3320 // binding by only attempting a simple conversion for non-direct
3321 // bindings) and p3's strange wording, we allow a const volatile
3322 // reference to bind to an rvalue. Hence the check for the presence
3323 // of "const" rather than checking for "const" being the only
3324 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003325 // This is also the point where rvalue references and lvalue inits no longer
3326 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003327 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003328 return ICS;
3329
Douglas Gregorf143cd52011-01-24 16:14:37 +00003330 // -- If the initializer expression
3331 //
3332 // -- is an xvalue, class prvalue, array prvalue or function
3333 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3334 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3335 (InitCategory.isXValue() ||
3336 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3337 (InitCategory.isLValue() && T2->isFunctionType()))) {
3338 ICS.setStandard();
3339 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003340 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003341 : ObjCConversion? ICK_Compatible_Conversion
3342 : ICK_Identity;
3343 ICS.Standard.Third = ICK_Identity;
3344 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3345 ICS.Standard.setToType(0, T2);
3346 ICS.Standard.setToType(1, T1);
3347 ICS.Standard.setToType(2, T1);
3348 ICS.Standard.ReferenceBinding = true;
3349 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3350 // binding unless we're binding to a class prvalue.
3351 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3352 // allow the use of rvalue references in C++98/03 for the benefit of
3353 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003354 ICS.Standard.DirectBinding =
3355 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003356 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003357 ICS.Standard.IsLvalueReference = !isRValRef;
3358 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003359 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003360 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003361 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003363 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364
Douglas Gregorf143cd52011-01-24 16:14:37 +00003365 // -- has a class type (i.e., T2 is a class type), where T1 is not
3366 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003367 // an xvalue, class prvalue, or function lvalue of type
3368 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003369 // "cv3 T3",
3370 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003371 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003372 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003373 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003374 // class subobject).
3375 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003377 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3378 Init, T2, /*AllowRvalues=*/true,
3379 AllowExplicit)) {
3380 // In the second case, if the reference is an rvalue reference
3381 // and the second standard conversion sequence of the
3382 // user-defined conversion sequence includes an lvalue-to-rvalue
3383 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003384 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003385 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3386 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3387
Douglas Gregor95273c32011-01-21 16:36:05 +00003388 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003389 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003390
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003391 // -- Otherwise, a temporary of type "cv1 T1" is created and
3392 // initialized from the initializer expression using the
3393 // rules for a non-reference copy initialization (8.5). The
3394 // reference is then bound to the temporary. If T1 is
3395 // reference-related to T2, cv1 must be the same
3396 // cv-qualification as, or greater cv-qualification than,
3397 // cv2; otherwise, the program is ill-formed.
3398 if (RefRelationship == Sema::Ref_Related) {
3399 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3400 // we would be reference-compatible or reference-compatible with
3401 // added qualification. But that wasn't the case, so the reference
3402 // initialization fails.
3403 return ICS;
3404 }
3405
3406 // If at least one of the types is a class type, the types are not
3407 // related, and we aren't allowed any user conversions, the
3408 // reference binding fails. This case is important for breaking
3409 // recursion, since TryImplicitConversion below will attempt to
3410 // create a temporary through the use of a copy constructor.
3411 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3412 (T1->isRecordType() || T2->isRecordType()))
3413 return ICS;
3414
Douglas Gregorcba72b12011-01-21 05:18:22 +00003415 // If T1 is reference-related to T2 and the reference is an rvalue
3416 // reference, the initializer expression shall not be an lvalue.
3417 if (RefRelationship >= Sema::Ref_Related &&
3418 isRValRef && Init->Classify(S.Context).isLValue())
3419 return ICS;
3420
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003421 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003422 // When a parameter of reference type is not bound directly to
3423 // an argument expression, the conversion sequence is the one
3424 // required to convert the argument expression to the
3425 // underlying type of the reference according to
3426 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3427 // to copy-initializing a temporary of the underlying type with
3428 // the argument expression. Any difference in top-level
3429 // cv-qualification is subsumed by the initialization itself
3430 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003431 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3432 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003433 /*InOverloadResolution=*/false,
3434 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003435
3436 // Of course, that's still a reference binding.
3437 if (ICS.isStandard()) {
3438 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003439 ICS.Standard.IsLvalueReference = !isRValRef;
3440 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3441 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003442 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003443 } else if (ICS.isUserDefined()) {
3444 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003445 ICS.Standard.IsLvalueReference = !isRValRef;
3446 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3447 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003448 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003449 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003450
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003451 return ICS;
3452}
3453
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003454/// TryCopyInitialization - Try to copy-initialize a value of type
3455/// ToType from the expression From. Return the implicit conversion
3456/// sequence required to pass this argument, which may be a bad
3457/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003458/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003459/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003460static ImplicitConversionSequence
3461TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003462 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003463 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003464 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003465 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003466 /*FIXME:*/From->getLocStart(),
3467 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003468 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003469
John McCall5c32be02010-08-24 20:38:10 +00003470 return TryImplicitConversion(S, From, ToType,
3471 SuppressUserConversions,
3472 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003473 InOverloadResolution,
3474 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003475}
3476
Douglas Gregor436424c2008-11-18 23:14:02 +00003477/// TryObjectArgumentInitialization - Try to initialize the object
3478/// parameter of the given member function (@c Method) from the
3479/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003480static ImplicitConversionSequence
3481TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003482 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003483 CXXMethodDecl *Method,
3484 CXXRecordDecl *ActingContext) {
3485 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003486 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3487 // const volatile object.
3488 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3489 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003490 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003491
3492 // Set up the conversion sequence as a "bad" conversion, to allow us
3493 // to exit early.
3494 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003495
3496 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003497 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003498 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003499 FromType = PT->getPointeeType();
3500
Douglas Gregor02824322011-01-26 19:30:28 +00003501 // When we had a pointer, it's implicitly dereferenced, so we
3502 // better have an lvalue.
3503 assert(FromClassification.isLValue());
3504 }
3505
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003506 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003507
Douglas Gregor02824322011-01-26 19:30:28 +00003508 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003509 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003510 // parameter is
3511 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003512 // - "lvalue reference to cv X" for functions declared without a
3513 // ref-qualifier or with the & ref-qualifier
3514 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003515 // ref-qualifier
3516 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003517 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003518 // cv-qualification on the member function declaration.
3519 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003521 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003522 // (C++ [over.match.funcs]p5). We perform a simplified version of
3523 // reference binding here, that allows class rvalues to bind to
3524 // non-constant references.
3525
Douglas Gregor02824322011-01-26 19:30:28 +00003526 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003527 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003529 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003530 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003531 ICS.setBad(BadConversionSequence::bad_qualifiers,
3532 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003533 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003534 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003535
3536 // Check that we have either the same type or a derived type. It
3537 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003538 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003539 ImplicitConversionKind SecondKind;
3540 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3541 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003542 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003543 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003544 else {
John McCall65eb8792010-02-25 01:37:24 +00003545 ICS.setBad(BadConversionSequence::unrelated_class,
3546 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003547 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003548 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003549
Douglas Gregor02824322011-01-26 19:30:28 +00003550 // Check the ref-qualifier.
3551 switch (Method->getRefQualifier()) {
3552 case RQ_None:
3553 // Do nothing; we don't care about lvalueness or rvalueness.
3554 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555
Douglas Gregor02824322011-01-26 19:30:28 +00003556 case RQ_LValue:
3557 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3558 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003559 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003560 ImplicitParamType);
3561 return ICS;
3562 }
3563 break;
3564
3565 case RQ_RValue:
3566 if (!FromClassification.isRValue()) {
3567 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003569 ImplicitParamType);
3570 return ICS;
3571 }
3572 break;
3573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574
Douglas Gregor436424c2008-11-18 23:14:02 +00003575 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003576 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003577 ICS.Standard.setAsIdentityConversion();
3578 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003579 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003580 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003581 ICS.Standard.ReferenceBinding = true;
3582 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003584 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003585 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3586 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3587 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003588 return ICS;
3589}
3590
3591/// PerformObjectArgumentInitialization - Perform initialization of
3592/// the implicit object parameter for the given Method with the given
3593/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003594ExprResult
3595Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003597 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003598 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003599 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003600 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003601 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003602
Douglas Gregor02824322011-01-26 19:30:28 +00003603 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003604 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003605 FromRecordType = PT->getPointeeType();
3606 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003607 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003608 } else {
3609 FromRecordType = From->getType();
3610 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003611 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003612 }
3613
John McCall6e9f8f62009-12-03 04:06:58 +00003614 // Note that we always use the true parent context when performing
3615 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003616 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003617 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3618 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003619 if (ICS.isBad()) {
3620 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3621 Qualifiers FromQs = FromRecordType.getQualifiers();
3622 Qualifiers ToQs = DestType.getQualifiers();
3623 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3624 if (CVR) {
3625 Diag(From->getSourceRange().getBegin(),
3626 diag::err_member_function_call_bad_cvr)
3627 << Method->getDeclName() << FromRecordType << (CVR - 1)
3628 << From->getSourceRange();
3629 Diag(Method->getLocation(), diag::note_previous_decl)
3630 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003631 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003632 }
3633 }
3634
Douglas Gregor436424c2008-11-18 23:14:02 +00003635 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003636 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003637 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003638 }
Mike Stump11289f42009-09-09 15:08:12 +00003639
John Wiegley01296292011-04-08 18:41:53 +00003640 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3641 ExprResult FromRes =
3642 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3643 if (FromRes.isInvalid())
3644 return ExprError();
3645 From = FromRes.take();
3646 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003647
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003648 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003649 From = ImpCastExprToType(From, DestType, CK_NoOp,
3650 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3651 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003652}
3653
Douglas Gregor5fb53972009-01-14 15:45:31 +00003654/// TryContextuallyConvertToBool - Attempt to contextually convert the
3655/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003656static ImplicitConversionSequence
3657TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003658 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003659 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003660 // FIXME: Are these flags correct?
3661 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003662 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003663 /*InOverloadResolution=*/false,
3664 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003665}
3666
3667/// PerformContextuallyConvertToBool - Perform a contextual conversion
3668/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003669ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003670 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003671 if (!ICS.isBad())
3672 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673
Fariborz Jahanian76197412009-11-18 18:26:29 +00003674 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003675 return Diag(From->getSourceRange().getBegin(),
3676 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003677 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003678 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003679}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003681/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3682/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003683static ImplicitConversionSequence
3684TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3685 QualType Ty = S.Context.getObjCIdType();
3686 return TryImplicitConversion(S, From, Ty,
3687 // FIXME: Are these flags correct?
3688 /*SuppressUserConversions=*/false,
3689 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003690 /*InOverloadResolution=*/false,
3691 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003692}
John McCall5c32be02010-08-24 20:38:10 +00003693
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003694/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3695/// of the expression From to 'id'.
John Wiegley01296292011-04-08 18:41:53 +00003696ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003697 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003698 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003699 if (!ICS.isBad())
3700 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003701 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003702}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003703
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003704/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003705/// enumeration type.
3706///
3707/// This routine will attempt to convert an expression of class type to an
3708/// integral or enumeration type, if that class type only has a single
3709/// conversion to an integral or enumeration type.
3710///
Douglas Gregor4799d032010-06-30 00:20:43 +00003711/// \param Loc The source location of the construct that requires the
3712/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003713///
Douglas Gregor4799d032010-06-30 00:20:43 +00003714/// \param FromE The expression we're converting from.
3715///
3716/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3717/// have integral or enumeration type.
3718///
3719/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3720/// incomplete class type.
3721///
3722/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3723/// explicit conversion function (because no implicit conversion functions
3724/// were available). This is a recovery mode.
3725///
3726/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3727/// showing which conversion was picked.
3728///
3729/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3730/// conversion function that could convert to integral or enumeration type.
3731///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003733/// usable conversion function.
3734///
3735/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3736/// function, which may be an extension in this case.
3737///
3738/// \returns The expression, converted to an integral or enumeration type if
3739/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003740ExprResult
John McCallb268a282010-08-23 23:25:46 +00003741Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003742 const PartialDiagnostic &NotIntDiag,
3743 const PartialDiagnostic &IncompleteDiag,
3744 const PartialDiagnostic &ExplicitConvDiag,
3745 const PartialDiagnostic &ExplicitConvNote,
3746 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003747 const PartialDiagnostic &AmbigNote,
3748 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003749 // We can't perform any more checking for type-dependent expressions.
3750 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003751 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003752
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003753 // If the expression already has integral or enumeration type, we're golden.
3754 QualType T = From->getType();
3755 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003756 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003757
3758 // FIXME: Check for missing '()' if T is a function type?
3759
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003761 // expression of integral or enumeration type.
3762 const RecordType *RecordTy = T->getAs<RecordType>();
3763 if (!RecordTy || !getLangOptions().CPlusPlus) {
3764 Diag(Loc, NotIntDiag)
3765 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003766 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003767 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003769 // We must have a complete class type.
3770 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003771 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003773 // Look for a conversion to an integral or enumeration type.
3774 UnresolvedSet<4> ViableConversions;
3775 UnresolvedSet<4> ExplicitConversions;
3776 const UnresolvedSetImpl *Conversions
3777 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003779 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780 E = Conversions->end();
3781 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003782 ++I) {
3783 if (CXXConversionDecl *Conversion
3784 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3785 if (Conversion->getConversionType().getNonReferenceType()
3786 ->isIntegralOrEnumerationType()) {
3787 if (Conversion->isExplicit())
3788 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3789 else
3790 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3791 }
3792 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003793
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003794 switch (ViableConversions.size()) {
3795 case 0:
3796 if (ExplicitConversions.size() == 1) {
3797 DeclAccessPair Found = ExplicitConversions[0];
3798 CXXConversionDecl *Conversion
3799 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003801 // The user probably meant to invoke the given explicit
3802 // conversion; use it.
3803 QualType ConvTy
3804 = Conversion->getConversionType().getNonReferenceType();
3805 std::string TypeStr;
3806 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003807
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003808 Diag(Loc, ExplicitConvDiag)
3809 << T << ConvTy
3810 << FixItHint::CreateInsertion(From->getLocStart(),
3811 "static_cast<" + TypeStr + ">(")
3812 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3813 ")");
3814 Diag(Conversion->getLocation(), ExplicitConvNote)
3815 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
3817 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003818 // explicit conversion function.
3819 if (isSFINAEContext())
3820 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003822 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003823 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3824 if (Result.isInvalid())
3825 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003826
Douglas Gregor668443e2011-01-20 00:18:04 +00003827 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003828 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003829
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003830 // We'll complain below about a non-integral condition type.
3831 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003833 case 1: {
3834 // Apply this conversion.
3835 DeclAccessPair Found = ViableConversions[0];
3836 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837
Douglas Gregor4799d032010-06-30 00:20:43 +00003838 CXXConversionDecl *Conversion
3839 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3840 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003841 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00003842 if (ConvDiag.getDiagID()) {
3843 if (isSFINAEContext())
3844 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845
Douglas Gregor4799d032010-06-30 00:20:43 +00003846 Diag(Loc, ConvDiag)
3847 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3848 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003849
Douglas Gregor668443e2011-01-20 00:18:04 +00003850 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003851 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003852 if (Result.isInvalid())
3853 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003854
Douglas Gregor668443e2011-01-20 00:18:04 +00003855 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003856 break;
3857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003859 default:
3860 Diag(Loc, AmbigDiag)
3861 << T << From->getSourceRange();
3862 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3863 CXXConversionDecl *Conv
3864 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3865 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3866 Diag(Conv->getLocation(), AmbigNote)
3867 << ConvTy->isEnumeralType() << ConvTy;
3868 }
John McCallb268a282010-08-23 23:25:46 +00003869 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003870 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003871
Douglas Gregor5823da32010-06-29 23:25:20 +00003872 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003873 Diag(Loc, NotIntDiag)
3874 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003875
John McCallb268a282010-08-23 23:25:46 +00003876 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003877}
3878
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003879/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003880/// candidate functions, using the given function call arguments. If
3881/// @p SuppressUserConversions, then don't allow user-defined
3882/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003883///
3884/// \para PartialOverloading true if we are performing "partial" overloading
3885/// based on an incomplete set of function arguments. This feature is used by
3886/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003887void
3888Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003889 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003890 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003891 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003892 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003893 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003894 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003895 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003896 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003897 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003898 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003899
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003900 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003901 if (!isa<CXXConstructorDecl>(Method)) {
3902 // If we get here, it's because we're calling a member function
3903 // that is named without a member access expression (e.g.,
3904 // "this->f") that was either written explicitly or created
3905 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003906 // function, e.g., X::f(). We use an empty type for the implied
3907 // object argument (C++ [over.call.func]p3), and the acting context
3908 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003909 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00003911 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003912 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003913 return;
3914 }
3915 // We treat a constructor like a non-member function, since its object
3916 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003917 }
3918
Douglas Gregorff7028a2009-11-13 23:59:09 +00003919 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003920 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003921
Douglas Gregor27381f32009-11-23 12:27:39 +00003922 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003923 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003924
Douglas Gregorffe14e32009-11-14 01:20:54 +00003925 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3926 // C++ [class.copy]p3:
3927 // A member function template is never instantiated to perform the copy
3928 // of a class object to an object of its class type.
3929 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003931 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003932 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3933 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003934 return;
3935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003936
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003937 // Add this candidate
3938 CandidateSet.push_back(OverloadCandidate());
3939 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003940 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003941 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003942 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003943 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003944 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003945 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003947 unsigned NumArgsInProto = Proto->getNumArgs();
3948
3949 // (C++ 13.3.2p2): A candidate function having fewer than m
3950 // parameters is viable only if it has an ellipsis in its parameter
3951 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00003953 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003954 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003955 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003956 return;
3957 }
3958
3959 // (C++ 13.3.2p2): A candidate function having more than m parameters
3960 // is viable only if the (m+1)st parameter has a default argument
3961 // (8.3.6). For the purposes of overload resolution, the
3962 // parameter list is truncated on the right, so that there are
3963 // exactly m parameters.
3964 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003965 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003966 // Not enough arguments.
3967 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003968 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003969 return;
3970 }
3971
3972 // Determine the implicit conversion sequences for each of the
3973 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003974 Candidate.Conversions.resize(NumArgs);
3975 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3976 if (ArgIdx < NumArgsInProto) {
3977 // (C++ 13.3.2p3): for F to be a viable function, there shall
3978 // exist for each argument an implicit conversion sequence
3979 // (13.3.3.1) that converts that argument to the corresponding
3980 // parameter of F.
3981 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003982 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003983 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003984 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003985 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003986 if (Candidate.Conversions[ArgIdx].isBad()) {
3987 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003988 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003989 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003990 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003991 } else {
3992 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3993 // argument for which there is no corresponding parameter is
3994 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003995 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003996 }
3997 }
3998}
3999
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004000/// \brief Add all of the function declarations in the given function set to
4001/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004002void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004003 Expr **Args, unsigned NumArgs,
4004 OverloadCandidateSet& CandidateSet,
4005 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004006 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004007 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4008 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004009 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004010 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004011 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004012 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004013 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004014 CandidateSet, SuppressUserConversions);
4015 else
John McCalla0296f72010-03-19 07:35:19 +00004016 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004017 SuppressUserConversions);
4018 } else {
John McCalla0296f72010-03-19 07:35:19 +00004019 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004020 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4021 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004022 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004023 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004024 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004025 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004026 Args[0]->Classify(Context),
4027 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004028 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004029 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004030 else
John McCalla0296f72010-03-19 07:35:19 +00004031 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004032 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004033 Args, NumArgs, CandidateSet,
4034 SuppressUserConversions);
4035 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004036 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004037}
4038
John McCallf0f1cf02009-11-17 07:50:12 +00004039/// AddMethodCandidate - Adds a named decl (which is some kind of
4040/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004041void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004042 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004043 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004044 Expr **Args, unsigned NumArgs,
4045 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004046 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004047 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004048 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004049
4050 if (isa<UsingShadowDecl>(Decl))
4051 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052
John McCallf0f1cf02009-11-17 07:50:12 +00004053 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4054 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4055 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004056 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4057 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004058 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004059 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004060 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004061 } else {
John McCalla0296f72010-03-19 07:35:19 +00004062 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004063 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004064 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004065 }
4066}
4067
Douglas Gregor436424c2008-11-18 23:14:02 +00004068/// AddMethodCandidate - Adds the given C++ member function to the set
4069/// of candidate functions, using the given function call arguments
4070/// and the object argument (@c Object). For example, in a call
4071/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4072/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4073/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004074/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004075void
John McCalla0296f72010-03-19 07:35:19 +00004076Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004077 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004078 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004079 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004080 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004081 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004082 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004083 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004084 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004085 assert(!isa<CXXConstructorDecl>(Method) &&
4086 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004087
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004088 if (!CandidateSet.isNewCandidate(Method))
4089 return;
4090
Douglas Gregor27381f32009-11-23 12:27:39 +00004091 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004092 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004093
Douglas Gregor436424c2008-11-18 23:14:02 +00004094 // Add this candidate
4095 CandidateSet.push_back(OverloadCandidate());
4096 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004097 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004098 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004099 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004100 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004101 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004102
4103 unsigned NumArgsInProto = Proto->getNumArgs();
4104
4105 // (C++ 13.3.2p2): A candidate function having fewer than m
4106 // parameters is viable only if it has an ellipsis in its parameter
4107 // list (8.3.5).
4108 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4109 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004110 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004111 return;
4112 }
4113
4114 // (C++ 13.3.2p2): A candidate function having more than m parameters
4115 // is viable only if the (m+1)st parameter has a default argument
4116 // (8.3.6). For the purposes of overload resolution, the
4117 // parameter list is truncated on the right, so that there are
4118 // exactly m parameters.
4119 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4120 if (NumArgs < MinRequiredArgs) {
4121 // Not enough arguments.
4122 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004123 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004124 return;
4125 }
4126
4127 Candidate.Viable = true;
4128 Candidate.Conversions.resize(NumArgs + 1);
4129
John McCall6e9f8f62009-12-03 04:06:58 +00004130 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004131 // The implicit object argument is ignored.
4132 Candidate.IgnoreObjectArgument = true;
4133 else {
4134 // Determine the implicit conversion sequence for the object
4135 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004136 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004137 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4138 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004139 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004140 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004141 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004142 return;
4143 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004144 }
4145
4146 // Determine the implicit conversion sequences for each of the
4147 // arguments.
4148 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4149 if (ArgIdx < NumArgsInProto) {
4150 // (C++ 13.3.2p3): for F to be a viable function, there shall
4151 // exist for each argument an implicit conversion sequence
4152 // (13.3.3.1) that converts that argument to the corresponding
4153 // parameter of F.
4154 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004155 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004156 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004157 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00004158 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00004159 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004160 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004161 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004162 break;
4163 }
4164 } else {
4165 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4166 // argument for which there is no corresponding parameter is
4167 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004168 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004169 }
4170 }
4171}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
Douglas Gregor97628d62009-08-21 00:16:32 +00004173/// \brief Add a C++ member function template as a candidate to the candidate
4174/// set, using template argument deduction to produce an appropriate member
4175/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004176void
Douglas Gregor97628d62009-08-21 00:16:32 +00004177Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004178 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004179 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004180 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004181 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004182 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004183 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004184 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004185 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004186 if (!CandidateSet.isNewCandidate(MethodTmpl))
4187 return;
4188
Douglas Gregor97628d62009-08-21 00:16:32 +00004189 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004190 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004191 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004192 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004193 // candidate functions in the usual way.113) A given name can refer to one
4194 // or more function templates and also to a set of overloaded non-template
4195 // functions. In such a case, the candidate functions generated from each
4196 // function template are combined with the set of non-template candidate
4197 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004198 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004199 FunctionDecl *Specialization = 0;
4200 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004201 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004202 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004203 CandidateSet.push_back(OverloadCandidate());
4204 OverloadCandidate &Candidate = CandidateSet.back();
4205 Candidate.FoundDecl = FoundDecl;
4206 Candidate.Function = MethodTmpl->getTemplatedDecl();
4207 Candidate.Viable = false;
4208 Candidate.FailureKind = ovl_fail_bad_deduction;
4209 Candidate.IsSurrogate = false;
4210 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004211 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004213 Info);
4214 return;
4215 }
Mike Stump11289f42009-09-09 15:08:12 +00004216
Douglas Gregor97628d62009-08-21 00:16:32 +00004217 // Add the function template specialization produced by template argument
4218 // deduction as a candidate.
4219 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004220 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004221 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004222 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004223 ActingContext, ObjectType, ObjectClassification,
4224 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004225}
4226
Douglas Gregor05155d82009-08-21 23:19:43 +00004227/// \brief Add a C++ function template specialization as a candidate
4228/// in the candidate set, using template argument deduction to produce
4229/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004230void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004231Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004232 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004233 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004234 Expr **Args, unsigned NumArgs,
4235 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004236 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004237 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4238 return;
4239
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004240 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004241 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004242 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004243 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004244 // candidate functions in the usual way.113) A given name can refer to one
4245 // or more function templates and also to a set of overloaded non-template
4246 // functions. In such a case, the candidate functions generated from each
4247 // function template are combined with the set of non-template candidate
4248 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004249 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004250 FunctionDecl *Specialization = 0;
4251 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004252 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004253 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004254 CandidateSet.push_back(OverloadCandidate());
4255 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004256 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004257 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4258 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004259 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004260 Candidate.IsSurrogate = false;
4261 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004262 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004264 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004265 return;
4266 }
Mike Stump11289f42009-09-09 15:08:12 +00004267
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004268 // Add the function template specialization produced by template argument
4269 // deduction as a candidate.
4270 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004271 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004272 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004273}
Mike Stump11289f42009-09-09 15:08:12 +00004274
Douglas Gregora1f013e2008-11-07 22:36:19 +00004275/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004276/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004277/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004278/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004279/// (which may or may not be the same type as the type that the
4280/// conversion function produces).
4281void
4282Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004283 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004284 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004285 Expr *From, QualType ToType,
4286 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004287 assert(!Conversion->getDescribedFunctionTemplate() &&
4288 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004289 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004290 if (!CandidateSet.isNewCandidate(Conversion))
4291 return;
4292
Douglas Gregor27381f32009-11-23 12:27:39 +00004293 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004294 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004295
Douglas Gregora1f013e2008-11-07 22:36:19 +00004296 // Add this candidate
4297 CandidateSet.push_back(OverloadCandidate());
4298 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004299 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004300 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004301 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004302 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004303 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004304 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004305 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004306 Candidate.Viable = true;
4307 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004308 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004309
Douglas Gregor6affc782010-08-19 15:37:02 +00004310 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004311 // For conversion functions, the function is considered to be a member of
4312 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004313 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004314 //
4315 // Determine the implicit conversion sequence for the implicit
4316 // object parameter.
4317 QualType ImplicitParamType = From->getType();
4318 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4319 ImplicitParamType = FromPtrType->getPointeeType();
4320 CXXRecordDecl *ConversionContext
4321 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004323 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324 = TryObjectArgumentInitialization(*this, From->getType(),
4325 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004326 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327
John McCall0d1da222010-01-12 00:44:57 +00004328 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004329 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004330 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004331 return;
4332 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004333
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004335 // derived to base as such conversions are given Conversion Rank. They only
4336 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4337 QualType FromCanon
4338 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4339 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4340 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4341 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004342 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004343 return;
4344 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345
Douglas Gregora1f013e2008-11-07 22:36:19 +00004346 // To determine what the conversion from the result of calling the
4347 // conversion function to the type we're eventually trying to
4348 // convert to (ToType), we need to synthesize a call to the
4349 // conversion function and attempt copy initialization from it. This
4350 // makes sure that we get the right semantics with respect to
4351 // lvalues/rvalues and the type. Fortunately, we can allocate this
4352 // call on the stack and we don't need its arguments to be
4353 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004354 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004355 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004356 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4357 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004358 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004359 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004360
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004361 QualType CallResultType
4362 = Conversion->getConversionType().getNonLValueExprType(Context);
4363 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4364 Candidate.Viable = false;
4365 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4366 return;
4367 }
4368
John McCall7decc9e2010-11-18 06:31:45 +00004369 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4370
Mike Stump11289f42009-09-09 15:08:12 +00004371 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004372 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4373 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004374 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004375 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004376 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004377 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004378 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004379 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004380
John McCall0d1da222010-01-12 00:44:57 +00004381 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004382 case ImplicitConversionSequence::StandardConversion:
4383 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004384
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004385 // C++ [over.ics.user]p3:
4386 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004387 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004388 // shall have exact match rank.
4389 if (Conversion->getPrimaryTemplate() &&
4390 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4391 Candidate.Viable = false;
4392 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394
Douglas Gregorcba72b12011-01-21 05:18:22 +00004395 // C++0x [dcl.init.ref]p5:
4396 // In the second case, if the reference is an rvalue reference and
4397 // the second standard conversion sequence of the user-defined
4398 // conversion sequence includes an lvalue-to-rvalue conversion, the
4399 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004400 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004401 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4402 Candidate.Viable = false;
4403 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4404 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004405 break;
4406
4407 case ImplicitConversionSequence::BadConversion:
4408 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004409 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004410 break;
4411
4412 default:
Mike Stump11289f42009-09-09 15:08:12 +00004413 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004414 "Can only end up with a standard conversion sequence or failure");
4415 }
4416}
4417
Douglas Gregor05155d82009-08-21 23:19:43 +00004418/// \brief Adds a conversion function template specialization
4419/// candidate to the overload set, using template argument deduction
4420/// to deduce the template arguments of the conversion function
4421/// template from the type that we are converting to (C++
4422/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004423void
Douglas Gregor05155d82009-08-21 23:19:43 +00004424Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004425 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004426 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004427 Expr *From, QualType ToType,
4428 OverloadCandidateSet &CandidateSet) {
4429 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4430 "Only conversion function templates permitted here");
4431
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004432 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4433 return;
4434
John McCallbc077cf2010-02-08 23:07:23 +00004435 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004436 CXXConversionDecl *Specialization = 0;
4437 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004438 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004439 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004440 CandidateSet.push_back(OverloadCandidate());
4441 OverloadCandidate &Candidate = CandidateSet.back();
4442 Candidate.FoundDecl = FoundDecl;
4443 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4444 Candidate.Viable = false;
4445 Candidate.FailureKind = ovl_fail_bad_deduction;
4446 Candidate.IsSurrogate = false;
4447 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004448 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004449 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004450 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004451 return;
4452 }
Mike Stump11289f42009-09-09 15:08:12 +00004453
Douglas Gregor05155d82009-08-21 23:19:43 +00004454 // Add the conversion function template specialization produced by
4455 // template argument deduction as a candidate.
4456 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004457 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004458 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004459}
4460
Douglas Gregorab7897a2008-11-19 22:57:39 +00004461/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4462/// converts the given @c Object to a function pointer via the
4463/// conversion function @c Conversion, and then attempts to call it
4464/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4465/// the type of function that we'll eventually be calling.
4466void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004467 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004468 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004469 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004470 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004471 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004472 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004473 if (!CandidateSet.isNewCandidate(Conversion))
4474 return;
4475
Douglas Gregor27381f32009-11-23 12:27:39 +00004476 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004477 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004478
Douglas Gregorab7897a2008-11-19 22:57:39 +00004479 CandidateSet.push_back(OverloadCandidate());
4480 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004481 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004482 Candidate.Function = 0;
4483 Candidate.Surrogate = Conversion;
4484 Candidate.Viable = true;
4485 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004486 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004487 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004488 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004489
4490 // Determine the implicit conversion sequence for the implicit
4491 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004492 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004494 Object->Classify(Context),
4495 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004496 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004497 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004498 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004499 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004500 return;
4501 }
4502
4503 // The first conversion is actually a user-defined conversion whose
4504 // first conversion is ObjectInit's standard conversion (which is
4505 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004506 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004507 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004508 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004509 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004511 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004512 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004513 = Candidate.Conversions[0].UserDefined.Before;
4514 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4515
Mike Stump11289f42009-09-09 15:08:12 +00004516 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004517 unsigned NumArgsInProto = Proto->getNumArgs();
4518
4519 // (C++ 13.3.2p2): A candidate function having fewer than m
4520 // parameters is viable only if it has an ellipsis in its parameter
4521 // list (8.3.5).
4522 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4523 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004524 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004525 return;
4526 }
4527
4528 // Function types don't have any default arguments, so just check if
4529 // we have enough arguments.
4530 if (NumArgs < NumArgsInProto) {
4531 // Not enough arguments.
4532 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004533 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004534 return;
4535 }
4536
4537 // Determine the implicit conversion sequences for each of the
4538 // arguments.
4539 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4540 if (ArgIdx < NumArgsInProto) {
4541 // (C++ 13.3.2p3): for F to be a viable function, there shall
4542 // exist for each argument an implicit conversion sequence
4543 // (13.3.3.1) that converts that argument to the corresponding
4544 // parameter of F.
4545 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004546 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004547 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004548 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004549 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004550 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004551 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004552 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004553 break;
4554 }
4555 } else {
4556 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4557 // argument for which there is no corresponding parameter is
4558 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004559 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004560 }
4561 }
4562}
4563
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004564/// \brief Add overload candidates for overloaded operators that are
4565/// member functions.
4566///
4567/// Add the overloaded operator candidates that are member functions
4568/// for the operator Op that was used in an operator expression such
4569/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4570/// CandidateSet will store the added overload candidates. (C++
4571/// [over.match.oper]).
4572void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4573 SourceLocation OpLoc,
4574 Expr **Args, unsigned NumArgs,
4575 OverloadCandidateSet& CandidateSet,
4576 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004577 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4578
4579 // C++ [over.match.oper]p3:
4580 // For a unary operator @ with an operand of a type whose
4581 // cv-unqualified version is T1, and for a binary operator @ with
4582 // a left operand of a type whose cv-unqualified version is T1 and
4583 // a right operand of a type whose cv-unqualified version is T2,
4584 // three sets of candidate functions, designated member
4585 // candidates, non-member candidates and built-in candidates, are
4586 // constructed as follows:
4587 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004588
4589 // -- If T1 is a class type, the set of member candidates is the
4590 // result of the qualified lookup of T1::operator@
4591 // (13.3.1.1.1); otherwise, the set of member candidates is
4592 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004593 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004594 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004595 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004596 return;
Mike Stump11289f42009-09-09 15:08:12 +00004597
John McCall27b18f82009-11-17 02:14:36 +00004598 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4599 LookupQualifiedName(Operators, T1Rec->getDecl());
4600 Operators.suppressDiagnostics();
4601
Mike Stump11289f42009-09-09 15:08:12 +00004602 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004603 OperEnd = Operators.end();
4604 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004605 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004606 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004608 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004609 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004610 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004611}
4612
Douglas Gregora11693b2008-11-12 17:17:38 +00004613/// AddBuiltinCandidate - Add a candidate for a built-in
4614/// operator. ResultTy and ParamTys are the result and parameter types
4615/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004616/// arguments being passed to the candidate. IsAssignmentOperator
4617/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004618/// operator. NumContextualBoolArguments is the number of arguments
4619/// (at the beginning of the argument list) that will be contextually
4620/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004621void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004622 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004623 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004624 bool IsAssignmentOperator,
4625 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004626 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004627 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004628
Douglas Gregora11693b2008-11-12 17:17:38 +00004629 // Add this candidate
4630 CandidateSet.push_back(OverloadCandidate());
4631 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004632 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004633 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004634 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004635 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004636 Candidate.BuiltinTypes.ResultTy = ResultTy;
4637 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4638 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4639
4640 // Determine the implicit conversion sequences for each of the
4641 // arguments.
4642 Candidate.Viable = true;
4643 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004644 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004645 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004646 // C++ [over.match.oper]p4:
4647 // For the built-in assignment operators, conversions of the
4648 // left operand are restricted as follows:
4649 // -- no temporaries are introduced to hold the left operand, and
4650 // -- no user-defined conversions are applied to the left
4651 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004652 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004653 //
4654 // We block these conversions by turning off user-defined
4655 // conversions, since that is the only way that initialization of
4656 // a reference to a non-class type can occur from something that
4657 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004658 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004659 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004660 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004661 Candidate.Conversions[ArgIdx]
4662 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004663 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004664 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004665 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004666 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004667 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004668 }
John McCall0d1da222010-01-12 00:44:57 +00004669 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004670 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004671 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004672 break;
4673 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004674 }
4675}
4676
4677/// BuiltinCandidateTypeSet - A set of types that will be used for the
4678/// candidate operator functions for built-in operators (C++
4679/// [over.built]). The types are separated into pointer types and
4680/// enumeration types.
4681class BuiltinCandidateTypeSet {
4682 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004683 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004684
4685 /// PointerTypes - The set of pointer types that will be used in the
4686 /// built-in candidates.
4687 TypeSet PointerTypes;
4688
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004689 /// MemberPointerTypes - The set of member pointer types that will be
4690 /// used in the built-in candidates.
4691 TypeSet MemberPointerTypes;
4692
Douglas Gregora11693b2008-11-12 17:17:38 +00004693 /// EnumerationTypes - The set of enumeration types that will be
4694 /// used in the built-in candidates.
4695 TypeSet EnumerationTypes;
4696
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004697 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004698 /// candidates.
4699 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004700
4701 /// \brief A flag indicating non-record types are viable candidates
4702 bool HasNonRecordTypes;
4703
4704 /// \brief A flag indicating whether either arithmetic or enumeration types
4705 /// were present in the candidate set.
4706 bool HasArithmeticOrEnumeralTypes;
4707
Douglas Gregor80af3132011-05-21 23:15:46 +00004708 /// \brief A flag indicating whether the nullptr type was present in the
4709 /// candidate set.
4710 bool HasNullPtrType;
4711
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004712 /// Sema - The semantic analysis instance where we are building the
4713 /// candidate type set.
4714 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004715
Douglas Gregora11693b2008-11-12 17:17:38 +00004716 /// Context - The AST context in which we will build the type sets.
4717 ASTContext &Context;
4718
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004719 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4720 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004721 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004722
4723public:
4724 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004725 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004726
Mike Stump11289f42009-09-09 15:08:12 +00004727 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004728 : HasNonRecordTypes(false),
4729 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00004730 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00004731 SemaRef(SemaRef),
4732 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004733
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004735 SourceLocation Loc,
4736 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004737 bool AllowExplicitConversions,
4738 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004739
4740 /// pointer_begin - First pointer type found;
4741 iterator pointer_begin() { return PointerTypes.begin(); }
4742
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004743 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004744 iterator pointer_end() { return PointerTypes.end(); }
4745
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004746 /// member_pointer_begin - First member pointer type found;
4747 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4748
4749 /// member_pointer_end - Past the last member pointer type found;
4750 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4751
Douglas Gregora11693b2008-11-12 17:17:38 +00004752 /// enumeration_begin - First enumeration type found;
4753 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4754
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004755 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004756 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004757
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004758 iterator vector_begin() { return VectorTypes.begin(); }
4759 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004760
4761 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4762 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00004763 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004764};
4765
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004766/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004767/// the set of pointer types along with any more-qualified variants of
4768/// that type. For example, if @p Ty is "int const *", this routine
4769/// will add "int const *", "int const volatile *", "int const
4770/// restrict *", and "int const volatile restrict *" to the set of
4771/// pointer types. Returns true if the add of @p Ty itself succeeded,
4772/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004773///
4774/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004775bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004776BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4777 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004778
Douglas Gregora11693b2008-11-12 17:17:38 +00004779 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004780 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004781 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004783 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004784 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004785 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004786 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004787 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004788 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004789 buildObjCPtr = true;
4790 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004791 else
4792 assert(false && "type was not a pointer type!");
4793 }
4794 else
4795 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796
Sebastian Redl4990a632009-11-18 20:39:26 +00004797 // Don't add qualified variants of arrays. For one, they're not allowed
4798 // (the qualifier would sink to the element type), and for another, the
4799 // only overload situation where it matters is subscript or pointer +- int,
4800 // and those shouldn't have qualifier variants anyway.
4801 if (PointeeTy->isArrayType())
4802 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004803 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004804 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004805 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004806 bool hasVolatile = VisibleQuals.hasVolatile();
4807 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808
John McCall8ccfcb52009-09-24 19:53:00 +00004809 // Iterate through all strict supersets of BaseCVR.
4810 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4811 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004812 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4813 // in the types.
4814 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4815 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004816 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004817 if (!buildObjCPtr)
4818 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4819 else
4820 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004821 }
4822
4823 return true;
4824}
4825
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004826/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4827/// to the set of pointer types along with any more-qualified variants of
4828/// that type. For example, if @p Ty is "int const *", this routine
4829/// will add "int const *", "int const volatile *", "int const
4830/// restrict *", and "int const volatile restrict *" to the set of
4831/// pointer types. Returns true if the add of @p Ty itself succeeded,
4832/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004833///
4834/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004835bool
4836BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4837 QualType Ty) {
4838 // Insert this type.
4839 if (!MemberPointerTypes.insert(Ty))
4840 return false;
4841
John McCall8ccfcb52009-09-24 19:53:00 +00004842 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4843 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004844
John McCall8ccfcb52009-09-24 19:53:00 +00004845 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004846 // Don't add qualified variants of arrays. For one, they're not allowed
4847 // (the qualifier would sink to the element type), and for another, the
4848 // only overload situation where it matters is subscript or pointer +- int,
4849 // and those shouldn't have qualifier variants anyway.
4850 if (PointeeTy->isArrayType())
4851 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004852 const Type *ClassTy = PointerTy->getClass();
4853
4854 // Iterate through all strict supersets of the pointee type's CVR
4855 // qualifiers.
4856 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4857 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4858 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859
John McCall8ccfcb52009-09-24 19:53:00 +00004860 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004861 MemberPointerTypes.insert(
4862 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004863 }
4864
4865 return true;
4866}
4867
Douglas Gregora11693b2008-11-12 17:17:38 +00004868/// AddTypesConvertedFrom - Add each of the types to which the type @p
4869/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004870/// primarily interested in pointer types and enumeration types. We also
4871/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004872/// AllowUserConversions is true if we should look at the conversion
4873/// functions of a class type, and AllowExplicitConversions if we
4874/// should also include the explicit conversion functions of a class
4875/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004876void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004877BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004878 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004879 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004880 bool AllowExplicitConversions,
4881 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004882 // Only deal with canonical types.
4883 Ty = Context.getCanonicalType(Ty);
4884
4885 // Look through reference types; they aren't part of the type of an
4886 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004887 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004888 Ty = RefTy->getPointeeType();
4889
John McCall33ddac02011-01-19 10:06:00 +00004890 // If we're dealing with an array type, decay to the pointer.
4891 if (Ty->isArrayType())
4892 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4893
4894 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004895 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004896
Chandler Carruth00a38332010-12-13 01:44:01 +00004897 // Flag if we ever add a non-record type.
4898 const RecordType *TyRec = Ty->getAs<RecordType>();
4899 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4900
Chandler Carruth00a38332010-12-13 01:44:01 +00004901 // Flag if we encounter an arithmetic type.
4902 HasArithmeticOrEnumeralTypes =
4903 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4904
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004905 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4906 PointerTypes.insert(Ty);
4907 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004908 // Insert our type, and its more-qualified variants, into the set
4909 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004910 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004911 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004912 } else if (Ty->isMemberPointerType()) {
4913 // Member pointers are far easier, since the pointee can't be converted.
4914 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4915 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004916 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004917 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004918 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004919 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004920 // We treat vector types as arithmetic types in many contexts as an
4921 // extension.
4922 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004923 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00004924 } else if (Ty->isNullPtrType()) {
4925 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00004926 } else if (AllowUserConversions && TyRec) {
4927 // No conversion functions in incomplete types.
4928 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4929 return;
Mike Stump11289f42009-09-09 15:08:12 +00004930
Chandler Carruth00a38332010-12-13 01:44:01 +00004931 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4932 const UnresolvedSetImpl *Conversions
4933 = ClassDecl->getVisibleConversionFunctions();
4934 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4935 E = Conversions->end(); I != E; ++I) {
4936 NamedDecl *D = I.getDecl();
4937 if (isa<UsingShadowDecl>(D))
4938 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004939
Chandler Carruth00a38332010-12-13 01:44:01 +00004940 // Skip conversion function templates; they don't tell us anything
4941 // about which builtin types we can convert to.
4942 if (isa<FunctionTemplateDecl>(D))
4943 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004944
Chandler Carruth00a38332010-12-13 01:44:01 +00004945 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4946 if (AllowExplicitConversions || !Conv->isExplicit()) {
4947 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4948 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004949 }
4950 }
4951 }
4952}
4953
Douglas Gregor84605ae2009-08-24 13:43:27 +00004954/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4955/// the volatile- and non-volatile-qualified assignment operators for the
4956/// given type to the candidate set.
4957static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4958 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004959 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004960 unsigned NumArgs,
4961 OverloadCandidateSet &CandidateSet) {
4962 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004963
Douglas Gregor84605ae2009-08-24 13:43:27 +00004964 // T& operator=(T&, T)
4965 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4966 ParamTypes[1] = T;
4967 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4968 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004969
Douglas Gregor84605ae2009-08-24 13:43:27 +00004970 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4971 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004972 ParamTypes[0]
4973 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004974 ParamTypes[1] = T;
4975 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004976 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004977 }
4978}
Mike Stump11289f42009-09-09 15:08:12 +00004979
Sebastian Redl1054fae2009-10-25 17:03:50 +00004980/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4981/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004982static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4983 Qualifiers VRQuals;
4984 const RecordType *TyRec;
4985 if (const MemberPointerType *RHSMPType =
4986 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004987 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004988 else
4989 TyRec = ArgExpr->getType()->getAs<RecordType>();
4990 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004991 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004992 VRQuals.addVolatile();
4993 VRQuals.addRestrict();
4994 return VRQuals;
4995 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004997 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004998 if (!ClassDecl->hasDefinition())
4999 return VRQuals;
5000
John McCallad371252010-01-20 00:46:10 +00005001 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005002 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005003
John McCallad371252010-01-20 00:46:10 +00005004 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005005 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005006 NamedDecl *D = I.getDecl();
5007 if (isa<UsingShadowDecl>(D))
5008 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5009 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005010 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5011 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5012 CanTy = ResTypeRef->getPointeeType();
5013 // Need to go down the pointer/mempointer chain and add qualifiers
5014 // as see them.
5015 bool done = false;
5016 while (!done) {
5017 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5018 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005019 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005020 CanTy->getAs<MemberPointerType>())
5021 CanTy = ResTypeMPtr->getPointeeType();
5022 else
5023 done = true;
5024 if (CanTy.isVolatileQualified())
5025 VRQuals.addVolatile();
5026 if (CanTy.isRestrictQualified())
5027 VRQuals.addRestrict();
5028 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5029 return VRQuals;
5030 }
5031 }
5032 }
5033 return VRQuals;
5034}
John McCall52872982010-11-13 05:51:15 +00005035
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005036namespace {
John McCall52872982010-11-13 05:51:15 +00005037
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005038/// \brief Helper class to manage the addition of builtin operator overload
5039/// candidates. It provides shared state and utility methods used throughout
5040/// the process, as well as a helper method to add each group of builtin
5041/// operator overloads from the standard to a candidate set.
5042class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005043 // Common instance state available to all overload candidate addition methods.
5044 Sema &S;
5045 Expr **Args;
5046 unsigned NumArgs;
5047 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005048 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005049 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
5050 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005051
Chandler Carruthc6586e52010-12-12 10:35:00 +00005052 // Define some constants used to index and iterate over the arithemetic types
5053 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005054 // The "promoted arithmetic types" are the arithmetic
5055 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005056 static const unsigned FirstIntegralType = 3;
5057 static const unsigned LastIntegralType = 18;
5058 static const unsigned FirstPromotedIntegralType = 3,
5059 LastPromotedIntegralType = 9;
5060 static const unsigned FirstPromotedArithmeticType = 0,
5061 LastPromotedArithmeticType = 9;
5062 static const unsigned NumArithmeticTypes = 18;
5063
Chandler Carruthc6586e52010-12-12 10:35:00 +00005064 /// \brief Get the canonical type for a given arithmetic type index.
5065 CanQualType getArithmeticType(unsigned index) {
5066 assert(index < NumArithmeticTypes);
5067 static CanQualType ASTContext::* const
5068 ArithmeticTypes[NumArithmeticTypes] = {
5069 // Start of promoted types.
5070 &ASTContext::FloatTy,
5071 &ASTContext::DoubleTy,
5072 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005073
Chandler Carruthc6586e52010-12-12 10:35:00 +00005074 // Start of integral types.
5075 &ASTContext::IntTy,
5076 &ASTContext::LongTy,
5077 &ASTContext::LongLongTy,
5078 &ASTContext::UnsignedIntTy,
5079 &ASTContext::UnsignedLongTy,
5080 &ASTContext::UnsignedLongLongTy,
5081 // End of promoted types.
5082
5083 &ASTContext::BoolTy,
5084 &ASTContext::CharTy,
5085 &ASTContext::WCharTy,
5086 &ASTContext::Char16Ty,
5087 &ASTContext::Char32Ty,
5088 &ASTContext::SignedCharTy,
5089 &ASTContext::ShortTy,
5090 &ASTContext::UnsignedCharTy,
5091 &ASTContext::UnsignedShortTy,
5092 // End of integral types.
5093 // FIXME: What about complex?
5094 };
5095 return S.Context.*ArithmeticTypes[index];
5096 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005097
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005098 /// \brief Gets the canonical type resulting from the usual arithemetic
5099 /// converions for the given arithmetic types.
5100 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5101 // Accelerator table for performing the usual arithmetic conversions.
5102 // The rules are basically:
5103 // - if either is floating-point, use the wider floating-point
5104 // - if same signedness, use the higher rank
5105 // - if same size, use unsigned of the higher rank
5106 // - use the larger type
5107 // These rules, together with the axiom that higher ranks are
5108 // never smaller, are sufficient to precompute all of these results
5109 // *except* when dealing with signed types of higher rank.
5110 // (we could precompute SLL x UI for all known platforms, but it's
5111 // better not to make any assumptions).
5112 enum PromotedType {
5113 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5114 };
5115 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5116 [LastPromotedArithmeticType] = {
5117 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5118 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5119 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5120 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5121 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5122 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5123 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5124 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5125 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5126 };
5127
5128 assert(L < LastPromotedArithmeticType);
5129 assert(R < LastPromotedArithmeticType);
5130 int Idx = ConversionsTable[L][R];
5131
5132 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005133 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005134
5135 // Slow path: we need to compare widths.
5136 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005137 CanQualType LT = getArithmeticType(L),
5138 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005139 unsigned LW = S.Context.getIntWidth(LT),
5140 RW = S.Context.getIntWidth(RT);
5141
5142 // If they're different widths, use the signed type.
5143 if (LW > RW) return LT;
5144 else if (LW < RW) return RT;
5145
5146 // Otherwise, use the unsigned type of the signed type's rank.
5147 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5148 assert(L == SLL || R == SLL);
5149 return S.Context.UnsignedLongLongTy;
5150 }
5151
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005152 /// \brief Helper method to factor out the common pattern of adding overloads
5153 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005154 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5155 bool HasVolatile) {
5156 QualType ParamTypes[2] = {
5157 S.Context.getLValueReferenceType(CandidateTy),
5158 S.Context.IntTy
5159 };
5160
5161 // Non-volatile version.
5162 if (NumArgs == 1)
5163 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5164 else
5165 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5166
5167 // Use a heuristic to reduce number of builtin candidates in the set:
5168 // add volatile version only if there are conversions to a volatile type.
5169 if (HasVolatile) {
5170 ParamTypes[0] =
5171 S.Context.getLValueReferenceType(
5172 S.Context.getVolatileType(CandidateTy));
5173 if (NumArgs == 1)
5174 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5175 else
5176 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5177 }
5178 }
5179
5180public:
5181 BuiltinOperatorOverloadBuilder(
5182 Sema &S, Expr **Args, unsigned NumArgs,
5183 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005184 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005185 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5186 OverloadCandidateSet &CandidateSet)
5187 : S(S), Args(Args), NumArgs(NumArgs),
5188 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005189 HasArithmeticOrEnumeralCandidateType(
5190 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005191 CandidateTypes(CandidateTypes),
5192 CandidateSet(CandidateSet) {
5193 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005194 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005195 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005196 assert(getArithmeticType(LastPromotedIntegralType - 1)
5197 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005198 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005199 assert(getArithmeticType(FirstPromotedArithmeticType)
5200 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005201 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005202 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5203 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005204 "Invalid last promoted arithmetic type");
5205 }
5206
5207 // C++ [over.built]p3:
5208 //
5209 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5210 // is either volatile or empty, there exist candidate operator
5211 // functions of the form
5212 //
5213 // VQ T& operator++(VQ T&);
5214 // T operator++(VQ T&, int);
5215 //
5216 // C++ [over.built]p4:
5217 //
5218 // For every pair (T, VQ), where T is an arithmetic type other
5219 // than bool, and VQ is either volatile or empty, there exist
5220 // candidate operator functions of the form
5221 //
5222 // VQ T& operator--(VQ T&);
5223 // T operator--(VQ T&, int);
5224 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005225 if (!HasArithmeticOrEnumeralCandidateType)
5226 return;
5227
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005228 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5229 Arith < NumArithmeticTypes; ++Arith) {
5230 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005231 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005232 VisibleTypeConversionsQuals.hasVolatile());
5233 }
5234 }
5235
5236 // C++ [over.built]p5:
5237 //
5238 // For every pair (T, VQ), where T is a cv-qualified or
5239 // cv-unqualified object type, and VQ is either volatile or
5240 // empty, there exist candidate operator functions of the form
5241 //
5242 // T*VQ& operator++(T*VQ&);
5243 // T*VQ& operator--(T*VQ&);
5244 // T* operator++(T*VQ&, int);
5245 // T* operator--(T*VQ&, int);
5246 void addPlusPlusMinusMinusPointerOverloads() {
5247 for (BuiltinCandidateTypeSet::iterator
5248 Ptr = CandidateTypes[0].pointer_begin(),
5249 PtrEnd = CandidateTypes[0].pointer_end();
5250 Ptr != PtrEnd; ++Ptr) {
5251 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005252 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005253 continue;
5254
5255 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5256 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5257 VisibleTypeConversionsQuals.hasVolatile()));
5258 }
5259 }
5260
5261 // C++ [over.built]p6:
5262 // For every cv-qualified or cv-unqualified object type T, there
5263 // exist candidate operator functions of the form
5264 //
5265 // T& operator*(T*);
5266 //
5267 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005268 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005269 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005270 // T& operator*(T*);
5271 void addUnaryStarPointerOverloads() {
5272 for (BuiltinCandidateTypeSet::iterator
5273 Ptr = CandidateTypes[0].pointer_begin(),
5274 PtrEnd = CandidateTypes[0].pointer_end();
5275 Ptr != PtrEnd; ++Ptr) {
5276 QualType ParamTy = *Ptr;
5277 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005278 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5279 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005280
Douglas Gregor02824322011-01-26 19:30:28 +00005281 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5282 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5283 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005284
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005285 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5286 &ParamTy, Args, 1, CandidateSet);
5287 }
5288 }
5289
5290 // C++ [over.built]p9:
5291 // For every promoted arithmetic type T, there exist candidate
5292 // operator functions of the form
5293 //
5294 // T operator+(T);
5295 // T operator-(T);
5296 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005297 if (!HasArithmeticOrEnumeralCandidateType)
5298 return;
5299
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005300 for (unsigned Arith = FirstPromotedArithmeticType;
5301 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005302 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005303 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5304 }
5305
5306 // Extension: We also add these operators for vector types.
5307 for (BuiltinCandidateTypeSet::iterator
5308 Vec = CandidateTypes[0].vector_begin(),
5309 VecEnd = CandidateTypes[0].vector_end();
5310 Vec != VecEnd; ++Vec) {
5311 QualType VecTy = *Vec;
5312 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5313 }
5314 }
5315
5316 // C++ [over.built]p8:
5317 // For every type T, there exist candidate operator functions of
5318 // the form
5319 //
5320 // T* operator+(T*);
5321 void addUnaryPlusPointerOverloads() {
5322 for (BuiltinCandidateTypeSet::iterator
5323 Ptr = CandidateTypes[0].pointer_begin(),
5324 PtrEnd = CandidateTypes[0].pointer_end();
5325 Ptr != PtrEnd; ++Ptr) {
5326 QualType ParamTy = *Ptr;
5327 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5328 }
5329 }
5330
5331 // C++ [over.built]p10:
5332 // For every promoted integral type T, there exist candidate
5333 // operator functions of the form
5334 //
5335 // T operator~(T);
5336 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005337 if (!HasArithmeticOrEnumeralCandidateType)
5338 return;
5339
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005340 for (unsigned Int = FirstPromotedIntegralType;
5341 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005342 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005343 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5344 }
5345
5346 // Extension: We also add this operator for vector types.
5347 for (BuiltinCandidateTypeSet::iterator
5348 Vec = CandidateTypes[0].vector_begin(),
5349 VecEnd = CandidateTypes[0].vector_end();
5350 Vec != VecEnd; ++Vec) {
5351 QualType VecTy = *Vec;
5352 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5353 }
5354 }
5355
5356 // C++ [over.match.oper]p16:
5357 // For every pointer to member type T, there exist candidate operator
5358 // functions of the form
5359 //
5360 // bool operator==(T,T);
5361 // bool operator!=(T,T);
5362 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5363 /// Set of (canonical) types that we've already handled.
5364 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5365
5366 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5367 for (BuiltinCandidateTypeSet::iterator
5368 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5369 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5370 MemPtr != MemPtrEnd;
5371 ++MemPtr) {
5372 // Don't add the same builtin candidate twice.
5373 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5374 continue;
5375
5376 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5377 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5378 CandidateSet);
5379 }
5380 }
5381 }
5382
5383 // C++ [over.built]p15:
5384 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005385 // For every T, where T is an enumeration type, a pointer type, or
5386 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005387 //
5388 // bool operator<(T, T);
5389 // bool operator>(T, T);
5390 // bool operator<=(T, T);
5391 // bool operator>=(T, T);
5392 // bool operator==(T, T);
5393 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005394 void addRelationalPointerOrEnumeralOverloads() {
5395 // C++ [over.built]p1:
5396 // If there is a user-written candidate with the same name and parameter
5397 // types as a built-in candidate operator function, the built-in operator
5398 // function is hidden and is not included in the set of candidate
5399 // functions.
5400 //
5401 // The text is actually in a note, but if we don't implement it then we end
5402 // up with ambiguities when the user provides an overloaded operator for
5403 // an enumeration type. Note that only enumeration types have this problem,
5404 // so we track which enumeration types we've seen operators for. Also, the
5405 // only other overloaded operator with enumeration argumenst, operator=,
5406 // cannot be overloaded for enumeration types, so this is the only place
5407 // where we must suppress candidates like this.
5408 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5409 UserDefinedBinaryOperators;
5410
5411 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5412 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5413 CandidateTypes[ArgIdx].enumeration_end()) {
5414 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5415 CEnd = CandidateSet.end();
5416 C != CEnd; ++C) {
5417 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5418 continue;
5419
5420 QualType FirstParamType =
5421 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5422 QualType SecondParamType =
5423 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5424
5425 // Skip if either parameter isn't of enumeral type.
5426 if (!FirstParamType->isEnumeralType() ||
5427 !SecondParamType->isEnumeralType())
5428 continue;
5429
5430 // Add this operator to the set of known user-defined operators.
5431 UserDefinedBinaryOperators.insert(
5432 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5433 S.Context.getCanonicalType(SecondParamType)));
5434 }
5435 }
5436 }
5437
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005438 /// Set of (canonical) types that we've already handled.
5439 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5440
5441 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5442 for (BuiltinCandidateTypeSet::iterator
5443 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5444 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5445 Ptr != PtrEnd; ++Ptr) {
5446 // Don't add the same builtin candidate twice.
5447 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5448 continue;
5449
5450 QualType ParamTypes[2] = { *Ptr, *Ptr };
5451 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5452 CandidateSet);
5453 }
5454 for (BuiltinCandidateTypeSet::iterator
5455 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5456 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5457 Enum != EnumEnd; ++Enum) {
5458 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5459
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005460 // Don't add the same builtin candidate twice, or if a user defined
5461 // candidate exists.
5462 if (!AddedTypes.insert(CanonType) ||
5463 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5464 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005465 continue;
5466
5467 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005468 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5469 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005470 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005471
5472 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5473 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5474 if (AddedTypes.insert(NullPtrTy) &&
5475 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5476 NullPtrTy))) {
5477 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5478 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5479 CandidateSet);
5480 }
5481 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005482 }
5483 }
5484
5485 // C++ [over.built]p13:
5486 //
5487 // For every cv-qualified or cv-unqualified object type T
5488 // there exist candidate operator functions of the form
5489 //
5490 // T* operator+(T*, ptrdiff_t);
5491 // T& operator[](T*, ptrdiff_t); [BELOW]
5492 // T* operator-(T*, ptrdiff_t);
5493 // T* operator+(ptrdiff_t, T*);
5494 // T& operator[](ptrdiff_t, T*); [BELOW]
5495 //
5496 // C++ [over.built]p14:
5497 //
5498 // For every T, where T is a pointer to object type, there
5499 // exist candidate operator functions of the form
5500 //
5501 // ptrdiff_t operator-(T, T);
5502 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5503 /// Set of (canonical) types that we've already handled.
5504 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5505
5506 for (int Arg = 0; Arg < 2; ++Arg) {
5507 QualType AsymetricParamTypes[2] = {
5508 S.Context.getPointerDiffType(),
5509 S.Context.getPointerDiffType(),
5510 };
5511 for (BuiltinCandidateTypeSet::iterator
5512 Ptr = CandidateTypes[Arg].pointer_begin(),
5513 PtrEnd = CandidateTypes[Arg].pointer_end();
5514 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005515 QualType PointeeTy = (*Ptr)->getPointeeType();
5516 if (!PointeeTy->isObjectType())
5517 continue;
5518
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005519 AsymetricParamTypes[Arg] = *Ptr;
5520 if (Arg == 0 || Op == OO_Plus) {
5521 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5522 // T* operator+(ptrdiff_t, T*);
5523 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5524 CandidateSet);
5525 }
5526 if (Op == OO_Minus) {
5527 // ptrdiff_t operator-(T, T);
5528 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5529 continue;
5530
5531 QualType ParamTypes[2] = { *Ptr, *Ptr };
5532 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5533 Args, 2, CandidateSet);
5534 }
5535 }
5536 }
5537 }
5538
5539 // C++ [over.built]p12:
5540 //
5541 // For every pair of promoted arithmetic types L and R, there
5542 // exist candidate operator functions of the form
5543 //
5544 // LR operator*(L, R);
5545 // LR operator/(L, R);
5546 // LR operator+(L, R);
5547 // LR operator-(L, R);
5548 // bool operator<(L, R);
5549 // bool operator>(L, R);
5550 // bool operator<=(L, R);
5551 // bool operator>=(L, R);
5552 // bool operator==(L, R);
5553 // bool operator!=(L, R);
5554 //
5555 // where LR is the result of the usual arithmetic conversions
5556 // between types L and R.
5557 //
5558 // C++ [over.built]p24:
5559 //
5560 // For every pair of promoted arithmetic types L and R, there exist
5561 // candidate operator functions of the form
5562 //
5563 // LR operator?(bool, L, R);
5564 //
5565 // where LR is the result of the usual arithmetic conversions
5566 // between types L and R.
5567 // Our candidates ignore the first parameter.
5568 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005569 if (!HasArithmeticOrEnumeralCandidateType)
5570 return;
5571
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005572 for (unsigned Left = FirstPromotedArithmeticType;
5573 Left < LastPromotedArithmeticType; ++Left) {
5574 for (unsigned Right = FirstPromotedArithmeticType;
5575 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005576 QualType LandR[2] = { getArithmeticType(Left),
5577 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005578 QualType Result =
5579 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005580 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005581 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5582 }
5583 }
5584
5585 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5586 // conditional operator for vector types.
5587 for (BuiltinCandidateTypeSet::iterator
5588 Vec1 = CandidateTypes[0].vector_begin(),
5589 Vec1End = CandidateTypes[0].vector_end();
5590 Vec1 != Vec1End; ++Vec1) {
5591 for (BuiltinCandidateTypeSet::iterator
5592 Vec2 = CandidateTypes[1].vector_begin(),
5593 Vec2End = CandidateTypes[1].vector_end();
5594 Vec2 != Vec2End; ++Vec2) {
5595 QualType LandR[2] = { *Vec1, *Vec2 };
5596 QualType Result = S.Context.BoolTy;
5597 if (!isComparison) {
5598 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5599 Result = *Vec1;
5600 else
5601 Result = *Vec2;
5602 }
5603
5604 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5605 }
5606 }
5607 }
5608
5609 // C++ [over.built]p17:
5610 //
5611 // For every pair of promoted integral types L and R, there
5612 // exist candidate operator functions of the form
5613 //
5614 // LR operator%(L, R);
5615 // LR operator&(L, R);
5616 // LR operator^(L, R);
5617 // LR operator|(L, R);
5618 // L operator<<(L, R);
5619 // L operator>>(L, R);
5620 //
5621 // where LR is the result of the usual arithmetic conversions
5622 // between types L and R.
5623 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005624 if (!HasArithmeticOrEnumeralCandidateType)
5625 return;
5626
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005627 for (unsigned Left = FirstPromotedIntegralType;
5628 Left < LastPromotedIntegralType; ++Left) {
5629 for (unsigned Right = FirstPromotedIntegralType;
5630 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005631 QualType LandR[2] = { getArithmeticType(Left),
5632 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005633 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5634 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005635 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005636 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5637 }
5638 }
5639 }
5640
5641 // C++ [over.built]p20:
5642 //
5643 // For every pair (T, VQ), where T is an enumeration or
5644 // pointer to member type and VQ is either volatile or
5645 // empty, there exist candidate operator functions of the form
5646 //
5647 // VQ T& operator=(VQ T&, T);
5648 void addAssignmentMemberPointerOrEnumeralOverloads() {
5649 /// Set of (canonical) types that we've already handled.
5650 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5651
5652 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5653 for (BuiltinCandidateTypeSet::iterator
5654 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5655 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5656 Enum != EnumEnd; ++Enum) {
5657 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5658 continue;
5659
5660 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5661 CandidateSet);
5662 }
5663
5664 for (BuiltinCandidateTypeSet::iterator
5665 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5666 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5667 MemPtr != MemPtrEnd; ++MemPtr) {
5668 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5669 continue;
5670
5671 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5672 CandidateSet);
5673 }
5674 }
5675 }
5676
5677 // C++ [over.built]p19:
5678 //
5679 // For every pair (T, VQ), where T is any type and VQ is either
5680 // volatile or empty, there exist candidate operator functions
5681 // of the form
5682 //
5683 // T*VQ& operator=(T*VQ&, T*);
5684 //
5685 // C++ [over.built]p21:
5686 //
5687 // For every pair (T, VQ), where T is a cv-qualified or
5688 // cv-unqualified object type and VQ is either volatile or
5689 // empty, there exist candidate operator functions of the form
5690 //
5691 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5692 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5693 void addAssignmentPointerOverloads(bool isEqualOp) {
5694 /// Set of (canonical) types that we've already handled.
5695 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5696
5697 for (BuiltinCandidateTypeSet::iterator
5698 Ptr = CandidateTypes[0].pointer_begin(),
5699 PtrEnd = CandidateTypes[0].pointer_end();
5700 Ptr != PtrEnd; ++Ptr) {
5701 // If this is operator=, keep track of the builtin candidates we added.
5702 if (isEqualOp)
5703 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005704 else if (!(*Ptr)->getPointeeType()->isObjectType())
5705 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005706
5707 // non-volatile version
5708 QualType ParamTypes[2] = {
5709 S.Context.getLValueReferenceType(*Ptr),
5710 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5711 };
5712 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5713 /*IsAssigmentOperator=*/ isEqualOp);
5714
5715 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5716 VisibleTypeConversionsQuals.hasVolatile()) {
5717 // volatile version
5718 ParamTypes[0] =
5719 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5720 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5721 /*IsAssigmentOperator=*/isEqualOp);
5722 }
5723 }
5724
5725 if (isEqualOp) {
5726 for (BuiltinCandidateTypeSet::iterator
5727 Ptr = CandidateTypes[1].pointer_begin(),
5728 PtrEnd = CandidateTypes[1].pointer_end();
5729 Ptr != PtrEnd; ++Ptr) {
5730 // Make sure we don't add the same candidate twice.
5731 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5732 continue;
5733
Chandler Carruth8e543b32010-12-12 08:17:55 +00005734 QualType ParamTypes[2] = {
5735 S.Context.getLValueReferenceType(*Ptr),
5736 *Ptr,
5737 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005738
5739 // non-volatile version
5740 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5741 /*IsAssigmentOperator=*/true);
5742
5743 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5744 VisibleTypeConversionsQuals.hasVolatile()) {
5745 // volatile version
5746 ParamTypes[0] =
5747 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005748 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5749 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005750 }
5751 }
5752 }
5753 }
5754
5755 // C++ [over.built]p18:
5756 //
5757 // For every triple (L, VQ, R), where L is an arithmetic type,
5758 // VQ is either volatile or empty, and R is a promoted
5759 // arithmetic type, there exist candidate operator functions of
5760 // the form
5761 //
5762 // VQ L& operator=(VQ L&, R);
5763 // VQ L& operator*=(VQ L&, R);
5764 // VQ L& operator/=(VQ L&, R);
5765 // VQ L& operator+=(VQ L&, R);
5766 // VQ L& operator-=(VQ L&, R);
5767 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005768 if (!HasArithmeticOrEnumeralCandidateType)
5769 return;
5770
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005771 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5772 for (unsigned Right = FirstPromotedArithmeticType;
5773 Right < LastPromotedArithmeticType; ++Right) {
5774 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005775 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005776
5777 // Add this built-in operator as a candidate (VQ is empty).
5778 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005779 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005780 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5781 /*IsAssigmentOperator=*/isEqualOp);
5782
5783 // Add this built-in operator as a candidate (VQ is 'volatile').
5784 if (VisibleTypeConversionsQuals.hasVolatile()) {
5785 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005786 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005787 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005788 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5789 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005790 /*IsAssigmentOperator=*/isEqualOp);
5791 }
5792 }
5793 }
5794
5795 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5796 for (BuiltinCandidateTypeSet::iterator
5797 Vec1 = CandidateTypes[0].vector_begin(),
5798 Vec1End = CandidateTypes[0].vector_end();
5799 Vec1 != Vec1End; ++Vec1) {
5800 for (BuiltinCandidateTypeSet::iterator
5801 Vec2 = CandidateTypes[1].vector_begin(),
5802 Vec2End = CandidateTypes[1].vector_end();
5803 Vec2 != Vec2End; ++Vec2) {
5804 QualType ParamTypes[2];
5805 ParamTypes[1] = *Vec2;
5806 // Add this built-in operator as a candidate (VQ is empty).
5807 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5808 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5809 /*IsAssigmentOperator=*/isEqualOp);
5810
5811 // Add this built-in operator as a candidate (VQ is 'volatile').
5812 if (VisibleTypeConversionsQuals.hasVolatile()) {
5813 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5814 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005815 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5816 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005817 /*IsAssigmentOperator=*/isEqualOp);
5818 }
5819 }
5820 }
5821 }
5822
5823 // C++ [over.built]p22:
5824 //
5825 // For every triple (L, VQ, R), where L is an integral type, VQ
5826 // is either volatile or empty, and R is a promoted integral
5827 // type, there exist candidate operator functions of the form
5828 //
5829 // VQ L& operator%=(VQ L&, R);
5830 // VQ L& operator<<=(VQ L&, R);
5831 // VQ L& operator>>=(VQ L&, R);
5832 // VQ L& operator&=(VQ L&, R);
5833 // VQ L& operator^=(VQ L&, R);
5834 // VQ L& operator|=(VQ L&, R);
5835 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005836 if (!HasArithmeticOrEnumeralCandidateType)
5837 return;
5838
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005839 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5840 for (unsigned Right = FirstPromotedIntegralType;
5841 Right < LastPromotedIntegralType; ++Right) {
5842 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005843 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005844
5845 // Add this built-in operator as a candidate (VQ is empty).
5846 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005847 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005848 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5849 if (VisibleTypeConversionsQuals.hasVolatile()) {
5850 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005851 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005852 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5853 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5854 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5855 CandidateSet);
5856 }
5857 }
5858 }
5859 }
5860
5861 // C++ [over.operator]p23:
5862 //
5863 // There also exist candidate operator functions of the form
5864 //
5865 // bool operator!(bool);
5866 // bool operator&&(bool, bool);
5867 // bool operator||(bool, bool);
5868 void addExclaimOverload() {
5869 QualType ParamTy = S.Context.BoolTy;
5870 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5871 /*IsAssignmentOperator=*/false,
5872 /*NumContextualBoolArguments=*/1);
5873 }
5874 void addAmpAmpOrPipePipeOverload() {
5875 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5876 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5877 /*IsAssignmentOperator=*/false,
5878 /*NumContextualBoolArguments=*/2);
5879 }
5880
5881 // C++ [over.built]p13:
5882 //
5883 // For every cv-qualified or cv-unqualified object type T there
5884 // exist candidate operator functions of the form
5885 //
5886 // T* operator+(T*, ptrdiff_t); [ABOVE]
5887 // T& operator[](T*, ptrdiff_t);
5888 // T* operator-(T*, ptrdiff_t); [ABOVE]
5889 // T* operator+(ptrdiff_t, T*); [ABOVE]
5890 // T& operator[](ptrdiff_t, T*);
5891 void addSubscriptOverloads() {
5892 for (BuiltinCandidateTypeSet::iterator
5893 Ptr = CandidateTypes[0].pointer_begin(),
5894 PtrEnd = CandidateTypes[0].pointer_end();
5895 Ptr != PtrEnd; ++Ptr) {
5896 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5897 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005898 if (!PointeeType->isObjectType())
5899 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005900
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005901 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5902
5903 // T& operator[](T*, ptrdiff_t)
5904 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5905 }
5906
5907 for (BuiltinCandidateTypeSet::iterator
5908 Ptr = CandidateTypes[1].pointer_begin(),
5909 PtrEnd = CandidateTypes[1].pointer_end();
5910 Ptr != PtrEnd; ++Ptr) {
5911 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5912 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005913 if (!PointeeType->isObjectType())
5914 continue;
5915
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005916 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5917
5918 // T& operator[](ptrdiff_t, T*)
5919 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5920 }
5921 }
5922
5923 // C++ [over.built]p11:
5924 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5925 // C1 is the same type as C2 or is a derived class of C2, T is an object
5926 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5927 // there exist candidate operator functions of the form
5928 //
5929 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5930 //
5931 // where CV12 is the union of CV1 and CV2.
5932 void addArrowStarOverloads() {
5933 for (BuiltinCandidateTypeSet::iterator
5934 Ptr = CandidateTypes[0].pointer_begin(),
5935 PtrEnd = CandidateTypes[0].pointer_end();
5936 Ptr != PtrEnd; ++Ptr) {
5937 QualType C1Ty = (*Ptr);
5938 QualType C1;
5939 QualifierCollector Q1;
5940 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5941 if (!isa<RecordType>(C1))
5942 continue;
5943 // heuristic to reduce number of builtin candidates in the set.
5944 // Add volatile/restrict version only if there are conversions to a
5945 // volatile/restrict type.
5946 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5947 continue;
5948 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5949 continue;
5950 for (BuiltinCandidateTypeSet::iterator
5951 MemPtr = CandidateTypes[1].member_pointer_begin(),
5952 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5953 MemPtr != MemPtrEnd; ++MemPtr) {
5954 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5955 QualType C2 = QualType(mptr->getClass(), 0);
5956 C2 = C2.getUnqualifiedType();
5957 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5958 break;
5959 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5960 // build CV12 T&
5961 QualType T = mptr->getPointeeType();
5962 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5963 T.isVolatileQualified())
5964 continue;
5965 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5966 T.isRestrictQualified())
5967 continue;
5968 T = Q1.apply(S.Context, T);
5969 QualType ResultTy = S.Context.getLValueReferenceType(T);
5970 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5971 }
5972 }
5973 }
5974
5975 // Note that we don't consider the first argument, since it has been
5976 // contextually converted to bool long ago. The candidates below are
5977 // therefore added as binary.
5978 //
5979 // C++ [over.built]p25:
5980 // For every type T, where T is a pointer, pointer-to-member, or scoped
5981 // enumeration type, there exist candidate operator functions of the form
5982 //
5983 // T operator?(bool, T, T);
5984 //
5985 void addConditionalOperatorOverloads() {
5986 /// Set of (canonical) types that we've already handled.
5987 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5988
5989 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5990 for (BuiltinCandidateTypeSet::iterator
5991 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5992 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5993 Ptr != PtrEnd; ++Ptr) {
5994 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5995 continue;
5996
5997 QualType ParamTypes[2] = { *Ptr, *Ptr };
5998 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5999 }
6000
6001 for (BuiltinCandidateTypeSet::iterator
6002 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6003 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6004 MemPtr != MemPtrEnd; ++MemPtr) {
6005 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6006 continue;
6007
6008 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6009 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6010 }
6011
6012 if (S.getLangOptions().CPlusPlus0x) {
6013 for (BuiltinCandidateTypeSet::iterator
6014 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6015 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6016 Enum != EnumEnd; ++Enum) {
6017 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6018 continue;
6019
6020 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6021 continue;
6022
6023 QualType ParamTypes[2] = { *Enum, *Enum };
6024 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6025 }
6026 }
6027 }
6028 }
6029};
6030
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006031} // end anonymous namespace
6032
6033/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6034/// operator overloads to the candidate set (C++ [over.built]), based
6035/// on the operator @p Op and the arguments given. For example, if the
6036/// operator is a binary '+', this routine might add "int
6037/// operator+(int, int)" to cover integer addition.
6038void
6039Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6040 SourceLocation OpLoc,
6041 Expr **Args, unsigned NumArgs,
6042 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006043 // Find all of the types that the arguments can convert to, but only
6044 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006045 // that make use of these types. Also record whether we encounter non-record
6046 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006047 Qualifiers VisibleTypeConversionsQuals;
6048 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006049 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6050 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006051
6052 bool HasNonRecordCandidateType = false;
6053 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006054 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
6055 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6056 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6057 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6058 OpLoc,
6059 true,
6060 (Op == OO_Exclaim ||
6061 Op == OO_AmpAmp ||
6062 Op == OO_PipePipe),
6063 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006064 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6065 CandidateTypes[ArgIdx].hasNonRecordTypes();
6066 HasArithmeticOrEnumeralCandidateType =
6067 HasArithmeticOrEnumeralCandidateType ||
6068 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006069 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006070
Chandler Carruth00a38332010-12-13 01:44:01 +00006071 // Exit early when no non-record types have been added to the candidate set
6072 // for any of the arguments to the operator.
6073 if (!HasNonRecordCandidateType)
6074 return;
6075
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006076 // Setup an object to manage the common state for building overloads.
6077 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6078 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006079 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006080 CandidateTypes, CandidateSet);
6081
6082 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006083 switch (Op) {
6084 case OO_None:
6085 case NUM_OVERLOADED_OPERATORS:
6086 assert(false && "Expected an overloaded operator");
6087 break;
6088
Chandler Carruth5184de02010-12-12 08:51:33 +00006089 case OO_New:
6090 case OO_Delete:
6091 case OO_Array_New:
6092 case OO_Array_Delete:
6093 case OO_Call:
6094 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6095 break;
6096
6097 case OO_Comma:
6098 case OO_Arrow:
6099 // C++ [over.match.oper]p3:
6100 // -- For the operator ',', the unary operator '&', or the
6101 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006102 break;
6103
6104 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006105 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006106 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006107 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006108
6109 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006110 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006111 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006112 } else {
6113 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6114 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6115 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006116 break;
6117
Chandler Carruth5184de02010-12-12 08:51:33 +00006118 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006119 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006120 OpBuilder.addUnaryStarPointerOverloads();
6121 else
6122 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6123 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006124
Chandler Carruth5184de02010-12-12 08:51:33 +00006125 case OO_Slash:
6126 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006127 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006128
6129 case OO_PlusPlus:
6130 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006131 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6132 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006133 break;
6134
Douglas Gregor84605ae2009-08-24 13:43:27 +00006135 case OO_EqualEqual:
6136 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006137 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006138 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006139
Douglas Gregora11693b2008-11-12 17:17:38 +00006140 case OO_Less:
6141 case OO_Greater:
6142 case OO_LessEqual:
6143 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006144 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006145 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6146 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006147
Douglas Gregora11693b2008-11-12 17:17:38 +00006148 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006149 case OO_Caret:
6150 case OO_Pipe:
6151 case OO_LessLess:
6152 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006153 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006154 break;
6155
Chandler Carruth5184de02010-12-12 08:51:33 +00006156 case OO_Amp: // '&' is either unary or binary
6157 if (NumArgs == 1)
6158 // C++ [over.match.oper]p3:
6159 // -- For the operator ',', the unary operator '&', or the
6160 // operator '->', the built-in candidates set is empty.
6161 break;
6162
6163 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6164 break;
6165
6166 case OO_Tilde:
6167 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6168 break;
6169
Douglas Gregora11693b2008-11-12 17:17:38 +00006170 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006171 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006172 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006173
6174 case OO_PlusEqual:
6175 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006176 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006177 // Fall through.
6178
6179 case OO_StarEqual:
6180 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006181 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006182 break;
6183
6184 case OO_PercentEqual:
6185 case OO_LessLessEqual:
6186 case OO_GreaterGreaterEqual:
6187 case OO_AmpEqual:
6188 case OO_CaretEqual:
6189 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006190 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006191 break;
6192
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006193 case OO_Exclaim:
6194 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006195 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006196
Douglas Gregora11693b2008-11-12 17:17:38 +00006197 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006198 case OO_PipePipe:
6199 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006200 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006201
6202 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006203 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006204 break;
6205
6206 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006207 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006208 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006209
6210 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006211 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006212 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6213 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006214 }
6215}
6216
Douglas Gregore254f902009-02-04 00:32:51 +00006217/// \brief Add function candidates found via argument-dependent lookup
6218/// to the set of overloading candidates.
6219///
6220/// This routine performs argument-dependent name lookup based on the
6221/// given function name (which may also be an operator name) and adds
6222/// all of the overload candidates found by ADL to the overload
6223/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006224void
Douglas Gregore254f902009-02-04 00:32:51 +00006225Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006226 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006227 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006228 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006229 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006230 bool PartialOverloading,
6231 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006232 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006233
John McCall91f61fc2010-01-26 06:04:06 +00006234 // FIXME: This approach for uniquing ADL results (and removing
6235 // redundant candidates from the set) relies on pointer-equality,
6236 // which means we need to key off the canonical decl. However,
6237 // always going back to the canonical decl might not get us the
6238 // right set of default arguments. What default arguments are
6239 // we supposed to consider on ADL candidates, anyway?
6240
Douglas Gregorcabea402009-09-22 15:41:20 +00006241 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006242 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6243 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006244
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006245 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006246 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6247 CandEnd = CandidateSet.end();
6248 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006249 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006250 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006251 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006252 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006253 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006254
6255 // For each of the ADL candidates we found, add it to the overload
6256 // set.
John McCall8fe68082010-01-26 07:16:45 +00006257 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006258 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006259 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006260 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006261 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006262
John McCalla0296f72010-03-19 07:35:19 +00006263 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006264 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006265 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006266 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006267 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006268 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006269 }
Douglas Gregore254f902009-02-04 00:32:51 +00006270}
6271
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006272/// isBetterOverloadCandidate - Determines whether the first overload
6273/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006274bool
John McCall5c32be02010-08-24 20:38:10 +00006275isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006276 const OverloadCandidate &Cand1,
6277 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006278 SourceLocation Loc,
6279 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006280 // Define viable functions to be better candidates than non-viable
6281 // functions.
6282 if (!Cand2.Viable)
6283 return Cand1.Viable;
6284 else if (!Cand1.Viable)
6285 return false;
6286
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006287 // C++ [over.match.best]p1:
6288 //
6289 // -- if F is a static member function, ICS1(F) is defined such
6290 // that ICS1(F) is neither better nor worse than ICS1(G) for
6291 // any function G, and, symmetrically, ICS1(G) is neither
6292 // better nor worse than ICS1(F).
6293 unsigned StartArg = 0;
6294 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6295 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006296
Douglas Gregord3cb3562009-07-07 23:38:56 +00006297 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006298 // A viable function F1 is defined to be a better function than another
6299 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006300 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006301 unsigned NumArgs = Cand1.Conversions.size();
6302 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6303 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006304 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006305 switch (CompareImplicitConversionSequences(S,
6306 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006307 Cand2.Conversions[ArgIdx])) {
6308 case ImplicitConversionSequence::Better:
6309 // Cand1 has a better conversion sequence.
6310 HasBetterConversion = true;
6311 break;
6312
6313 case ImplicitConversionSequence::Worse:
6314 // Cand1 can't be better than Cand2.
6315 return false;
6316
6317 case ImplicitConversionSequence::Indistinguishable:
6318 // Do nothing.
6319 break;
6320 }
6321 }
6322
Mike Stump11289f42009-09-09 15:08:12 +00006323 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006324 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006325 if (HasBetterConversion)
6326 return true;
6327
Mike Stump11289f42009-09-09 15:08:12 +00006328 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006329 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006330 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006331 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6332 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006333
6334 // -- F1 and F2 are function template specializations, and the function
6335 // template for F1 is more specialized than the template for F2
6336 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006337 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006338 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006339 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006340 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006341 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6342 Cand2.Function->getPrimaryTemplate(),
6343 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006344 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006345 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006346 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006347 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006348 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006349
Douglas Gregora1f013e2008-11-07 22:36:19 +00006350 // -- the context is an initialization by user-defined conversion
6351 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6352 // from the return type of F1 to the destination type (i.e.,
6353 // the type of the entity being initialized) is a better
6354 // conversion sequence than the standard conversion sequence
6355 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006356 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006357 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006358 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006359 switch (CompareStandardConversionSequences(S,
6360 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006361 Cand2.FinalConversion)) {
6362 case ImplicitConversionSequence::Better:
6363 // Cand1 has a better conversion sequence.
6364 return true;
6365
6366 case ImplicitConversionSequence::Worse:
6367 // Cand1 can't be better than Cand2.
6368 return false;
6369
6370 case ImplicitConversionSequence::Indistinguishable:
6371 // Do nothing
6372 break;
6373 }
6374 }
6375
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006376 return false;
6377}
6378
Mike Stump11289f42009-09-09 15:08:12 +00006379/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006380/// within an overload candidate set.
6381///
6382/// \param CandidateSet the set of candidate functions.
6383///
6384/// \param Loc the location of the function name (or operator symbol) for
6385/// which overload resolution occurs.
6386///
Mike Stump11289f42009-09-09 15:08:12 +00006387/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006388/// function, Best points to the candidate function found.
6389///
6390/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006391OverloadingResult
6392OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006393 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006394 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006395 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006396 Best = end();
6397 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6398 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006399 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006400 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006401 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006402 }
6403
6404 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006405 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006406 return OR_No_Viable_Function;
6407
6408 // Make sure that this function is better than every other viable
6409 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006410 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006411 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006412 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006413 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006414 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006415 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006416 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006417 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006418 }
Mike Stump11289f42009-09-09 15:08:12 +00006419
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006420 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006421 if (Best->Function &&
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006422 (Best->Function->isDeleted() || Best->Function->isUnavailable()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006423 return OR_Deleted;
6424
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006425 return OR_Success;
6426}
6427
John McCall53262c92010-01-12 02:15:36 +00006428namespace {
6429
6430enum OverloadCandidateKind {
6431 oc_function,
6432 oc_method,
6433 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006434 oc_function_template,
6435 oc_method_template,
6436 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006437 oc_implicit_default_constructor,
6438 oc_implicit_copy_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006439 oc_implicit_copy_assignment,
6440 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006441};
6442
John McCalle1ac8d12010-01-13 00:25:19 +00006443OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6444 FunctionDecl *Fn,
6445 std::string &Description) {
6446 bool isTemplate = false;
6447
6448 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6449 isTemplate = true;
6450 Description = S.getTemplateArgumentBindingsText(
6451 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6452 }
John McCallfd0b2f82010-01-06 09:43:14 +00006453
6454 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006455 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006456 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006457
Sebastian Redl08905022011-02-05 19:23:19 +00006458 if (Ctor->getInheritedConstructor())
6459 return oc_implicit_inherited_constructor;
6460
John McCall53262c92010-01-12 02:15:36 +00006461 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6462 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006463 }
6464
6465 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6466 // This actually gets spelled 'candidate function' for now, but
6467 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006468 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006469 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006470
Douglas Gregorec3bec02010-09-27 22:37:28 +00006471 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006472 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006473 return oc_implicit_copy_assignment;
6474 }
6475
John McCalle1ac8d12010-01-13 00:25:19 +00006476 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006477}
6478
Sebastian Redl08905022011-02-05 19:23:19 +00006479void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6480 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6481 if (!Ctor) return;
6482
6483 Ctor = Ctor->getInheritedConstructor();
6484 if (!Ctor) return;
6485
6486 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6487}
6488
John McCall53262c92010-01-12 02:15:36 +00006489} // end anonymous namespace
6490
6491// Notes the location of an overload candidate.
6492void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006493 std::string FnDesc;
6494 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6495 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6496 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006497 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006498}
6499
Douglas Gregorb491ed32011-02-19 21:32:49 +00006500//Notes the location of all overload candidates designated through
6501// OverloadedExpr
6502void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6503 assert(OverloadedExpr->getType() == Context.OverloadTy);
6504
6505 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6506 OverloadExpr *OvlExpr = Ovl.Expression;
6507
6508 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6509 IEnd = OvlExpr->decls_end();
6510 I != IEnd; ++I) {
6511 if (FunctionTemplateDecl *FunTmpl =
6512 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6513 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6514 } else if (FunctionDecl *Fun
6515 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6516 NoteOverloadCandidate(Fun);
6517 }
6518 }
6519}
6520
John McCall0d1da222010-01-12 00:44:57 +00006521/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6522/// "lead" diagnostic; it will be given two arguments, the source and
6523/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006524void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6525 Sema &S,
6526 SourceLocation CaretLoc,
6527 const PartialDiagnostic &PDiag) const {
6528 S.Diag(CaretLoc, PDiag)
6529 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006530 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006531 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6532 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006533 }
John McCall12f97bc2010-01-08 04:41:39 +00006534}
6535
John McCall0d1da222010-01-12 00:44:57 +00006536namespace {
6537
John McCall6a61b522010-01-13 09:16:55 +00006538void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6539 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6540 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006541 assert(Cand->Function && "for now, candidate must be a function");
6542 FunctionDecl *Fn = Cand->Function;
6543
6544 // There's a conversion slot for the object argument if this is a
6545 // non-constructor method. Note that 'I' corresponds the
6546 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006547 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006548 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006549 if (I == 0)
6550 isObjectArgument = true;
6551 else
6552 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006553 }
6554
John McCalle1ac8d12010-01-13 00:25:19 +00006555 std::string FnDesc;
6556 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6557
John McCall6a61b522010-01-13 09:16:55 +00006558 Expr *FromExpr = Conv.Bad.FromExpr;
6559 QualType FromTy = Conv.Bad.getFromType();
6560 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006561
John McCallfb7ad0f2010-02-02 02:42:52 +00006562 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006563 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006564 Expr *E = FromExpr->IgnoreParens();
6565 if (isa<UnaryOperator>(E))
6566 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006567 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006568
6569 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6570 << (unsigned) FnKind << FnDesc
6571 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6572 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006573 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006574 return;
6575 }
6576
John McCall6d174642010-01-23 08:10:49 +00006577 // Do some hand-waving analysis to see if the non-viability is due
6578 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006579 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6580 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6581 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6582 CToTy = RT->getPointeeType();
6583 else {
6584 // TODO: detect and diagnose the full richness of const mismatches.
6585 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6586 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6587 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6588 }
6589
6590 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6591 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6592 // It is dumb that we have to do this here.
6593 while (isa<ArrayType>(CFromTy))
6594 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6595 while (isa<ArrayType>(CToTy))
6596 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6597
6598 Qualifiers FromQs = CFromTy.getQualifiers();
6599 Qualifiers ToQs = CToTy.getQualifiers();
6600
6601 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6602 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6603 << (unsigned) FnKind << FnDesc
6604 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6605 << FromTy
6606 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6607 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006608 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006609 return;
6610 }
6611
Douglas Gregoraec25842011-04-26 23:16:46 +00006612 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6613 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6614 << (unsigned) FnKind << FnDesc
6615 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6616 << FromTy
6617 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6618 << (unsigned) isObjectArgument << I+1;
6619 MaybeEmitInheritedConstructorNote(S, Fn);
6620 return;
6621 }
6622
John McCall47000992010-01-14 03:28:57 +00006623 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6624 assert(CVR && "unexpected qualifiers mismatch");
6625
6626 if (isObjectArgument) {
6627 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6628 << (unsigned) FnKind << FnDesc
6629 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6630 << FromTy << (CVR - 1);
6631 } else {
6632 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6633 << (unsigned) FnKind << FnDesc
6634 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6635 << FromTy << (CVR - 1) << I+1;
6636 }
Sebastian Redl08905022011-02-05 19:23:19 +00006637 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006638 return;
6639 }
6640
John McCall6d174642010-01-23 08:10:49 +00006641 // Diagnose references or pointers to incomplete types differently,
6642 // since it's far from impossible that the incompleteness triggered
6643 // the failure.
6644 QualType TempFromTy = FromTy.getNonReferenceType();
6645 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6646 TempFromTy = PTy->getPointeeType();
6647 if (TempFromTy->isIncompleteType()) {
6648 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6649 << (unsigned) FnKind << FnDesc
6650 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6651 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006652 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006653 return;
6654 }
6655
Douglas Gregor56f2e342010-06-30 23:01:39 +00006656 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006657 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006658 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6659 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6660 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6661 FromPtrTy->getPointeeType()) &&
6662 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6663 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006664 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006665 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006666 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006667 }
6668 } else if (const ObjCObjectPointerType *FromPtrTy
6669 = FromTy->getAs<ObjCObjectPointerType>()) {
6670 if (const ObjCObjectPointerType *ToPtrTy
6671 = ToTy->getAs<ObjCObjectPointerType>())
6672 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6673 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6674 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6675 FromPtrTy->getPointeeType()) &&
6676 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006677 BaseToDerivedConversion = 2;
6678 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6679 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6680 !FromTy->isIncompleteType() &&
6681 !ToRefTy->getPointeeType()->isIncompleteType() &&
6682 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6683 BaseToDerivedConversion = 3;
6684 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006685
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006686 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006687 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006688 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006689 << (unsigned) FnKind << FnDesc
6690 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006691 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006692 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006693 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006694 return;
6695 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006696
John McCall47000992010-01-14 03:28:57 +00006697 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006698 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6699 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006700 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006701 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006702 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006703}
6704
6705void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6706 unsigned NumFormalArgs) {
6707 // TODO: treat calls to a missing default constructor as a special case
6708
6709 FunctionDecl *Fn = Cand->Function;
6710 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6711
6712 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006713
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00006714 // With invalid overloaded operators, it's possible that we think we
6715 // have an arity mismatch when it fact it looks like we have the
6716 // right number of arguments, because only overloaded operators have
6717 // the weird behavior of overloading member and non-member functions.
6718 // Just don't report anything.
6719 if (Fn->isInvalidDecl() &&
6720 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6721 return;
6722
John McCall6a61b522010-01-13 09:16:55 +00006723 // at least / at most / exactly
6724 unsigned mode, modeCount;
6725 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006726 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6727 (Cand->FailureKind == ovl_fail_bad_deduction &&
6728 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006729 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006730 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006731 mode = 0; // "at least"
6732 else
6733 mode = 2; // "exactly"
6734 modeCount = MinParams;
6735 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006736 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6737 (Cand->FailureKind == ovl_fail_bad_deduction &&
6738 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006739 if (MinParams != FnTy->getNumArgs())
6740 mode = 1; // "at most"
6741 else
6742 mode = 2; // "exactly"
6743 modeCount = FnTy->getNumArgs();
6744 }
6745
6746 std::string Description;
6747 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6748
6749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006750 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006751 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006752 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006753}
6754
John McCall8b9ed552010-02-01 18:53:26 +00006755/// Diagnose a failed template-argument deduction.
6756void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6757 Expr **Args, unsigned NumArgs) {
6758 FunctionDecl *Fn = Cand->Function; // pattern
6759
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006760 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006761 NamedDecl *ParamD;
6762 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6763 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6764 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006765 switch (Cand->DeductionFailure.Result) {
6766 case Sema::TDK_Success:
6767 llvm_unreachable("TDK_success while diagnosing bad deduction");
6768
6769 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006770 assert(ParamD && "no parameter found for incomplete deduction result");
6771 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6772 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006773 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006774 return;
6775 }
6776
John McCall42d7d192010-08-05 09:05:08 +00006777 case Sema::TDK_Underqualified: {
6778 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6779 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6780
6781 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6782
6783 // Param will have been canonicalized, but it should just be a
6784 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006785 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006786 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006787 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006788 assert(S.Context.hasSameType(Param, NonCanonParam));
6789
6790 // Arg has also been canonicalized, but there's nothing we can do
6791 // about that. It also doesn't matter as much, because it won't
6792 // have any template parameters in it (because deduction isn't
6793 // done on dependent types).
6794 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6795
6796 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6797 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00006798 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00006799 return;
6800 }
6801
6802 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006803 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006804 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006805 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006806 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006807 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006808 which = 1;
6809 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006810 which = 2;
6811 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006812
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006813 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006814 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006815 << *Cand->DeductionFailure.getFirstArg()
6816 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00006817 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006818 return;
6819 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006820
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006821 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006822 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006823 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006824 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006825 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6826 << ParamD->getDeclName();
6827 else {
6828 int index = 0;
6829 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6830 index = TTP->getIndex();
6831 else if (NonTypeTemplateParmDecl *NTTP
6832 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6833 index = NTTP->getIndex();
6834 else
6835 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006836 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006837 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6838 << (index + 1);
6839 }
Sebastian Redl08905022011-02-05 19:23:19 +00006840 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006841 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006842
Douglas Gregor02eb4832010-05-08 18:13:28 +00006843 case Sema::TDK_TooManyArguments:
6844 case Sema::TDK_TooFewArguments:
6845 DiagnoseArityMismatch(S, Cand, NumArgs);
6846 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006847
6848 case Sema::TDK_InstantiationDepth:
6849 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00006850 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006851 return;
6852
6853 case Sema::TDK_SubstitutionFailure: {
6854 std::string ArgString;
6855 if (TemplateArgumentList *Args
6856 = Cand->DeductionFailure.getTemplateArgumentList())
6857 ArgString = S.getTemplateArgumentBindingsText(
6858 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6859 *Args);
6860 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6861 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00006862 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006863 return;
6864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006865
John McCall8b9ed552010-02-01 18:53:26 +00006866 // TODO: diagnose these individually, then kill off
6867 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006868 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006869 case Sema::TDK_FailedOverloadResolution:
6870 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00006871 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006872 return;
6873 }
6874}
6875
6876/// Generates a 'note' diagnostic for an overload candidate. We've
6877/// already generated a primary error at the call site.
6878///
6879/// It really does need to be a single diagnostic with its caret
6880/// pointed at the candidate declaration. Yes, this creates some
6881/// major challenges of technical writing. Yes, this makes pointing
6882/// out problems with specific arguments quite awkward. It's still
6883/// better than generating twenty screens of text for every failed
6884/// overload.
6885///
6886/// It would be great to be able to express per-candidate problems
6887/// more richly for those diagnostic clients that cared, but we'd
6888/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006889void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6890 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006891 FunctionDecl *Fn = Cand->Function;
6892
John McCall12f97bc2010-01-08 04:41:39 +00006893 // Note deleted candidates, but only if they're viable.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006894 if (Cand->Viable && (Fn->isDeleted() || Fn->isUnavailable())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006895 std::string FnDesc;
6896 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006897
6898 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006899 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00006900 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00006901 return;
John McCall12f97bc2010-01-08 04:41:39 +00006902 }
6903
John McCalle1ac8d12010-01-13 00:25:19 +00006904 // We don't really have anything else to say about viable candidates.
6905 if (Cand->Viable) {
6906 S.NoteOverloadCandidate(Fn);
6907 return;
6908 }
John McCall0d1da222010-01-12 00:44:57 +00006909
John McCall6a61b522010-01-13 09:16:55 +00006910 switch (Cand->FailureKind) {
6911 case ovl_fail_too_many_arguments:
6912 case ovl_fail_too_few_arguments:
6913 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006914
John McCall6a61b522010-01-13 09:16:55 +00006915 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006916 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6917
John McCallfe796dd2010-01-23 05:17:32 +00006918 case ovl_fail_trivial_conversion:
6919 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006920 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006921 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006922
John McCall65eb8792010-02-25 01:37:24 +00006923 case ovl_fail_bad_conversion: {
6924 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6925 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006926 if (Cand->Conversions[I].isBad())
6927 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006928
John McCall6a61b522010-01-13 09:16:55 +00006929 // FIXME: this currently happens when we're called from SemaInit
6930 // when user-conversion overload fails. Figure out how to handle
6931 // those conditions and diagnose them well.
6932 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006933 }
John McCall65eb8792010-02-25 01:37:24 +00006934 }
John McCalld3224162010-01-08 00:58:21 +00006935}
6936
6937void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6938 // Desugar the type of the surrogate down to a function type,
6939 // retaining as many typedefs as possible while still showing
6940 // the function type (and, therefore, its parameter types).
6941 QualType FnType = Cand->Surrogate->getConversionType();
6942 bool isLValueReference = false;
6943 bool isRValueReference = false;
6944 bool isPointer = false;
6945 if (const LValueReferenceType *FnTypeRef =
6946 FnType->getAs<LValueReferenceType>()) {
6947 FnType = FnTypeRef->getPointeeType();
6948 isLValueReference = true;
6949 } else if (const RValueReferenceType *FnTypeRef =
6950 FnType->getAs<RValueReferenceType>()) {
6951 FnType = FnTypeRef->getPointeeType();
6952 isRValueReference = true;
6953 }
6954 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6955 FnType = FnTypePtr->getPointeeType();
6956 isPointer = true;
6957 }
6958 // Desugar down to a function type.
6959 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6960 // Reconstruct the pointer/reference as appropriate.
6961 if (isPointer) FnType = S.Context.getPointerType(FnType);
6962 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6963 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6964
6965 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6966 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00006967 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00006968}
6969
6970void NoteBuiltinOperatorCandidate(Sema &S,
6971 const char *Opc,
6972 SourceLocation OpLoc,
6973 OverloadCandidate *Cand) {
6974 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6975 std::string TypeStr("operator");
6976 TypeStr += Opc;
6977 TypeStr += "(";
6978 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6979 if (Cand->Conversions.size() == 1) {
6980 TypeStr += ")";
6981 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6982 } else {
6983 TypeStr += ", ";
6984 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6985 TypeStr += ")";
6986 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6987 }
6988}
6989
6990void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6991 OverloadCandidate *Cand) {
6992 unsigned NoOperands = Cand->Conversions.size();
6993 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6994 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006995 if (ICS.isBad()) break; // all meaningless after first invalid
6996 if (!ICS.isAmbiguous()) continue;
6997
John McCall5c32be02010-08-24 20:38:10 +00006998 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006999 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007000 }
7001}
7002
John McCall3712d9e2010-01-15 23:32:50 +00007003SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7004 if (Cand->Function)
7005 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007006 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007007 return Cand->Surrogate->getLocation();
7008 return SourceLocation();
7009}
7010
John McCallad2587a2010-01-12 00:48:53 +00007011struct CompareOverloadCandidatesForDisplay {
7012 Sema &S;
7013 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007014
7015 bool operator()(const OverloadCandidate *L,
7016 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007017 // Fast-path this check.
7018 if (L == R) return false;
7019
John McCall12f97bc2010-01-08 04:41:39 +00007020 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007021 if (L->Viable) {
7022 if (!R->Viable) return true;
7023
7024 // TODO: introduce a tri-valued comparison for overload
7025 // candidates. Would be more worthwhile if we had a sort
7026 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007027 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7028 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007029 } else if (R->Viable)
7030 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007031
John McCall3712d9e2010-01-15 23:32:50 +00007032 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007033
John McCall3712d9e2010-01-15 23:32:50 +00007034 // Criteria by which we can sort non-viable candidates:
7035 if (!L->Viable) {
7036 // 1. Arity mismatches come after other candidates.
7037 if (L->FailureKind == ovl_fail_too_many_arguments ||
7038 L->FailureKind == ovl_fail_too_few_arguments)
7039 return false;
7040 if (R->FailureKind == ovl_fail_too_many_arguments ||
7041 R->FailureKind == ovl_fail_too_few_arguments)
7042 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007043
John McCallfe796dd2010-01-23 05:17:32 +00007044 // 2. Bad conversions come first and are ordered by the number
7045 // of bad conversions and quality of good conversions.
7046 if (L->FailureKind == ovl_fail_bad_conversion) {
7047 if (R->FailureKind != ovl_fail_bad_conversion)
7048 return true;
7049
7050 // If there's any ordering between the defined conversions...
7051 // FIXME: this might not be transitive.
7052 assert(L->Conversions.size() == R->Conversions.size());
7053
7054 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007055 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7056 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007057 switch (CompareImplicitConversionSequences(S,
7058 L->Conversions[I],
7059 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007060 case ImplicitConversionSequence::Better:
7061 leftBetter++;
7062 break;
7063
7064 case ImplicitConversionSequence::Worse:
7065 leftBetter--;
7066 break;
7067
7068 case ImplicitConversionSequence::Indistinguishable:
7069 break;
7070 }
7071 }
7072 if (leftBetter > 0) return true;
7073 if (leftBetter < 0) return false;
7074
7075 } else if (R->FailureKind == ovl_fail_bad_conversion)
7076 return false;
7077
John McCall3712d9e2010-01-15 23:32:50 +00007078 // TODO: others?
7079 }
7080
7081 // Sort everything else by location.
7082 SourceLocation LLoc = GetLocationForCandidate(L);
7083 SourceLocation RLoc = GetLocationForCandidate(R);
7084
7085 // Put candidates without locations (e.g. builtins) at the end.
7086 if (LLoc.isInvalid()) return false;
7087 if (RLoc.isInvalid()) return true;
7088
7089 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007090 }
7091};
7092
John McCallfe796dd2010-01-23 05:17:32 +00007093/// CompleteNonViableCandidate - Normally, overload resolution only
7094/// computes up to the first
7095void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7096 Expr **Args, unsigned NumArgs) {
7097 assert(!Cand->Viable);
7098
7099 // Don't do anything on failures other than bad conversion.
7100 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7101
7102 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007103 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007104 unsigned ConvCount = Cand->Conversions.size();
7105 while (true) {
7106 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7107 ConvIdx++;
7108 if (Cand->Conversions[ConvIdx - 1].isBad())
7109 break;
7110 }
7111
7112 if (ConvIdx == ConvCount)
7113 return;
7114
John McCall65eb8792010-02-25 01:37:24 +00007115 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7116 "remaining conversion is initialized?");
7117
Douglas Gregoradc7a702010-04-16 17:45:54 +00007118 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007119 // operation somehow.
7120 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007121
7122 const FunctionProtoType* Proto;
7123 unsigned ArgIdx = ConvIdx;
7124
7125 if (Cand->IsSurrogate) {
7126 QualType ConvType
7127 = Cand->Surrogate->getConversionType().getNonReferenceType();
7128 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7129 ConvType = ConvPtrType->getPointeeType();
7130 Proto = ConvType->getAs<FunctionProtoType>();
7131 ArgIdx--;
7132 } else if (Cand->Function) {
7133 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7134 if (isa<CXXMethodDecl>(Cand->Function) &&
7135 !isa<CXXConstructorDecl>(Cand->Function))
7136 ArgIdx--;
7137 } else {
7138 // Builtin binary operator with a bad first conversion.
7139 assert(ConvCount <= 3);
7140 for (; ConvIdx != ConvCount; ++ConvIdx)
7141 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007142 = TryCopyInitialization(S, Args[ConvIdx],
7143 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007144 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007145 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00007146 return;
7147 }
7148
7149 // Fill in the rest of the conversions.
7150 unsigned NumArgsInProto = Proto->getNumArgs();
7151 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7152 if (ArgIdx < NumArgsInProto)
7153 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007154 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007155 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007156 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00007157 else
7158 Cand->Conversions[ConvIdx].setEllipsis();
7159 }
7160}
7161
John McCalld3224162010-01-08 00:58:21 +00007162} // end anonymous namespace
7163
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007164/// PrintOverloadCandidates - When overload resolution fails, prints
7165/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007166/// set.
John McCall5c32be02010-08-24 20:38:10 +00007167void OverloadCandidateSet::NoteCandidates(Sema &S,
7168 OverloadCandidateDisplayKind OCD,
7169 Expr **Args, unsigned NumArgs,
7170 const char *Opc,
7171 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007172 // Sort the candidates by viability and position. Sorting directly would
7173 // be prohibitive, so we make a set of pointers and sort those.
7174 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007175 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7176 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007177 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007178 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007179 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007180 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007181 if (Cand->Function || Cand->IsSurrogate)
7182 Cands.push_back(Cand);
7183 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7184 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007185 }
7186 }
7187
John McCallad2587a2010-01-12 00:48:53 +00007188 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007189 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007190
John McCall0d1da222010-01-12 00:44:57 +00007191 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007192
John McCall12f97bc2010-01-08 04:41:39 +00007193 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007194 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007195 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007196 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7197 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007198
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007199 // Set an arbitrary limit on the number of candidate functions we'll spam
7200 // the user with. FIXME: This limit should depend on details of the
7201 // candidate list.
7202 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7203 break;
7204 }
7205 ++CandsShown;
7206
John McCalld3224162010-01-08 00:58:21 +00007207 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007208 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007209 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007210 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007211 else {
7212 assert(Cand->Viable &&
7213 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007214 // Generally we only see ambiguities including viable builtin
7215 // operators if overload resolution got screwed up by an
7216 // ambiguous user-defined conversion.
7217 //
7218 // FIXME: It's quite possible for different conversions to see
7219 // different ambiguities, though.
7220 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007221 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007222 ReportedAmbiguousConversions = true;
7223 }
John McCalld3224162010-01-08 00:58:21 +00007224
John McCall0d1da222010-01-12 00:44:57 +00007225 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007226 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007227 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007228 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007229
7230 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007231 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007232}
7233
Douglas Gregorb491ed32011-02-19 21:32:49 +00007234// [PossiblyAFunctionType] --> [Return]
7235// NonFunctionType --> NonFunctionType
7236// R (A) --> R(A)
7237// R (*)(A) --> R (A)
7238// R (&)(A) --> R (A)
7239// R (S::*)(A) --> R (A)
7240QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7241 QualType Ret = PossiblyAFunctionType;
7242 if (const PointerType *ToTypePtr =
7243 PossiblyAFunctionType->getAs<PointerType>())
7244 Ret = ToTypePtr->getPointeeType();
7245 else if (const ReferenceType *ToTypeRef =
7246 PossiblyAFunctionType->getAs<ReferenceType>())
7247 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007248 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007249 PossiblyAFunctionType->getAs<MemberPointerType>())
7250 Ret = MemTypePtr->getPointeeType();
7251 Ret =
7252 Context.getCanonicalType(Ret).getUnqualifiedType();
7253 return Ret;
7254}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007255
Douglas Gregorb491ed32011-02-19 21:32:49 +00007256// A helper class to help with address of function resolution
7257// - allows us to avoid passing around all those ugly parameters
7258class AddressOfFunctionResolver
7259{
7260 Sema& S;
7261 Expr* SourceExpr;
7262 const QualType& TargetType;
7263 QualType TargetFunctionType; // Extracted function type from target type
7264
7265 bool Complain;
7266 //DeclAccessPair& ResultFunctionAccessPair;
7267 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007268
Douglas Gregorb491ed32011-02-19 21:32:49 +00007269 bool TargetTypeIsNonStaticMemberFunction;
7270 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007271
Douglas Gregorb491ed32011-02-19 21:32:49 +00007272 OverloadExpr::FindResult OvlExprInfo;
7273 OverloadExpr *OvlExpr;
7274 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007275 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007276
Douglas Gregorb491ed32011-02-19 21:32:49 +00007277public:
7278 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7279 const QualType& TargetType, bool Complain)
7280 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7281 Complain(Complain), Context(S.getASTContext()),
7282 TargetTypeIsNonStaticMemberFunction(
7283 !!TargetType->getAs<MemberPointerType>()),
7284 FoundNonTemplateFunction(false),
7285 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7286 OvlExpr(OvlExprInfo.Expression)
7287 {
7288 ExtractUnqualifiedFunctionTypeFromTargetType();
7289
7290 if (!TargetFunctionType->isFunctionType()) {
7291 if (OvlExpr->hasExplicitTemplateArgs()) {
7292 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007293 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007294 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007295
7296 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7297 if (!Method->isStatic()) {
7298 // If the target type is a non-function type and the function
7299 // found is a non-static member function, pretend as if that was
7300 // the target, it's the only possible type to end up with.
7301 TargetTypeIsNonStaticMemberFunction = true;
7302
7303 // And skip adding the function if its not in the proper form.
7304 // We'll diagnose this due to an empty set of functions.
7305 if (!OvlExprInfo.HasFormOfMemberPointer)
7306 return;
7307 }
7308 }
7309
Douglas Gregorb491ed32011-02-19 21:32:49 +00007310 Matches.push_back(std::make_pair(dap,Fn));
7311 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007312 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007313 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007314 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007315
7316 if (OvlExpr->hasExplicitTemplateArgs())
7317 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007318
Douglas Gregorb491ed32011-02-19 21:32:49 +00007319 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7320 // C++ [over.over]p4:
7321 // If more than one function is selected, [...]
7322 if (Matches.size() > 1) {
7323 if (FoundNonTemplateFunction)
7324 EliminateAllTemplateMatches();
7325 else
7326 EliminateAllExceptMostSpecializedTemplate();
7327 }
7328 }
7329 }
7330
7331private:
7332 bool isTargetTypeAFunction() const {
7333 return TargetFunctionType->isFunctionType();
7334 }
7335
7336 // [ToType] [Return]
7337
7338 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7339 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7340 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7341 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7342 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7343 }
7344
7345 // return true if any matching specializations were found
7346 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7347 const DeclAccessPair& CurAccessFunPair) {
7348 if (CXXMethodDecl *Method
7349 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7350 // Skip non-static function templates when converting to pointer, and
7351 // static when converting to member pointer.
7352 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7353 return false;
7354 }
7355 else if (TargetTypeIsNonStaticMemberFunction)
7356 return false;
7357
7358 // C++ [over.over]p2:
7359 // If the name is a function template, template argument deduction is
7360 // done (14.8.2.2), and if the argument deduction succeeds, the
7361 // resulting template argument list is used to generate a single
7362 // function template specialization, which is added to the set of
7363 // overloaded functions considered.
7364 FunctionDecl *Specialization = 0;
7365 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7366 if (Sema::TemplateDeductionResult Result
7367 = S.DeduceTemplateArguments(FunctionTemplate,
7368 &OvlExplicitTemplateArgs,
7369 TargetFunctionType, Specialization,
7370 Info)) {
7371 // FIXME: make a note of the failed deduction for diagnostics.
7372 (void)Result;
7373 return false;
7374 }
7375
7376 // Template argument deduction ensures that we have an exact match.
7377 // This function template specicalization works.
7378 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7379 assert(TargetFunctionType
7380 == Context.getCanonicalType(Specialization->getType()));
7381 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7382 return true;
7383 }
7384
7385 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7386 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007387 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007388 // Skip non-static functions when converting to pointer, and static
7389 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007390 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7391 return false;
7392 }
7393 else if (TargetTypeIsNonStaticMemberFunction)
7394 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007395
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007396 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007397 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007398 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7399 FunDecl->getType()) ||
7400 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007401 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007402 Matches.push_back(std::make_pair(CurAccessFunPair,
7403 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007404 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007405 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007406 }
Mike Stump11289f42009-09-09 15:08:12 +00007407 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007408
7409 return false;
7410 }
7411
7412 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7413 bool Ret = false;
7414
7415 // If the overload expression doesn't have the form of a pointer to
7416 // member, don't try to convert it to a pointer-to-member type.
7417 if (IsInvalidFormOfPointerToMemberFunction())
7418 return false;
7419
7420 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7421 E = OvlExpr->decls_end();
7422 I != E; ++I) {
7423 // Look through any using declarations to find the underlying function.
7424 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7425
7426 // C++ [over.over]p3:
7427 // Non-member functions and static member functions match
7428 // targets of type "pointer-to-function" or "reference-to-function."
7429 // Nonstatic member functions match targets of
7430 // type "pointer-to-member-function."
7431 // Note that according to DR 247, the containing class does not matter.
7432 if (FunctionTemplateDecl *FunctionTemplate
7433 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7434 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7435 Ret = true;
7436 }
7437 // If we have explicit template arguments supplied, skip non-templates.
7438 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7439 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7440 Ret = true;
7441 }
7442 assert(Ret || Matches.empty());
7443 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007444 }
7445
Douglas Gregorb491ed32011-02-19 21:32:49 +00007446 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007447 // [...] and any given function template specialization F1 is
7448 // eliminated if the set contains a second function template
7449 // specialization whose function template is more specialized
7450 // than the function template of F1 according to the partial
7451 // ordering rules of 14.5.5.2.
7452
7453 // The algorithm specified above is quadratic. We instead use a
7454 // two-pass algorithm (similar to the one used to identify the
7455 // best viable function in an overload set) that identifies the
7456 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007457
7458 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7459 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7460 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007461
John McCall58cc69d2010-01-27 01:50:18 +00007462 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007463 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7464 TPOC_Other, 0, SourceExpr->getLocStart(),
7465 S.PDiag(),
7466 S.PDiag(diag::err_addr_ovl_ambiguous)
7467 << Matches[0].second->getDeclName(),
7468 S.PDiag(diag::note_ovl_candidate)
7469 << (unsigned) oc_function_template,
7470 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007471
Douglas Gregorb491ed32011-02-19 21:32:49 +00007472 if (Result != MatchesCopy.end()) {
7473 // Make it the first and only element
7474 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7475 Matches[0].second = cast<FunctionDecl>(*Result);
7476 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007477 }
7478 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007479
Douglas Gregorb491ed32011-02-19 21:32:49 +00007480 void EliminateAllTemplateMatches() {
7481 // [...] any function template specializations in the set are
7482 // eliminated if the set also contains a non-template function, [...]
7483 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7484 if (Matches[I].second->getPrimaryTemplate() == 0)
7485 ++I;
7486 else {
7487 Matches[I] = Matches[--N];
7488 Matches.set_size(N);
7489 }
7490 }
7491 }
7492
7493public:
7494 void ComplainNoMatchesFound() const {
7495 assert(Matches.empty());
7496 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7497 << OvlExpr->getName() << TargetFunctionType
7498 << OvlExpr->getSourceRange();
7499 S.NoteAllOverloadCandidates(OvlExpr);
7500 }
7501
7502 bool IsInvalidFormOfPointerToMemberFunction() const {
7503 return TargetTypeIsNonStaticMemberFunction &&
7504 !OvlExprInfo.HasFormOfMemberPointer;
7505 }
7506
7507 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7508 // TODO: Should we condition this on whether any functions might
7509 // have matched, or is it more appropriate to do that in callers?
7510 // TODO: a fixit wouldn't hurt.
7511 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7512 << TargetType << OvlExpr->getSourceRange();
7513 }
7514
7515 void ComplainOfInvalidConversion() const {
7516 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7517 << OvlExpr->getName() << TargetType;
7518 }
7519
7520 void ComplainMultipleMatchesFound() const {
7521 assert(Matches.size() > 1);
7522 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7523 << OvlExpr->getName()
7524 << OvlExpr->getSourceRange();
7525 S.NoteAllOverloadCandidates(OvlExpr);
7526 }
7527
7528 int getNumMatches() const { return Matches.size(); }
7529
7530 FunctionDecl* getMatchingFunctionDecl() const {
7531 if (Matches.size() != 1) return 0;
7532 return Matches[0].second;
7533 }
7534
7535 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7536 if (Matches.size() != 1) return 0;
7537 return &Matches[0].first;
7538 }
7539};
7540
7541/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7542/// an overloaded function (C++ [over.over]), where @p From is an
7543/// expression with overloaded function type and @p ToType is the type
7544/// we're trying to resolve to. For example:
7545///
7546/// @code
7547/// int f(double);
7548/// int f(int);
7549///
7550/// int (*pfd)(double) = f; // selects f(double)
7551/// @endcode
7552///
7553/// This routine returns the resulting FunctionDecl if it could be
7554/// resolved, and NULL otherwise. When @p Complain is true, this
7555/// routine will emit diagnostics if there is an error.
7556FunctionDecl *
7557Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7558 bool Complain,
7559 DeclAccessPair &FoundResult) {
7560
7561 assert(AddressOfExpr->getType() == Context.OverloadTy);
7562
7563 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7564 int NumMatches = Resolver.getNumMatches();
7565 FunctionDecl* Fn = 0;
7566 if ( NumMatches == 0 && Complain) {
7567 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7568 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7569 else
7570 Resolver.ComplainNoMatchesFound();
7571 }
7572 else if (NumMatches > 1 && Complain)
7573 Resolver.ComplainMultipleMatchesFound();
7574 else if (NumMatches == 1) {
7575 Fn = Resolver.getMatchingFunctionDecl();
7576 assert(Fn);
7577 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7578 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007579 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007580 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007581 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007582
7583 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007584}
7585
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007586/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007587/// resolve that overloaded function expression down to a single function.
7588///
7589/// This routine can only resolve template-ids that refer to a single function
7590/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007591/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007592/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00007593FunctionDecl *
7594Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7595 bool Complain,
7596 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007597 // C++ [over.over]p1:
7598 // [...] [Note: any redundant set of parentheses surrounding the
7599 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007600 // C++ [over.over]p1:
7601 // [...] The overloaded function name can be preceded by the &
7602 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007603
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007604 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00007605 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007606 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007607
7608 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00007609 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007610
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007611 // Look through all of the overloaded functions, searching for one
7612 // whose type matches exactly.
7613 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007614 for (UnresolvedSetIterator I = ovl->decls_begin(),
7615 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007616 // C++0x [temp.arg.explicit]p3:
7617 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007618 // where deduction is not done, if a template argument list is
7619 // specified and it, along with any default template arguments,
7620 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007621 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007622 FunctionTemplateDecl *FunctionTemplate
7623 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007624
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007625 // C++ [over.over]p2:
7626 // If the name is a function template, template argument deduction is
7627 // done (14.8.2.2), and if the argument deduction succeeds, the
7628 // resulting template argument list is used to generate a single
7629 // function template specialization, which is added to the set of
7630 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007631 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007632 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007633 if (TemplateDeductionResult Result
7634 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7635 Specialization, Info)) {
7636 // FIXME: make a note of the failed deduction for diagnostics.
7637 (void)Result;
7638 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007639 }
7640
John McCall0009fcc2011-04-26 20:42:42 +00007641 assert(Specialization && "no specialization and no error?");
7642
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007643 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007644 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007645 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00007646 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7647 << ovl->getName();
7648 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007649 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007650 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00007651 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007652
John McCall0009fcc2011-04-26 20:42:42 +00007653 Matched = Specialization;
7654 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007656
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007657 return Matched;
7658}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007659
Douglas Gregor1beec452011-03-12 01:48:56 +00007660
7661
7662
7663// Resolve and fix an overloaded expression that
7664// can be resolved because it identifies a single function
7665// template specialization
7666// Last three arguments should only be supplied if Complain = true
7667ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00007668 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00007669 const SourceRange& OpRangeForComplaining,
7670 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00007671 unsigned DiagIDForComplaining) {
7672 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00007673
John McCall0009fcc2011-04-26 20:42:42 +00007674 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00007675
John McCall0009fcc2011-04-26 20:42:42 +00007676 DeclAccessPair found;
7677 ExprResult SingleFunctionExpression;
7678 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7679 ovl.Expression, /*complain*/ false, &found)) {
7680 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7681 return ExprError();
7682
7683 // It is only correct to resolve to an instance method if we're
7684 // resolving a form that's permitted to be a pointer to member.
7685 // Otherwise we'll end up making a bound member expression, which
7686 // is illegal in all the contexts we resolve like this.
7687 if (!ovl.HasFormOfMemberPointer &&
7688 isa<CXXMethodDecl>(fn) &&
7689 cast<CXXMethodDecl>(fn)->isInstance()) {
7690 if (complain) {
7691 Diag(ovl.Expression->getExprLoc(),
7692 diag::err_invalid_use_of_bound_member_func)
7693 << ovl.Expression->getSourceRange();
7694 // TODO: I believe we only end up here if there's a mix of
7695 // static and non-static candidates (otherwise the expression
7696 // would have 'bound member' type, not 'overload' type).
7697 // Ideally we would note which candidate was chosen and why
7698 // the static candidates were rejected.
7699 }
7700
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007701 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00007702 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007703
John McCall0009fcc2011-04-26 20:42:42 +00007704 // Fix the expresion to refer to 'fn'.
7705 SingleFunctionExpression =
7706 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7707
7708 // If desired, do function-to-pointer decay.
7709 if (doFunctionPointerConverion)
7710 SingleFunctionExpression =
7711 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7712 }
7713
7714 if (!SingleFunctionExpression.isUsable()) {
7715 if (complain) {
7716 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7717 << ovl.Expression->getName()
7718 << DestTypeForComplaining
7719 << OpRangeForComplaining
7720 << ovl.Expression->getQualifierLoc().getSourceRange();
7721 NoteAllOverloadCandidates(SrcExpr);
7722 }
7723 return ExprError();
7724 }
7725
7726 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00007727}
7728
Douglas Gregorcabea402009-09-22 15:41:20 +00007729/// \brief Add a single candidate to the overload set.
7730static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007731 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007732 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007733 Expr **Args, unsigned NumArgs,
7734 OverloadCandidateSet &CandidateSet,
7735 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007736 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007737 if (isa<UsingShadowDecl>(Callee))
7738 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7739
Douglas Gregorcabea402009-09-22 15:41:20 +00007740 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007741 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007742 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007743 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007744 return;
John McCalld14a8642009-11-21 08:51:07 +00007745 }
7746
7747 if (FunctionTemplateDecl *FuncTemplate
7748 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007749 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7750 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007751 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007752 return;
7753 }
7754
7755 assert(false && "unhandled case in overloaded call candidate");
7756
7757 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007758}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007759
Douglas Gregorcabea402009-09-22 15:41:20 +00007760/// \brief Add the overload candidates named by callee and/or found by argument
7761/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007762void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007763 Expr **Args, unsigned NumArgs,
7764 OverloadCandidateSet &CandidateSet,
7765 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007766
7767#ifndef NDEBUG
7768 // Verify that ArgumentDependentLookup is consistent with the rules
7769 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007770 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007771 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7772 // and let Y be the lookup set produced by argument dependent
7773 // lookup (defined as follows). If X contains
7774 //
7775 // -- a declaration of a class member, or
7776 //
7777 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007778 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007779 //
7780 // -- a declaration that is neither a function or a function
7781 // template
7782 //
7783 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007784
John McCall57500772009-12-16 12:17:52 +00007785 if (ULE->requiresADL()) {
7786 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7787 E = ULE->decls_end(); I != E; ++I) {
7788 assert(!(*I)->getDeclContext()->isRecord());
7789 assert(isa<UsingShadowDecl>(*I) ||
7790 !(*I)->getDeclContext()->isFunctionOrMethod());
7791 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007792 }
7793 }
7794#endif
7795
John McCall57500772009-12-16 12:17:52 +00007796 // It would be nice to avoid this copy.
7797 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00007798 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00007799 if (ULE->hasExplicitTemplateArgs()) {
7800 ULE->copyTemplateArgumentsInto(TABuffer);
7801 ExplicitTemplateArgs = &TABuffer;
7802 }
7803
7804 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7805 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007806 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007807 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007808 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007809
John McCall57500772009-12-16 12:17:52 +00007810 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007811 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7812 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007813 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007814 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007815 PartialOverloading,
7816 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00007817}
John McCalld681c392009-12-16 08:11:27 +00007818
7819/// Attempts to recover from a call where no functions were found.
7820///
7821/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007822static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007823BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007824 UnresolvedLookupExpr *ULE,
7825 SourceLocation LParenLoc,
7826 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007827 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007828
7829 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00007830 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00007831
John McCall57500772009-12-16 12:17:52 +00007832 TemplateArgumentListInfo TABuffer;
7833 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7834 if (ULE->hasExplicitTemplateArgs()) {
7835 ULE->copyTemplateArgumentsInto(TABuffer);
7836 ExplicitTemplateArgs = &TABuffer;
7837 }
7838
John McCalld681c392009-12-16 08:11:27 +00007839 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7840 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007841 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007842 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007843
John McCall57500772009-12-16 12:17:52 +00007844 assert(!R.empty() && "lookup results empty despite recovery");
7845
7846 // Build an implicit member call if appropriate. Just drop the
7847 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007848 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007849 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007850 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7851 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007852 else if (ExplicitTemplateArgs)
7853 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7854 else
7855 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7856
7857 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007858 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007859
7860 // This shouldn't cause an infinite loop because we're giving it
7861 // an expression with non-empty lookup results, which should never
7862 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007863 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007864 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007865}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007866
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007867/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007868/// (which eventually refers to the declaration Func) and the call
7869/// arguments Args/NumArgs, attempt to resolve the function call down
7870/// to a specific function. If overload resolution succeeds, returns
7871/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007872/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007873/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007874ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007875Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007876 SourceLocation LParenLoc,
7877 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00007878 SourceLocation RParenLoc,
7879 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00007880#ifndef NDEBUG
7881 if (ULE->requiresADL()) {
7882 // To do ADL, we must have found an unqualified name.
7883 assert(!ULE->getQualifier() && "qualified name with ADL");
7884
7885 // We don't perform ADL for implicit declarations of builtins.
7886 // Verify that this was correctly set up.
7887 FunctionDecl *F;
7888 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7889 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7890 F->getBuiltinID() && F->isImplicit())
7891 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007892
John McCall57500772009-12-16 12:17:52 +00007893 // We don't perform ADL in C.
7894 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00007895 } else
7896 assert(!ULE->isStdAssociatedNamespace() &&
7897 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00007898#endif
7899
John McCallbc077cf2010-02-08 23:07:23 +00007900 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007901
John McCall57500772009-12-16 12:17:52 +00007902 // Add the functions denoted by the callee to the set of candidate
7903 // functions, including those from argument-dependent lookup.
7904 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007905
7906 // If we found nothing, try to recover.
7907 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7908 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007909 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007910 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007911 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007912
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007913 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007914 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007915 case OR_Success: {
7916 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00007917 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00007918 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007919 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7920 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007921 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00007922 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7923 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00007924 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007925
7926 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007927 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007928 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007929 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007930 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007931 break;
7932
7933 case OR_Ambiguous:
7934 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007935 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007936 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007937 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007938
7939 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007940 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007941 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7942 << Best->Function->isDeleted()
7943 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007944 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007945 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007946 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7947 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00007948 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007949 }
7950
Douglas Gregorb412e172010-07-25 18:17:45 +00007951 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007952 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007953}
7954
John McCall4c4c1df2010-01-26 03:27:55 +00007955static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007956 return Functions.size() > 1 ||
7957 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7958}
7959
Douglas Gregor084d8552009-03-13 23:49:33 +00007960/// \brief Create a unary operation that may resolve to an overloaded
7961/// operator.
7962///
7963/// \param OpLoc The location of the operator itself (e.g., '*').
7964///
7965/// \param OpcIn The UnaryOperator::Opcode that describes this
7966/// operator.
7967///
7968/// \param Functions The set of non-member functions that will be
7969/// considered by overload resolution. The caller needs to build this
7970/// set based on the context using, e.g.,
7971/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7972/// set should not contain any member functions; those will be added
7973/// by CreateOverloadedUnaryOp().
7974///
7975/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007976ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007977Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7978 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007979 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007980 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007981
7982 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7983 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7984 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007985 // TODO: provide better source location info.
7986 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007987
John Wiegley01296292011-04-08 18:41:53 +00007988 if (Input->getObjectKind() == OK_ObjCProperty) {
7989 ExprResult Result = ConvertPropertyForRValue(Input);
7990 if (Result.isInvalid())
7991 return ExprError();
7992 Input = Result.take();
7993 }
John McCalle26a8722010-12-04 08:14:53 +00007994
Douglas Gregor084d8552009-03-13 23:49:33 +00007995 Expr *Args[2] = { Input, 0 };
7996 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007997
Douglas Gregor084d8552009-03-13 23:49:33 +00007998 // For post-increment and post-decrement, add the implicit '0' as
7999 // the second argument, so that we know this is a post-increment or
8000 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008001 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008002 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008003 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8004 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008005 NumArgs = 2;
8006 }
8007
8008 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008009 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008010 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008011 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008012 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008013 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008014 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008015
John McCall58cc69d2010-01-27 01:50:18 +00008016 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008017 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008018 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008019 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008020 /*ADL*/ true, IsOverloaded(Fns),
8021 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008022 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008023 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008024 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008025 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008026 OpLoc));
8027 }
8028
8029 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008030 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008031
8032 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008033 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008034
8035 // Add operator candidates that are member functions.
8036 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8037
John McCall4c4c1df2010-01-26 03:27:55 +00008038 // Add candidates from ADL.
8039 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008040 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008041 /*ExplicitTemplateArgs*/ 0,
8042 CandidateSet);
8043
Douglas Gregor084d8552009-03-13 23:49:33 +00008044 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008045 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008046
8047 // Perform overload resolution.
8048 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008049 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008050 case OR_Success: {
8051 // We found a built-in operator or an overloaded operator.
8052 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008053
Douglas Gregor084d8552009-03-13 23:49:33 +00008054 if (FnDecl) {
8055 // We matched an overloaded operator. Build a call to that
8056 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008057
Chandler Carruth30141632011-02-25 19:41:05 +00008058 MarkDeclarationReferenced(OpLoc, FnDecl);
8059
Douglas Gregor084d8552009-03-13 23:49:33 +00008060 // Convert the arguments.
8061 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008062 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008063
John Wiegley01296292011-04-08 18:41:53 +00008064 ExprResult InputRes =
8065 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8066 Best->FoundDecl, Method);
8067 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008068 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008069 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008070 } else {
8071 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008072 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008073 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008074 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008075 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008076 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008077 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008078 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008079 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008080 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008081 }
8082
John McCall4fa0d5f2010-05-06 18:15:07 +00008083 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8084
John McCall7decc9e2010-11-18 06:31:45 +00008085 // Determine the result type.
8086 QualType ResultTy = FnDecl->getResultType();
8087 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8088 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008089
Douglas Gregor084d8552009-03-13 23:49:33 +00008090 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008091 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8092 if (FnExpr.isInvalid())
8093 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008094
Eli Friedman030eee42009-11-18 03:58:17 +00008095 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008096 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008097 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008098 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008099
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008100 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008101 FnDecl))
8102 return ExprError();
8103
John McCallb268a282010-08-23 23:25:46 +00008104 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008105 } else {
8106 // We matched a built-in operator. Convert the arguments, then
8107 // break out so that we will build the appropriate built-in
8108 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008109 ExprResult InputRes =
8110 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8111 Best->Conversions[0], AA_Passing);
8112 if (InputRes.isInvalid())
8113 return ExprError();
8114 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008115 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008116 }
John Wiegley01296292011-04-08 18:41:53 +00008117 }
8118
8119 case OR_No_Viable_Function:
8120 // No viable function; fall through to handling this as a
8121 // built-in operator, which will produce an error message for us.
8122 break;
8123
8124 case OR_Ambiguous:
8125 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8126 << UnaryOperator::getOpcodeStr(Opc)
8127 << Input->getType()
8128 << Input->getSourceRange();
8129 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8130 Args, NumArgs,
8131 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8132 return ExprError();
8133
8134 case OR_Deleted:
8135 Diag(OpLoc, diag::err_ovl_deleted_oper)
8136 << Best->Function->isDeleted()
8137 << UnaryOperator::getOpcodeStr(Opc)
8138 << getDeletedOrUnavailableSuffix(Best->Function)
8139 << Input->getSourceRange();
8140 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8141 return ExprError();
8142 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008143
8144 // Either we found no viable overloaded operator or we matched a
8145 // built-in operator. In either case, fall through to trying to
8146 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008147 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008148}
8149
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008150/// \brief Create a binary operation that may resolve to an overloaded
8151/// operator.
8152///
8153/// \param OpLoc The location of the operator itself (e.g., '+').
8154///
8155/// \param OpcIn The BinaryOperator::Opcode that describes this
8156/// operator.
8157///
8158/// \param Functions The set of non-member functions that will be
8159/// considered by overload resolution. The caller needs to build this
8160/// set based on the context using, e.g.,
8161/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8162/// set should not contain any member functions; those will be added
8163/// by CreateOverloadedBinOp().
8164///
8165/// \param LHS Left-hand argument.
8166/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008167ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008168Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008169 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008170 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008171 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008172 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008173 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008174
8175 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8176 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8177 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8178
8179 // If either side is type-dependent, create an appropriate dependent
8180 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008181 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008182 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008183 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008184 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008185 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008186 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008187 Context.DependentTy,
8188 VK_RValue, OK_Ordinary,
8189 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008190
Douglas Gregor5287f092009-11-05 00:51:44 +00008191 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8192 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008193 VK_LValue,
8194 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008195 Context.DependentTy,
8196 Context.DependentTy,
8197 OpLoc));
8198 }
John McCall4c4c1df2010-01-26 03:27:55 +00008199
8200 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008201 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008202 // TODO: provide better source location info in DNLoc component.
8203 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008204 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008205 = UnresolvedLookupExpr::Create(Context, NamingClass,
8206 NestedNameSpecifierLoc(), OpNameInfo,
8207 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008208 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008209 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008210 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008211 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008212 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008213 OpLoc));
8214 }
8215
John McCalle26a8722010-12-04 08:14:53 +00008216 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008217 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8218 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8219 if (Result.isInvalid())
8220 return ExprError();
8221 Args[1] = Result.take();
8222 }
John McCalle26a8722010-12-04 08:14:53 +00008223
8224 // The LHS is more complicated.
8225 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8226
8227 // There's a tension for assignment operators between primitive
8228 // property assignment and the overloaded operators.
8229 if (BinaryOperator::isAssignmentOp(Opc)) {
8230 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8231
8232 // Is the property "logically" settable?
8233 bool Settable = (PRE->isExplicitProperty() ||
8234 PRE->getImplicitPropertySetter());
8235
8236 // To avoid gratuitously inventing semantics, use the primitive
8237 // unless it isn't. Thoughts in case we ever really care:
8238 // - If the property isn't logically settable, we have to
8239 // load and hope.
8240 // - If the property is settable and this is simple assignment,
8241 // we really should use the primitive.
8242 // - If the property is settable, then we could try overloading
8243 // on a generic lvalue of the appropriate type; if it works
8244 // out to a builtin candidate, we would do that same operation
8245 // on the property, and otherwise just error.
8246 if (Settable)
8247 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8248 }
8249
John Wiegley01296292011-04-08 18:41:53 +00008250 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8251 if (Result.isInvalid())
8252 return ExprError();
8253 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008254 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008255
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008256 // If this is the assignment operator, we only perform overload resolution
8257 // if the left-hand side is a class or enumeration type. This is actually
8258 // a hack. The standard requires that we do overload resolution between the
8259 // various built-in candidates, but as DR507 points out, this can lead to
8260 // problems. So we do it this way, which pretty much follows what GCC does.
8261 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008262 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008263 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008264
John McCalle26a8722010-12-04 08:14:53 +00008265 // If this is the .* operator, which is not overloadable, just
8266 // create a built-in binary operator.
8267 if (Opc == BO_PtrMemD)
8268 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8269
Douglas Gregor084d8552009-03-13 23:49:33 +00008270 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008271 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008272
8273 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008274 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008275
8276 // Add operator candidates that are member functions.
8277 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8278
John McCall4c4c1df2010-01-26 03:27:55 +00008279 // Add candidates from ADL.
8280 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8281 Args, 2,
8282 /*ExplicitTemplateArgs*/ 0,
8283 CandidateSet);
8284
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008285 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008286 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008287
8288 // Perform overload resolution.
8289 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008290 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008291 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008292 // We found a built-in operator or an overloaded operator.
8293 FunctionDecl *FnDecl = Best->Function;
8294
8295 if (FnDecl) {
8296 // We matched an overloaded operator. Build a call to that
8297 // operator.
8298
Chandler Carruth30141632011-02-25 19:41:05 +00008299 MarkDeclarationReferenced(OpLoc, FnDecl);
8300
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008301 // Convert the arguments.
8302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008303 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008304 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008305
Chandler Carruth8e543b32010-12-12 08:17:55 +00008306 ExprResult Arg1 =
8307 PerformCopyInitialization(
8308 InitializedEntity::InitializeParameter(Context,
8309 FnDecl->getParamDecl(0)),
8310 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008311 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008312 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008313
John Wiegley01296292011-04-08 18:41:53 +00008314 ExprResult Arg0 =
8315 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8316 Best->FoundDecl, Method);
8317 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008318 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008319 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008320 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008321 } else {
8322 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008323 ExprResult Arg0 = PerformCopyInitialization(
8324 InitializedEntity::InitializeParameter(Context,
8325 FnDecl->getParamDecl(0)),
8326 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008327 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008328 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008329
Chandler Carruth8e543b32010-12-12 08:17:55 +00008330 ExprResult Arg1 =
8331 PerformCopyInitialization(
8332 InitializedEntity::InitializeParameter(Context,
8333 FnDecl->getParamDecl(1)),
8334 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008335 if (Arg1.isInvalid())
8336 return ExprError();
8337 Args[0] = LHS = Arg0.takeAs<Expr>();
8338 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008339 }
8340
John McCall4fa0d5f2010-05-06 18:15:07 +00008341 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8342
John McCall7decc9e2010-11-18 06:31:45 +00008343 // Determine the result type.
8344 QualType ResultTy = FnDecl->getResultType();
8345 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8346 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008347
8348 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008349 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8350 if (FnExpr.isInvalid())
8351 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008352
John McCallb268a282010-08-23 23:25:46 +00008353 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008354 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008355 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008356
8357 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008358 FnDecl))
8359 return ExprError();
8360
John McCallb268a282010-08-23 23:25:46 +00008361 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008362 } else {
8363 // We matched a built-in operator. Convert the arguments, then
8364 // break out so that we will build the appropriate built-in
8365 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008366 ExprResult ArgsRes0 =
8367 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8368 Best->Conversions[0], AA_Passing);
8369 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008370 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008371 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008372
John Wiegley01296292011-04-08 18:41:53 +00008373 ExprResult ArgsRes1 =
8374 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8375 Best->Conversions[1], AA_Passing);
8376 if (ArgsRes1.isInvalid())
8377 return ExprError();
8378 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008379 break;
8380 }
8381 }
8382
Douglas Gregor66950a32009-09-30 21:46:01 +00008383 case OR_No_Viable_Function: {
8384 // C++ [over.match.oper]p9:
8385 // If the operator is the operator , [...] and there are no
8386 // viable functions, then the operator is assumed to be the
8387 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008388 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008389 break;
8390
Chandler Carruth8e543b32010-12-12 08:17:55 +00008391 // For class as left operand for assignment or compound assigment
8392 // operator do not fall through to handling in built-in, but report that
8393 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008394 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008395 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008396 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008397 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8398 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008399 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008400 } else {
8401 // No viable function; try to create a built-in operation, which will
8402 // produce an error. Then, show the non-viable candidates.
8403 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008405 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008406 "C++ binary operator overloading is missing candidates!");
8407 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008408 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8409 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008410 return move(Result);
8411 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008412
8413 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008414 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008415 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008416 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008417 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008418 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8419 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008420 return ExprError();
8421
8422 case OR_Deleted:
8423 Diag(OpLoc, diag::err_ovl_deleted_oper)
8424 << Best->Function->isDeleted()
8425 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008426 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008427 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008428 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008429 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008430 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008431
Douglas Gregor66950a32009-09-30 21:46:01 +00008432 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008433 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008434}
8435
John McCalldadc5752010-08-24 06:29:42 +00008436ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008437Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8438 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008439 Expr *Base, Expr *Idx) {
8440 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008441 DeclarationName OpName =
8442 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8443
8444 // If either side is type-dependent, create an appropriate dependent
8445 // expression.
8446 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8447
John McCall58cc69d2010-01-27 01:50:18 +00008448 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008449 // CHECKME: no 'operator' keyword?
8450 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8451 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008452 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008453 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008454 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008455 /*ADL*/ true, /*Overloaded*/ false,
8456 UnresolvedSetIterator(),
8457 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008458 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008459
Sebastian Redladba46e2009-10-29 20:17:01 +00008460 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8461 Args, 2,
8462 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008463 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008464 RLoc));
8465 }
8466
John Wiegley01296292011-04-08 18:41:53 +00008467 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8468 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8469 if (Result.isInvalid())
8470 return ExprError();
8471 Args[0] = Result.take();
8472 }
8473 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8474 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8475 if (Result.isInvalid())
8476 return ExprError();
8477 Args[1] = Result.take();
8478 }
John McCalle26a8722010-12-04 08:14:53 +00008479
Sebastian Redladba46e2009-10-29 20:17:01 +00008480 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008481 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008482
8483 // Subscript can only be overloaded as a member function.
8484
8485 // Add operator candidates that are member functions.
8486 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8487
8488 // Add builtin operator candidates.
8489 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8490
8491 // Perform overload resolution.
8492 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008493 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008494 case OR_Success: {
8495 // We found a built-in operator or an overloaded operator.
8496 FunctionDecl *FnDecl = Best->Function;
8497
8498 if (FnDecl) {
8499 // We matched an overloaded operator. Build a call to that
8500 // operator.
8501
Chandler Carruth30141632011-02-25 19:41:05 +00008502 MarkDeclarationReferenced(LLoc, FnDecl);
8503
John McCalla0296f72010-03-19 07:35:19 +00008504 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008505 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008506
Sebastian Redladba46e2009-10-29 20:17:01 +00008507 // Convert the arguments.
8508 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00008509 ExprResult Arg0 =
8510 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8511 Best->FoundDecl, Method);
8512 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008513 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008514 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008515
Anders Carlssona68e51e2010-01-29 18:37:50 +00008516 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008517 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008518 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008519 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008520 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008521 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008522 Owned(Args[1]));
8523 if (InputInit.isInvalid())
8524 return ExprError();
8525
8526 Args[1] = InputInit.takeAs<Expr>();
8527
Sebastian Redladba46e2009-10-29 20:17:01 +00008528 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008529 QualType ResultTy = FnDecl->getResultType();
8530 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8531 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008532
8533 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008534 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8535 if (FnExpr.isInvalid())
8536 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008537
John McCallb268a282010-08-23 23:25:46 +00008538 CXXOperatorCallExpr *TheCall =
8539 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00008540 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008541 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008542
John McCallb268a282010-08-23 23:25:46 +00008543 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008544 FnDecl))
8545 return ExprError();
8546
John McCallb268a282010-08-23 23:25:46 +00008547 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008548 } else {
8549 // We matched a built-in operator. Convert the arguments, then
8550 // break out so that we will build the appropriate built-in
8551 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008552 ExprResult ArgsRes0 =
8553 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8554 Best->Conversions[0], AA_Passing);
8555 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008556 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008557 Args[0] = ArgsRes0.take();
8558
8559 ExprResult ArgsRes1 =
8560 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8561 Best->Conversions[1], AA_Passing);
8562 if (ArgsRes1.isInvalid())
8563 return ExprError();
8564 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008565
8566 break;
8567 }
8568 }
8569
8570 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008571 if (CandidateSet.empty())
8572 Diag(LLoc, diag::err_ovl_no_oper)
8573 << Args[0]->getType() << /*subscript*/ 0
8574 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8575 else
8576 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8577 << Args[0]->getType()
8578 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008579 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8580 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008581 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008582 }
8583
8584 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008585 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008586 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008587 << Args[0]->getType() << Args[1]->getType()
8588 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008589 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8590 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008591 return ExprError();
8592
8593 case OR_Deleted:
8594 Diag(LLoc, diag::err_ovl_deleted_oper)
8595 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008596 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00008597 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008598 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8599 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008600 return ExprError();
8601 }
8602
8603 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008604 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008605}
8606
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008607/// BuildCallToMemberFunction - Build a call to a member
8608/// function. MemExpr is the expression that refers to the member
8609/// function (and includes the object parameter), Args/NumArgs are the
8610/// arguments to the function call (not including the object
8611/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00008612/// expression refers to a non-static member function or an overloaded
8613/// member function.
John McCalldadc5752010-08-24 06:29:42 +00008614ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008615Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8616 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008617 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00008618 assert(MemExprE->getType() == Context.BoundMemberTy ||
8619 MemExprE->getType() == Context.OverloadTy);
8620
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008621 // Dig out the member expression. This holds both the object
8622 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008623 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008624
John McCall0009fcc2011-04-26 20:42:42 +00008625 // Determine whether this is a call to a pointer-to-member function.
8626 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
8627 assert(op->getType() == Context.BoundMemberTy);
8628 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
8629
8630 QualType fnType =
8631 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
8632
8633 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
8634 QualType resultType = proto->getCallResultType(Context);
8635 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
8636
8637 // Check that the object type isn't more qualified than the
8638 // member function we're calling.
8639 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
8640
8641 QualType objectType = op->getLHS()->getType();
8642 if (op->getOpcode() == BO_PtrMemI)
8643 objectType = objectType->castAs<PointerType>()->getPointeeType();
8644 Qualifiers objectQuals = objectType.getQualifiers();
8645
8646 Qualifiers difference = objectQuals - funcQuals;
8647 difference.removeObjCGCAttr();
8648 difference.removeAddressSpace();
8649 if (difference) {
8650 std::string qualsString = difference.getAsString();
8651 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
8652 << fnType.getUnqualifiedType()
8653 << qualsString
8654 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
8655 }
8656
8657 CXXMemberCallExpr *call
8658 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
8659 resultType, valueKind, RParenLoc);
8660
8661 if (CheckCallReturnType(proto->getResultType(),
8662 op->getRHS()->getSourceRange().getBegin(),
8663 call, 0))
8664 return ExprError();
8665
8666 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
8667 return ExprError();
8668
8669 return MaybeBindToTemporary(call);
8670 }
8671
John McCall10eae182009-11-30 22:42:35 +00008672 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008673 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008674 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008675 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008676 if (isa<MemberExpr>(NakedMemExpr)) {
8677 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008678 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008679 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008680 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008681 } else {
8682 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008683 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008684
John McCall6e9f8f62009-12-03 04:06:58 +00008685 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008686 Expr::Classification ObjectClassification
8687 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8688 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008689
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008690 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008691 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008692
John McCall2d74de92009-12-01 22:10:20 +00008693 // FIXME: avoid copy.
8694 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8695 if (UnresExpr->hasExplicitTemplateArgs()) {
8696 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8697 TemplateArgs = &TemplateArgsBuffer;
8698 }
8699
John McCall10eae182009-11-30 22:42:35 +00008700 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8701 E = UnresExpr->decls_end(); I != E; ++I) {
8702
John McCall6e9f8f62009-12-03 04:06:58 +00008703 NamedDecl *Func = *I;
8704 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8705 if (isa<UsingShadowDecl>(Func))
8706 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8707
Douglas Gregor02824322011-01-26 19:30:28 +00008708
Francois Pichet64225792011-01-18 05:04:39 +00008709 // Microsoft supports direct constructor calls.
8710 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8711 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8712 CandidateSet);
8713 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008714 // If explicit template arguments were provided, we can't call a
8715 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008716 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008717 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008718
John McCalla0296f72010-03-19 07:35:19 +00008719 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008720 ObjectClassification,
8721 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00008722 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008723 } else {
John McCall10eae182009-11-30 22:42:35 +00008724 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008725 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008726 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00008727 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008728 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008729 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008730 }
Mike Stump11289f42009-09-09 15:08:12 +00008731
John McCall10eae182009-11-30 22:42:35 +00008732 DeclarationName DeclName = UnresExpr->getMemberName();
8733
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008734 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008735 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008736 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008737 case OR_Success:
8738 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00008739 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00008740 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008741 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008742 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008743 break;
8744
8745 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008746 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008747 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008748 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008749 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008750 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008751 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008752
8753 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008754 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008755 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008756 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008757 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008758 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008759
8760 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008761 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008762 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008763 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008764 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008765 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008766 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008767 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008768 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008769 }
8770
John McCall16df1e52010-03-30 21:47:33 +00008771 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008772
John McCall2d74de92009-12-01 22:10:20 +00008773 // If overload resolution picked a static member, build a
8774 // non-member call based on that function.
8775 if (Method->isStatic()) {
8776 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8777 Args, NumArgs, RParenLoc);
8778 }
8779
John McCall10eae182009-11-30 22:42:35 +00008780 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008781 }
8782
John McCall7decc9e2010-11-18 06:31:45 +00008783 QualType ResultType = Method->getResultType();
8784 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8785 ResultType = ResultType.getNonLValueExprType(Context);
8786
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008787 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008788 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00008789 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008790 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008791
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008792 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008793 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008794 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008795 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008796
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008797 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008798 // We only need to do this if there was actually an overload; otherwise
8799 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00008800 if (!Method->isStatic()) {
8801 ExprResult ObjectArg =
8802 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
8803 FoundDecl, Method);
8804 if (ObjectArg.isInvalid())
8805 return ExprError();
8806 MemExpr->setBase(ObjectArg.take());
8807 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008808
8809 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008810 const FunctionProtoType *Proto =
8811 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008812 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008813 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008814 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008815
John McCallb268a282010-08-23 23:25:46 +00008816 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008817 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008818
Anders Carlsson47061ee2011-05-06 14:25:31 +00008819 if ((isa<CXXConstructorDecl>(CurContext) ||
8820 isa<CXXDestructorDecl>(CurContext)) &&
8821 TheCall->getMethodDecl()->isPure()) {
8822 const CXXMethodDecl *MD = TheCall->getMethodDecl();
8823
8824 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()))
8825 Diag(MemExpr->getLocStart(),
8826 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
8827 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
8828 << MD->getParent()->getDeclName();
8829
8830 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
8831 }
John McCallb268a282010-08-23 23:25:46 +00008832 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008833}
8834
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008835/// BuildCallToObjectOfClassType - Build a call to an object of class
8836/// type (C++ [over.call.object]), which can end up invoking an
8837/// overloaded function call operator (@c operator()) or performing a
8838/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008839ExprResult
John Wiegley01296292011-04-08 18:41:53 +00008840Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008841 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008842 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008843 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00008844 ExprResult Object = Owned(Obj);
8845 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
8846 Object = ConvertPropertyForRValue(Object.take());
8847 if (Object.isInvalid())
8848 return ExprError();
8849 }
John McCalle26a8722010-12-04 08:14:53 +00008850
John Wiegley01296292011-04-08 18:41:53 +00008851 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
8852 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008853
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008854 // C++ [over.call.object]p1:
8855 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008856 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008857 // candidate functions includes at least the function call
8858 // operators of T. The function call operators of T are obtained by
8859 // ordinary lookup of the name operator() in the context of
8860 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008861 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008862 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008863
John Wiegley01296292011-04-08 18:41:53 +00008864 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008865 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008866 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008867 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008868
John McCall27b18f82009-11-17 02:14:36 +00008869 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8870 LookupQualifiedName(R, Record->getDecl());
8871 R.suppressDiagnostics();
8872
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008873 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008874 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00008875 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
8876 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008877 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008878 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008879
Douglas Gregorab7897a2008-11-19 22:57:39 +00008880 // C++ [over.call.object]p2:
8881 // In addition, for each conversion function declared in T of the
8882 // form
8883 //
8884 // operator conversion-type-id () cv-qualifier;
8885 //
8886 // where cv-qualifier is the same cv-qualification as, or a
8887 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008888 // denotes the type "pointer to function of (P1,...,Pn) returning
8889 // R", or the type "reference to pointer to function of
8890 // (P1,...,Pn) returning R", or the type "reference to function
8891 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008892 // is also considered as a candidate function. Similarly,
8893 // surrogate call functions are added to the set of candidate
8894 // functions for each conversion function declared in an
8895 // accessible base class provided the function is not hidden
8896 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008897 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008898 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008899 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008900 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008901 NamedDecl *D = *I;
8902 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8903 if (isa<UsingShadowDecl>(D))
8904 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008905
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008906 // Skip over templated conversion functions; they aren't
8907 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008908 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008909 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008910
John McCall6e9f8f62009-12-03 04:06:58 +00008911 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008912
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008913 // Strip the reference type (if any) and then the pointer type (if
8914 // any) to get down to what might be a function type.
8915 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8916 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8917 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008918
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008919 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008920 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John Wiegley01296292011-04-08 18:41:53 +00008921 Object.get(), Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008922 }
Mike Stump11289f42009-09-09 15:08:12 +00008923
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008924 // Perform overload resolution.
8925 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00008926 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00008927 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008928 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008929 // Overload resolution succeeded; we'll build the appropriate call
8930 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008931 break;
8932
8933 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008934 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00008935 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8936 << Object.get()->getType() << /*call*/ 1
8937 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00008938 else
John Wiegley01296292011-04-08 18:41:53 +00008939 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00008940 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008941 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008942 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008943 break;
8944
8945 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00008946 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008947 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008948 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008949 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008950 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008951
8952 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00008953 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00008954 diag::err_ovl_deleted_object_call)
8955 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00008956 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008957 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00008958 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008959 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008960 break;
Mike Stump11289f42009-09-09 15:08:12 +00008961 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008962
Douglas Gregorb412e172010-07-25 18:17:45 +00008963 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008964 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008965
Douglas Gregorab7897a2008-11-19 22:57:39 +00008966 if (Best->Function == 0) {
8967 // Since there is no function declaration, this is one of the
8968 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008969 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008970 = cast<CXXConversionDecl>(
8971 Best->Conversions[0].UserDefined.ConversionFunction);
8972
John Wiegley01296292011-04-08 18:41:53 +00008973 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008974 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008975
Douglas Gregorab7897a2008-11-19 22:57:39 +00008976 // We selected one of the surrogate functions that converts the
8977 // object parameter to a function pointer. Perform the conversion
8978 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008979
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008980 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008981 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00008982 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00008983 if (Call.isInvalid())
8984 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008985
Douglas Gregor668443e2011-01-20 00:18:04 +00008986 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008987 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008988 }
8989
Chandler Carruth30141632011-02-25 19:41:05 +00008990 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00008991 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008992 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008993
Douglas Gregorab7897a2008-11-19 22:57:39 +00008994 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8995 // that calls this method, using Object for the implicit object
8996 // parameter and passing along the remaining arguments.
8997 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008998 const FunctionProtoType *Proto =
8999 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009000
9001 unsigned NumArgsInProto = Proto->getNumArgs();
9002 unsigned NumArgsToCheck = NumArgs;
9003
9004 // Build the full argument list for the method call (the
9005 // implicit object parameter is placed at the beginning of the
9006 // list).
9007 Expr **MethodArgs;
9008 if (NumArgs < NumArgsInProto) {
9009 NumArgsToCheck = NumArgsInProto;
9010 MethodArgs = new Expr*[NumArgsInProto + 1];
9011 } else {
9012 MethodArgs = new Expr*[NumArgs + 1];
9013 }
John Wiegley01296292011-04-08 18:41:53 +00009014 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009015 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9016 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009017
John Wiegley01296292011-04-08 18:41:53 +00009018 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9019 if (NewFn.isInvalid())
9020 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009021
9022 // Once we've built TheCall, all of the expressions are properly
9023 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009024 QualType ResultTy = Method->getResultType();
9025 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9026 ResultTy = ResultTy.getNonLValueExprType(Context);
9027
John McCallb268a282010-08-23 23:25:46 +00009028 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009029 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009030 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009031 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009032 delete [] MethodArgs;
9033
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009034 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009035 Method))
9036 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009037
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009038 // We may have default arguments. If so, we need to allocate more
9039 // slots in the call for them.
9040 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009041 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009042 else if (NumArgs > NumArgsInProto)
9043 NumArgsToCheck = NumArgsInProto;
9044
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009045 bool IsError = false;
9046
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009047 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009048 ExprResult ObjRes =
9049 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9050 Best->FoundDecl, Method);
9051 if (ObjRes.isInvalid())
9052 IsError = true;
9053 else
9054 Object = move(ObjRes);
9055 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009056
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009057 // Check the argument types.
9058 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009059 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009060 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009061 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009062
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009063 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009064
John McCalldadc5752010-08-24 06:29:42 +00009065 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009066 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009067 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009068 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009069 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009070
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009071 IsError |= InputInit.isInvalid();
9072 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009073 } else {
John McCalldadc5752010-08-24 06:29:42 +00009074 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009075 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9076 if (DefArg.isInvalid()) {
9077 IsError = true;
9078 break;
9079 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009080
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009081 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009082 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009083
9084 TheCall->setArg(i + 1, Arg);
9085 }
9086
9087 // If this is a variadic call, handle args passed through "...".
9088 if (Proto->isVariadic()) {
9089 // Promote the arguments (C99 6.5.2.2p7).
9090 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009091 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9092 IsError |= Arg.isInvalid();
9093 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009094 }
9095 }
9096
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009097 if (IsError) return true;
9098
John McCallb268a282010-08-23 23:25:46 +00009099 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009100 return true;
9101
John McCalle172be52010-08-24 06:09:16 +00009102 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009103}
9104
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009105/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009106/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009107/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009108ExprResult
John McCallb268a282010-08-23 23:25:46 +00009109Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009110 assert(Base->getType()->isRecordType() &&
9111 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009112
John Wiegley01296292011-04-08 18:41:53 +00009113 if (Base->getObjectKind() == OK_ObjCProperty) {
9114 ExprResult Result = ConvertPropertyForRValue(Base);
9115 if (Result.isInvalid())
9116 return ExprError();
9117 Base = Result.take();
9118 }
John McCalle26a8722010-12-04 08:14:53 +00009119
John McCallbc077cf2010-02-08 23:07:23 +00009120 SourceLocation Loc = Base->getExprLoc();
9121
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009122 // C++ [over.ref]p1:
9123 //
9124 // [...] An expression x->m is interpreted as (x.operator->())->m
9125 // for a class object x of type T if T::operator->() exists and if
9126 // the operator is selected as the best match function by the
9127 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009128 DeclarationName OpName =
9129 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009130 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009131 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009132
John McCallbc077cf2010-02-08 23:07:23 +00009133 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009134 PDiag(diag::err_typecheck_incomplete_tag)
9135 << Base->getSourceRange()))
9136 return ExprError();
9137
John McCall27b18f82009-11-17 02:14:36 +00009138 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9139 LookupQualifiedName(R, BaseRecord->getDecl());
9140 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009141
9142 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009143 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009144 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9145 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009146 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009147
9148 // Perform overload resolution.
9149 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009150 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009151 case OR_Success:
9152 // Overload resolution succeeded; we'll build the call below.
9153 break;
9154
9155 case OR_No_Viable_Function:
9156 if (CandidateSet.empty())
9157 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009158 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009159 else
9160 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009161 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009162 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009163 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009164
9165 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009166 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9167 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009168 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009169 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009170
9171 case OR_Deleted:
9172 Diag(OpLoc, diag::err_ovl_deleted_oper)
9173 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009174 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009175 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009176 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009177 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009178 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009179 }
9180
Chandler Carruth30141632011-02-25 19:41:05 +00009181 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009182 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009183 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009184
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009185 // Convert the object parameter.
9186 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009187 ExprResult BaseResult =
9188 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9189 Best->FoundDecl, Method);
9190 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009191 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009192 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009193
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009194 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009195 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9196 if (FnExpr.isInvalid())
9197 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009198
John McCall7decc9e2010-11-18 06:31:45 +00009199 QualType ResultTy = Method->getResultType();
9200 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9201 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009202 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009203 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009204 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009205
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009206 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009207 Method))
9208 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009209
9210 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009211}
9212
Douglas Gregorcd695e52008-11-10 20:40:00 +00009213/// FixOverloadedFunctionReference - E is an expression that refers to
9214/// a C++ overloaded function (possibly with some parentheses and
9215/// perhaps a '&' around it). We have resolved the overloaded function
9216/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009217/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009218Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009219 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009220 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009221 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9222 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009223 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009224 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009225
Douglas Gregor51c538b2009-11-20 19:42:02 +00009226 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009227 }
9228
Douglas Gregor51c538b2009-11-20 19:42:02 +00009229 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009230 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9231 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009232 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009233 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009234 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009235 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009236 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009237 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009238
9239 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009240 ICE->getCastKind(),
9241 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009242 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009243 }
9244
Douglas Gregor51c538b2009-11-20 19:42:02 +00009245 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009246 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009247 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009248 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9249 if (Method->isStatic()) {
9250 // Do nothing: static member functions aren't any different
9251 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009252 } else {
John McCalle66edc12009-11-24 19:00:30 +00009253 // Fix the sub expression, which really has to be an
9254 // UnresolvedLookupExpr holding an overloaded member function
9255 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009256 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9257 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009258 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009259 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009260
John McCalld14a8642009-11-21 08:51:07 +00009261 assert(isa<DeclRefExpr>(SubExpr)
9262 && "fixed to something other than a decl ref");
9263 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9264 && "fixed to a member ref with no nested name qualifier");
9265
9266 // We have taken the address of a pointer to member
9267 // function. Perform the computation here so that we get the
9268 // appropriate pointer to member type.
9269 QualType ClassType
9270 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9271 QualType MemPtrType
9272 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9273
John McCall7decc9e2010-11-18 06:31:45 +00009274 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9275 VK_RValue, OK_Ordinary,
9276 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009277 }
9278 }
John McCall16df1e52010-03-30 21:47:33 +00009279 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9280 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009281 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009282 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009283
John McCalle3027922010-08-25 11:45:40 +00009284 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009285 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009286 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009287 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009288 }
John McCalld14a8642009-11-21 08:51:07 +00009289
9290 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009291 // FIXME: avoid copy.
9292 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009293 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009294 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9295 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009296 }
9297
John McCalld14a8642009-11-21 08:51:07 +00009298 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009299 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009300 Fn,
9301 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009302 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009303 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009304 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009305 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009306 }
9307
John McCall10eae182009-11-30 22:42:35 +00009308 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009309 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009310 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9311 if (MemExpr->hasExplicitTemplateArgs()) {
9312 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9313 TemplateArgs = &TemplateArgsBuffer;
9314 }
John McCall6b51f282009-11-23 01:53:49 +00009315
John McCall2d74de92009-12-01 22:10:20 +00009316 Expr *Base;
9317
John McCall7decc9e2010-11-18 06:31:45 +00009318 // If we're filling in a static method where we used to have an
9319 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009320 if (MemExpr->isImplicitAccess()) {
9321 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9322 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009323 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009324 Fn,
9325 MemExpr->getMemberLoc(),
9326 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009327 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009328 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009329 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009330 } else {
9331 SourceLocation Loc = MemExpr->getMemberLoc();
9332 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009333 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009334 Base = new (Context) CXXThisExpr(Loc,
9335 MemExpr->getBaseType(),
9336 /*isImplicit=*/true);
9337 }
John McCall2d74de92009-12-01 22:10:20 +00009338 } else
John McCallc3007a22010-10-26 07:05:15 +00009339 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009340
John McCall4adb38c2011-04-27 00:36:17 +00009341 ExprValueKind valueKind;
9342 QualType type;
9343 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9344 valueKind = VK_LValue;
9345 type = Fn->getType();
9346 } else {
9347 valueKind = VK_RValue;
9348 type = Context.BoundMemberTy;
9349 }
9350
John McCall2d74de92009-12-01 22:10:20 +00009351 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009352 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009353 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009354 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009355 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009356 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009357 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009358 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009360
John McCallc3007a22010-10-26 07:05:15 +00009361 llvm_unreachable("Invalid reference to overloaded function");
9362 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009363}
9364
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009365ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009366 DeclAccessPair Found,
9367 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009368 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009369}
9370
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009371} // end namespace clang