blob: 2706aeaf1d9a5f9da1df76c0a64f076ab4c86811 [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
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000052}
53
John McCall5c32be02010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000202}
203
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000242bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261/// DebugPrint - Print this standard conversion sequence to standard
262/// error. Useful for debugging overloading issues.
263void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000264 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 bool PrintedSomething = false;
266 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000268 PrintedSomething = true;
269 }
270
271 if (Second != ICK_Identity) {
272 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000273 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000275 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000276
277 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000279 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000281 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000282 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000283 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 PrintedSomething = true;
285 }
286
287 if (Third != ICK_Identity) {
288 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000289 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000290 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000291 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000292 PrintedSomething = true;
293 }
294
295 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000296 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000297 }
298}
299
300/// DebugPrint - Print this user-defined conversion sequence to standard
301/// error. Useful for debugging overloading issues.
302void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000303 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304 if (Before.First || Before.Second || Before.Third) {
305 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000306 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000307 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000308 if (ConversionFunction)
309 OS << '\'' << *ConversionFunction << '\'';
310 else
311 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000312 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000313 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000314 After.DebugPrint();
315 }
316}
317
318/// DebugPrint - Print this implicit conversion sequence to standard
319/// error. Useful for debugging overloading issues.
320void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000322 switch (ConversionKind) {
323 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000324 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000325 Standard.DebugPrint();
326 break;
327 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000328 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329 UserDefined.DebugPrint();
330 break;
331 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000332 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000333 break;
John McCall0d1da222010-01-12 00:44:57 +0000334 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000335 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000336 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000338 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 break;
340 }
341
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000342 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000343}
344
John McCall0d1da222010-01-12 00:44:57 +0000345void AmbiguousConversionSequence::construct() {
346 new (&conversions()) ConversionSet();
347}
348
349void AmbiguousConversionSequence::destruct() {
350 conversions().~ConversionSet();
351}
352
353void
354AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
355 FromTypePtr = O.FromTypePtr;
356 ToTypePtr = O.ToTypePtr;
357 new (&conversions()) ConversionSet(O.conversions());
358}
359
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360namespace {
361 // Structure used by OverloadCandidate::DeductionFailureInfo to store
362 // template parameter and template argument information.
363 struct DFIParamWithArguments {
364 TemplateParameter Param;
365 TemplateArgument FirstArg;
366 TemplateArgument SecondArg;
367 };
368}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370/// \brief Convert from Sema's representation of template deduction information
371/// to the form used in overload-candidate information.
372OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000373static MakeDeductionFailureInfo(ASTContext &Context,
374 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000375 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 OverloadCandidate::DeductionFailureInfo Result;
377 Result.Result = static_cast<unsigned>(TDK);
378 Result.Data = 0;
379 switch (TDK) {
380 case Sema::TDK_Success:
381 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000382 case Sema::TDK_TooManyArguments:
383 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000387 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 Result.Data = Info.Param.getOpaqueValue();
389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000391 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000392 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000393 // FIXME: Should allocate from normal heap so that we can free this later.
394 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 Saved->Param = Info.Param;
396 Saved->FirstArg = Info.FirstArg;
397 Saved->SecondArg = Info.SecondArg;
398 Result.Data = Saved;
399 break;
400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000401
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000402 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000403 Result.Data = Info.take();
404 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000407 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000408 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411 return Result;
412}
John McCall0d1da222010-01-12 00:44:57 +0000413
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000414void OverloadCandidate::DeductionFailureInfo::Destroy() {
415 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
416 case Sema::TDK_Success:
417 case Sema::TDK_InstantiationDepth:
418 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000419 case Sema::TDK_TooManyArguments:
420 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000421 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000423
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000424 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000425 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000426 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000427 Data = 0;
428 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000429
430 case Sema::TDK_SubstitutionFailure:
431 // FIXME: Destroy the template arugment list?
432 Data = 0;
433 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor461761d2010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
442TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000443OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
444 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
445 case Sema::TDK_Success:
446 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000447 case Sema::TDK_TooManyArguments:
448 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000449 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000450 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000453 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000455
456 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000465
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000466 return TemplateParameter();
467}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Douglas Gregord09efd42010-05-08 20:07:26 +0000469TemplateArgumentList *
470OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
471 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
472 case Sema::TDK_Success:
473 case Sema::TDK_InstantiationDepth:
474 case Sema::TDK_TooManyArguments:
475 case Sema::TDK_TooFewArguments:
476 case Sema::TDK_Incomplete:
477 case Sema::TDK_InvalidExplicitArguments:
478 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000479 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000480 return 0;
481
482 case Sema::TDK_SubstitutionFailure:
483 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000484
Douglas Gregord09efd42010-05-08 20:07:26 +0000485 // Unhandled
486 case Sema::TDK_NonDeducedMismatch:
487 case Sema::TDK_FailedOverloadResolution:
488 break;
489 }
490
491 return 0;
492}
493
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
495 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
496 case Sema::TDK_Success:
497 case Sema::TDK_InstantiationDepth:
498 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000499 case Sema::TDK_TooManyArguments:
500 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000501 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000502 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503 return 0;
504
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000506 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000508
Douglas Gregor461761d2010-05-08 18:20:53 +0000509 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000510 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000511 case Sema::TDK_FailedOverloadResolution:
512 break;
513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000514
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000515 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000516}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000517
518const TemplateArgument *
519OverloadCandidate::DeductionFailureInfo::getSecondArg() {
520 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
521 case Sema::TDK_Success:
522 case Sema::TDK_InstantiationDepth:
523 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000524 case Sema::TDK_TooManyArguments:
525 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000526 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000527 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000528 return 0;
529
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000531 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000532 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
533
Douglas Gregor461761d2010-05-08 18:20:53 +0000534 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000536 case Sema::TDK_FailedOverloadResolution:
537 break;
538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000540 return 0;
541}
542
543void OverloadCandidateSet::clear() {
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000544 for (unsigned i = 0, e = NumInlineSequences; i != e; ++i)
545 reinterpret_cast<ImplicitConversionSequence*>(InlineSpace)[i]
546 .~ImplicitConversionSequence();
547 NumInlineSequences = 0;
548 ConversionSequenceAllocator.DestroyAll();
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000549 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000550 Functions.clear();
551}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000552
John McCall4124c492011-10-17 18:40:02 +0000553namespace {
554 class UnbridgedCastsSet {
555 struct Entry {
556 Expr **Addr;
557 Expr *Saved;
558 };
559 SmallVector<Entry, 2> Entries;
560
561 public:
562 void save(Sema &S, Expr *&E) {
563 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
564 Entry entry = { &E, E };
565 Entries.push_back(entry);
566 E = S.stripARCUnbridgedCast(E);
567 }
568
569 void restore() {
570 for (SmallVectorImpl<Entry>::iterator
571 i = Entries.begin(), e = Entries.end(); i != e; ++i)
572 *i->Addr = i->Saved;
573 }
574 };
575}
576
577/// checkPlaceholderForOverload - Do any interesting placeholder-like
578/// preprocessing on the given expression.
579///
580/// \param unbridgedCasts a collection to which to add unbridged casts;
581/// without this, they will be immediately diagnosed as errors
582///
583/// Return true on unrecoverable error.
584static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
585 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000586 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
587 // We can't handle overloaded expressions here because overload
588 // resolution might reasonably tweak them.
589 if (placeholder->getKind() == BuiltinType::Overload) return false;
590
591 // If the context potentially accepts unbridged ARC casts, strip
592 // the unbridged cast and add it to the collection for later restoration.
593 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
594 unbridgedCasts) {
595 unbridgedCasts->save(S, E);
596 return false;
597 }
598
599 // Go ahead and check everything else.
600 ExprResult result = S.CheckPlaceholderExpr(E);
601 if (result.isInvalid())
602 return true;
603
604 E = result.take();
605 return false;
606 }
607
608 // Nothing to do.
609 return false;
610}
611
612/// checkArgPlaceholdersForOverload - Check a set of call operands for
613/// placeholders.
614static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
615 unsigned numArgs,
616 UnbridgedCastsSet &unbridged) {
617 for (unsigned i = 0; i != numArgs; ++i)
618 if (checkPlaceholderForOverload(S, args[i], &unbridged))
619 return true;
620
621 return false;
622}
623
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000624// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000625// overload of the declarations in Old. This routine returns false if
626// New and Old cannot be overloaded, e.g., if New has the same
627// signature as some function in Old (C++ 1.3.10) or if the Old
628// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000629// it does return false, MatchedDecl will point to the decl that New
630// cannot be overloaded with. This decl may be a UsingShadowDecl on
631// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000632//
633// Example: Given the following input:
634//
635// void f(int, float); // #1
636// void f(int, int); // #2
637// int f(int, int); // #3
638//
639// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000640// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000641//
John McCall3d988d92009-12-02 08:47:38 +0000642// When we process #2, Old contains only the FunctionDecl for #1. By
643// comparing the parameter types, we see that #1 and #2 are overloaded
644// (since they have different signatures), so this routine returns
645// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646//
John McCall3d988d92009-12-02 08:47:38 +0000647// When we process #3, Old is an overload set containing #1 and #2. We
648// compare the signatures of #3 to #1 (they're overloaded, so we do
649// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
650// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000651// signature), IsOverload returns false and MatchedDecl will be set to
652// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000653//
654// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
655// into a class by a using declaration. The rules for whether to hide
656// shadow declarations ignore some properties which otherwise figure
657// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000658Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000659Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
660 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000661 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000662 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000663 NamedDecl *OldD = *I;
664
665 bool OldIsUsingDecl = false;
666 if (isa<UsingShadowDecl>(OldD)) {
667 OldIsUsingDecl = true;
668
669 // We can always introduce two using declarations into the same
670 // context, even if they have identical signatures.
671 if (NewIsUsingDecl) continue;
672
673 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
674 }
675
676 // If either declaration was introduced by a using declaration,
677 // we'll need to use slightly different rules for matching.
678 // Essentially, these rules are the normal rules, except that
679 // function templates hide function templates with different
680 // return types or template parameter lists.
681 bool UseMemberUsingDeclRules =
682 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
683
John McCall3d988d92009-12-02 08:47:38 +0000684 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000685 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
686 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
687 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
688 continue;
689 }
690
John McCalldaa3d6b2009-12-09 03:35:25 +0000691 Match = *I;
692 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000693 }
John McCall3d988d92009-12-02 08:47:38 +0000694 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000695 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
696 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
697 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
698 continue;
699 }
700
John McCalldaa3d6b2009-12-09 03:35:25 +0000701 Match = *I;
702 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000703 }
John McCalla8987a2942010-11-10 03:01:53 +0000704 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000705 // We can overload with these, which can show up when doing
706 // redeclaration checks for UsingDecls.
707 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000708 } else if (isa<TagDecl>(OldD)) {
709 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000710 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
711 // Optimistically assume that an unresolved using decl will
712 // overload; if it doesn't, we'll have to diagnose during
713 // template instantiation.
714 } else {
John McCall1f82f242009-11-18 22:49:29 +0000715 // (C++ 13p1):
716 // Only function declarations can be overloaded; object and type
717 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000718 Match = *I;
719 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000720 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000721 }
John McCall1f82f242009-11-18 22:49:29 +0000722
John McCalldaa3d6b2009-12-09 03:35:25 +0000723 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000724}
725
John McCalle9cccd82010-06-16 08:42:20 +0000726bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
727 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000728 // If both of the functions are extern "C", then they are not
729 // overloads.
730 if (Old->isExternC() && New->isExternC())
731 return false;
732
John McCall1f82f242009-11-18 22:49:29 +0000733 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
734 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
735
736 // C++ [temp.fct]p2:
737 // A function template can be overloaded with other function templates
738 // and with normal (non-template) functions.
739 if ((OldTemplate == 0) != (NewTemplate == 0))
740 return true;
741
742 // Is the function New an overload of the function Old?
743 QualType OldQType = Context.getCanonicalType(Old->getType());
744 QualType NewQType = Context.getCanonicalType(New->getType());
745
746 // Compare the signatures (C++ 1.3.10) of the two functions to
747 // determine whether they are overloads. If we find any mismatch
748 // in the signature, they are overloads.
749
750 // If either of these functions is a K&R-style function (no
751 // prototype), then we consider them to have matching signatures.
752 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
753 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
754 return false;
755
John McCall424cec92011-01-19 06:33:43 +0000756 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
757 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000758
759 // The signature of a function includes the types of its
760 // parameters (C++ 1.3.10), which includes the presence or absence
761 // of the ellipsis; see C++ DR 357).
762 if (OldQType != NewQType &&
763 (OldType->getNumArgs() != NewType->getNumArgs() ||
764 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000765 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000766 return true;
767
768 // C++ [temp.over.link]p4:
769 // The signature of a function template consists of its function
770 // signature, its return type and its template parameter list. The names
771 // of the template parameters are significant only for establishing the
772 // relationship between the template parameters and the rest of the
773 // signature.
774 //
775 // We check the return type and template parameter lists for function
776 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000777 //
778 // However, we don't consider either of these when deciding whether
779 // a member introduced by a shadow declaration is hidden.
780 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000781 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
782 OldTemplate->getTemplateParameters(),
783 false, TPL_TemplateMatch) ||
784 OldType->getResultType() != NewType->getResultType()))
785 return true;
786
787 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000788 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000789 //
790 // As part of this, also check whether one of the member functions
791 // is static, in which case they are not overloads (C++
792 // 13.1p2). While not part of the definition of the signature,
793 // this check is important to determine whether these functions
794 // can be overloaded.
795 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
796 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
797 if (OldMethod && NewMethod &&
798 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000799 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000800 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
801 if (!UseUsingDeclRules &&
802 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
803 (OldMethod->getRefQualifier() == RQ_None ||
804 NewMethod->getRefQualifier() == RQ_None)) {
805 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000806 // - Member function declarations with the same name and the same
807 // parameter-type-list as well as member function template
808 // declarations with the same name, the same parameter-type-list, and
809 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000810 // them, but not all, have a ref-qualifier (8.3.5).
811 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
812 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
813 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000815
John McCall1f82f242009-11-18 22:49:29 +0000816 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818
John McCall1f82f242009-11-18 22:49:29 +0000819 // The signatures match; this is not an overload.
820 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821}
822
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000823/// \brief Checks availability of the function depending on the current
824/// function context. Inside an unavailable function, unavailability is ignored.
825///
826/// \returns true if \arg FD is unavailable and current context is inside
827/// an available function, false otherwise.
828bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
829 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
830}
831
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000832/// \brief Tries a user-defined conversion from From to ToType.
833///
834/// Produces an implicit conversion sequence for when a standard conversion
835/// is not an option. See TryImplicitConversion for more information.
836static ImplicitConversionSequence
837TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
838 bool SuppressUserConversions,
839 bool AllowExplicit,
840 bool InOverloadResolution,
841 bool CStyle,
842 bool AllowObjCWritebackConversion) {
843 ImplicitConversionSequence ICS;
844
845 if (SuppressUserConversions) {
846 // We're not in the case above, so there is no conversion that
847 // we can perform.
848 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
849 return ICS;
850 }
851
852 // Attempt user-defined conversion.
853 OverloadCandidateSet Conversions(From->getExprLoc());
854 OverloadingResult UserDefResult
855 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
856 AllowExplicit);
857
858 if (UserDefResult == OR_Success) {
859 ICS.setUserDefined();
860 // C++ [over.ics.user]p4:
861 // A conversion of an expression of class type to the same class
862 // type is given Exact Match rank, and a conversion of an
863 // expression of class type to a base class of that type is
864 // given Conversion rank, in spite of the fact that a copy
865 // constructor (i.e., a user-defined conversion function) is
866 // called for those cases.
867 if (CXXConstructorDecl *Constructor
868 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
869 QualType FromCanon
870 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
871 QualType ToCanon
872 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
873 if (Constructor->isCopyConstructor() &&
874 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
875 // Turn this into a "standard" conversion sequence, so that it
876 // gets ranked with standard conversion sequences.
877 ICS.setStandard();
878 ICS.Standard.setAsIdentityConversion();
879 ICS.Standard.setFromType(From->getType());
880 ICS.Standard.setAllToTypes(ToType);
881 ICS.Standard.CopyConstructor = Constructor;
882 if (ToCanon != FromCanon)
883 ICS.Standard.Second = ICK_Derived_To_Base;
884 }
885 }
886
887 // C++ [over.best.ics]p4:
888 // However, when considering the argument of a user-defined
889 // conversion function that is a candidate by 13.3.1.3 when
890 // invoked for the copying of the temporary in the second step
891 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
892 // 13.3.1.6 in all cases, only standard conversion sequences and
893 // ellipsis conversion sequences are allowed.
894 if (SuppressUserConversions && ICS.isUserDefined()) {
895 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
896 }
897 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
898 ICS.setAmbiguous();
899 ICS.Ambiguous.setFromType(From->getType());
900 ICS.Ambiguous.setToType(ToType);
901 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
902 Cand != Conversions.end(); ++Cand)
903 if (Cand->Viable)
904 ICS.Ambiguous.addConversion(Cand->Function);
905 } else {
906 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
907 }
908
909 return ICS;
910}
911
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000912/// TryImplicitConversion - Attempt to perform an implicit conversion
913/// from the given expression (Expr) to the given type (ToType). This
914/// function returns an implicit conversion sequence that can be used
915/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000916///
917/// void f(float f);
918/// void g(int i) { f(i); }
919///
920/// this routine would produce an implicit conversion sequence to
921/// describe the initialization of f from i, which will be a standard
922/// conversion sequence containing an lvalue-to-rvalue conversion (C++
923/// 4.1) followed by a floating-integral conversion (C++ 4.9).
924//
925/// Note that this routine only determines how the conversion can be
926/// performed; it does not actually perform the conversion. As such,
927/// it will not produce any diagnostics if no conversion is available,
928/// but will instead return an implicit conversion sequence of kind
929/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000930///
931/// If @p SuppressUserConversions, then user-defined conversions are
932/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000933/// If @p AllowExplicit, then explicit user-defined conversions are
934/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000935///
936/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
937/// writeback conversion, which allows __autoreleasing id* parameters to
938/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000939static ImplicitConversionSequence
940TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
941 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000942 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000943 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000944 bool CStyle,
945 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000946 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000947 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000948 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000949 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000950 return ICS;
951 }
952
John McCall5c32be02010-08-24 20:38:10 +0000953 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000954 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000955 return ICS;
956 }
957
Douglas Gregor836a7e82010-08-11 02:15:33 +0000958 // C++ [over.ics.user]p4:
959 // A conversion of an expression of class type to the same class
960 // type is given Exact Match rank, and a conversion of an
961 // expression of class type to a base class of that type is
962 // given Conversion rank, in spite of the fact that a copy/move
963 // constructor (i.e., a user-defined conversion function) is
964 // called for those cases.
965 QualType FromType = From->getType();
966 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000967 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
968 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000969 ICS.setStandard();
970 ICS.Standard.setAsIdentityConversion();
971 ICS.Standard.setFromType(FromType);
972 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000973
Douglas Gregor5ab11652010-04-17 22:01:05 +0000974 // We don't actually check at this point whether there is a valid
975 // copy/move constructor, since overloading just assumes that it
976 // exists. When we actually perform initialization, we'll find the
977 // appropriate constructor to copy the returned object, if needed.
978 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000979
Douglas Gregor5ab11652010-04-17 22:01:05 +0000980 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000981 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000982 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor836a7e82010-08-11 02:15:33 +0000984 return ICS;
985 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000986
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000987 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
988 AllowExplicit, InOverloadResolution, CStyle,
989 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000990}
991
John McCall31168b02011-06-15 23:02:42 +0000992ImplicitConversionSequence
993Sema::TryImplicitConversion(Expr *From, QualType ToType,
994 bool SuppressUserConversions,
995 bool AllowExplicit,
996 bool InOverloadResolution,
997 bool CStyle,
998 bool AllowObjCWritebackConversion) {
999 return clang::TryImplicitConversion(*this, From, ToType,
1000 SuppressUserConversions, AllowExplicit,
1001 InOverloadResolution, CStyle,
1002 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001003}
1004
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001005/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001006/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001007/// converted expression. Flavor is the kind of conversion we're
1008/// performing, used in the error message. If @p AllowExplicit,
1009/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001010ExprResult
1011Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001012 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001013 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001014 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001015}
1016
John Wiegley01296292011-04-08 18:41:53 +00001017ExprResult
1018Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001019 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001020 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001021 if (checkPlaceholderForOverload(*this, From))
1022 return ExprError();
1023
John McCall31168b02011-06-15 23:02:42 +00001024 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1025 bool AllowObjCWritebackConversion
1026 = getLangOptions().ObjCAutoRefCount &&
1027 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001028
John McCall5c32be02010-08-24 20:38:10 +00001029 ICS = clang::TryImplicitConversion(*this, From, ToType,
1030 /*SuppressUserConversions=*/false,
1031 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001032 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001033 /*CStyle=*/false,
1034 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001035 return PerformImplicitConversion(From, ToType, ICS, Action);
1036}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001037
1038/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001039/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001040bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1041 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001042 if (Context.hasSameUnqualifiedType(FromType, ToType))
1043 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
John McCall991eb4b2010-12-21 00:44:39 +00001045 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1046 // where F adds one of the following at most once:
1047 // - a pointer
1048 // - a member pointer
1049 // - a block pointer
1050 CanQualType CanTo = Context.getCanonicalType(ToType);
1051 CanQualType CanFrom = Context.getCanonicalType(FromType);
1052 Type::TypeClass TyClass = CanTo->getTypeClass();
1053 if (TyClass != CanFrom->getTypeClass()) return false;
1054 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1055 if (TyClass == Type::Pointer) {
1056 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1057 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1058 } else if (TyClass == Type::BlockPointer) {
1059 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1060 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1061 } else if (TyClass == Type::MemberPointer) {
1062 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1063 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1064 } else {
1065 return false;
1066 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001067
John McCall991eb4b2010-12-21 00:44:39 +00001068 TyClass = CanTo->getTypeClass();
1069 if (TyClass != CanFrom->getTypeClass()) return false;
1070 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1071 return false;
1072 }
1073
1074 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1075 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1076 if (!EInfo.getNoReturn()) return false;
1077
1078 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1079 assert(QualType(FromFn, 0).isCanonical());
1080 if (QualType(FromFn, 0) != CanTo) return false;
1081
1082 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001083 return true;
1084}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085
Douglas Gregor46188682010-05-18 22:42:18 +00001086/// \brief Determine whether the conversion from FromType to ToType is a valid
1087/// vector conversion.
1088///
1089/// \param ICK Will be set to the vector conversion kind, if this is a vector
1090/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001091static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1092 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001093 // We need at least one of these types to be a vector type to have a vector
1094 // conversion.
1095 if (!ToType->isVectorType() && !FromType->isVectorType())
1096 return false;
1097
1098 // Identical types require no conversions.
1099 if (Context.hasSameUnqualifiedType(FromType, ToType))
1100 return false;
1101
1102 // There are no conversions between extended vector types, only identity.
1103 if (ToType->isExtVectorType()) {
1104 // There are no conversions between extended vector types other than the
1105 // identity conversion.
1106 if (FromType->isExtVectorType())
1107 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
Douglas Gregor46188682010-05-18 22:42:18 +00001109 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001110 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001111 ICK = ICK_Vector_Splat;
1112 return true;
1113 }
1114 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001115
1116 // We can perform the conversion between vector types in the following cases:
1117 // 1)vector types are equivalent AltiVec and GCC vector types
1118 // 2)lax vector conversions are permitted and the vector types are of the
1119 // same size
1120 if (ToType->isVectorType() && FromType->isVectorType()) {
1121 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001122 (Context.getLangOptions().LaxVectorConversions &&
1123 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001124 ICK = ICK_Vector_Conversion;
1125 return true;
1126 }
Douglas Gregor46188682010-05-18 22:42:18 +00001127 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001128
Douglas Gregor46188682010-05-18 22:42:18 +00001129 return false;
1130}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001131
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001132/// IsStandardConversion - Determines whether there is a standard
1133/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1134/// expression From to the type ToType. Standard conversion sequences
1135/// only consider non-class types; for conversions that involve class
1136/// types, use TryImplicitConversion. If a conversion exists, SCS will
1137/// contain the standard conversion sequence required to perform this
1138/// conversion and this routine will return true. Otherwise, this
1139/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001140static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1141 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001142 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001143 bool CStyle,
1144 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001146
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001148 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001149 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001150 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001151 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001152 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001153
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001154 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001155 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001156 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001157 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001158 return false;
1159
Mike Stump11289f42009-09-09 15:08:12 +00001160 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001161 }
1162
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 // The first conversion can be an lvalue-to-rvalue conversion,
1164 // array-to-pointer conversion, or function-to-pointer conversion
1165 // (C++ 4p1).
1166
John McCall5c32be02010-08-24 20:38:10 +00001167 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001168 DeclAccessPair AccessPair;
1169 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001171 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001172 // We were able to resolve the address of the overloaded function,
1173 // so we can convert to the type of that function.
1174 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001175
1176 // we can sometimes resolve &foo<int> regardless of ToType, so check
1177 // if the type matches (identity) or we are converting to bool
1178 if (!S.Context.hasSameUnqualifiedType(
1179 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1180 QualType resultTy;
1181 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001182 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001183 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1184 // otherwise, only a boolean conversion is standard
1185 if (!ToType->isBooleanType())
1186 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001188
Chandler Carruthffce2452011-03-29 08:08:18 +00001189 // Check if the "from" expression is taking the address of an overloaded
1190 // function and recompute the FromType accordingly. Take advantage of the
1191 // fact that non-static member functions *must* have such an address-of
1192 // expression.
1193 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1194 if (Method && !Method->isStatic()) {
1195 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1196 "Non-unary operator on non-static member address");
1197 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1198 == UO_AddrOf &&
1199 "Non-address-of operator on non-static member address");
1200 const Type *ClassType
1201 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1202 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001203 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1204 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1205 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001206 "Non-address-of operator for overloaded function expression");
1207 FromType = S.Context.getPointerType(FromType);
1208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001209
Douglas Gregor980fb162010-04-29 18:24:40 +00001210 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001211 assert(S.Context.hasSameType(
1212 FromType,
1213 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001214 } else {
1215 return false;
1216 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001217 }
John McCall154a2fd2011-08-30 00:57:29 +00001218 // Lvalue-to-rvalue conversion (C++11 4.1):
1219 // A glvalue (3.10) of a non-function, non-array type T can
1220 // be converted to a prvalue.
1221 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001222 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001223 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001224 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001225 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226
1227 // If T is a non-class type, the type of the rvalue is the
1228 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001229 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1230 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001231 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001232 } else if (FromType->isArrayType()) {
1233 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001234 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235
1236 // An lvalue or rvalue of type "array of N T" or "array of unknown
1237 // bound of T" can be converted to an rvalue of type "pointer to
1238 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001239 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240
John McCall5c32be02010-08-24 20:38:10 +00001241 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001242 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001243 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001244
1245 // For the purpose of ranking in overload resolution
1246 // (13.3.3.1.1), this conversion is considered an
1247 // array-to-pointer conversion followed by a qualification
1248 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001249 SCS.Second = ICK_Identity;
1250 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001251 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001252 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001253 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001254 }
John McCall086a4642010-11-24 05:12:34 +00001255 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001256 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001257 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258
1259 // An lvalue of function type T can be converted to an rvalue of
1260 // type "pointer to T." The result is a pointer to the
1261 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001262 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001263 } else {
1264 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001265 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001267 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001268
1269 // The second conversion can be an integral promotion, floating
1270 // point promotion, integral conversion, floating point conversion,
1271 // floating-integral conversion, pointer conversion,
1272 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001273 // For overloading in C, this can also be a "compatible-type"
1274 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001275 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001276 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001277 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001278 // The unqualified versions of the types are the same: there's no
1279 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001280 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001281 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001282 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001283 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001284 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001285 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001286 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001287 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001288 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001289 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001290 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001291 SCS.Second = ICK_Complex_Promotion;
1292 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001293 } else if (ToType->isBooleanType() &&
1294 (FromType->isArithmeticType() ||
1295 FromType->isAnyPointerType() ||
1296 FromType->isBlockPointerType() ||
1297 FromType->isMemberPointerType() ||
1298 FromType->isNullPtrType())) {
1299 // Boolean conversions (C++ 4.12).
1300 SCS.Second = ICK_Boolean_Conversion;
1301 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001302 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001303 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001304 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001305 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001306 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001307 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001308 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001309 SCS.Second = ICK_Complex_Conversion;
1310 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001311 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1312 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001313 // Complex-real conversions (C99 6.3.1.7)
1314 SCS.Second = ICK_Complex_Real;
1315 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001316 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001317 // Floating point conversions (C++ 4.8).
1318 SCS.Second = ICK_Floating_Conversion;
1319 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001321 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001322 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001323 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001324 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001325 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001326 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001327 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001328 SCS.Second = ICK_Block_Pointer_Conversion;
1329 } else if (AllowObjCWritebackConversion &&
1330 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1331 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001332 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1333 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001334 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001335 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001336 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001337 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001338 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001339 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001340 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001341 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001342 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001343 SCS.Second = SecondICK;
1344 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001345 } else if (!S.getLangOptions().CPlusPlus &&
1346 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001347 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001348 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001349 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001350 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001351 // Treat a conversion that strips "noreturn" as an identity conversion.
1352 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001353 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1354 InOverloadResolution,
1355 SCS, CStyle)) {
1356 SCS.Second = ICK_TransparentUnionConversion;
1357 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001358 } else {
1359 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001360 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001361 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001362 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001363
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001364 QualType CanonFrom;
1365 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001366 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001367 bool ObjCLifetimeConversion;
1368 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1369 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001370 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001371 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001372 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001373 CanonFrom = S.Context.getCanonicalType(FromType);
1374 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001375 } else {
1376 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001377 SCS.Third = ICK_Identity;
1378
Mike Stump11289f42009-09-09 15:08:12 +00001379 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001380 // [...] Any difference in top-level cv-qualification is
1381 // subsumed by the initialization itself and does not constitute
1382 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001383 CanonFrom = S.Context.getCanonicalType(FromType);
1384 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001386 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001387 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001388 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1389 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001390 FromType = ToType;
1391 CanonFrom = CanonTo;
1392 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001393 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001394 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001395
1396 // If we have not converted the argument type to the parameter type,
1397 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001398 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001399 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001401 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001402}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001403
1404static bool
1405IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1406 QualType &ToType,
1407 bool InOverloadResolution,
1408 StandardConversionSequence &SCS,
1409 bool CStyle) {
1410
1411 const RecordType *UT = ToType->getAsUnionType();
1412 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1413 return false;
1414 // The field to initialize within the transparent union.
1415 RecordDecl *UD = UT->getDecl();
1416 // It's compatible if the expression matches any of the fields.
1417 for (RecordDecl::field_iterator it = UD->field_begin(),
1418 itend = UD->field_end();
1419 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001420 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1421 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001422 ToType = it->getType();
1423 return true;
1424 }
1425 }
1426 return false;
1427}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001428
1429/// IsIntegralPromotion - Determines whether the conversion from the
1430/// expression From (whose potentially-adjusted type is FromType) to
1431/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1432/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001433bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001434 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001435 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001436 if (!To) {
1437 return false;
1438 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001439
1440 // An rvalue of type char, signed char, unsigned char, short int, or
1441 // unsigned short int can be converted to an rvalue of type int if
1442 // int can represent all the values of the source type; otherwise,
1443 // the source rvalue can be converted to an rvalue of type unsigned
1444 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001445 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1446 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001447 if (// We can promote any signed, promotable integer type to an int
1448 (FromType->isSignedIntegerType() ||
1449 // We can promote any unsigned integer type whose size is
1450 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001451 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001452 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001454 }
1455
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001456 return To->getKind() == BuiltinType::UInt;
1457 }
1458
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001459 // C++0x [conv.prom]p3:
1460 // A prvalue of an unscoped enumeration type whose underlying type is not
1461 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1462 // following types that can represent all the values of the enumeration
1463 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1464 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001465 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001467 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468 // with lowest integer conversion rank (4.13) greater than the rank of long
1469 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001470 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001471 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1472 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1473 // provided for a scoped enumeration.
1474 if (FromEnumType->getDecl()->isScoped())
1475 return false;
1476
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001477 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001478 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001479 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001480 return Context.hasSameUnqualifiedType(ToType,
1481 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001482 }
John McCall56774992009-12-09 09:09:27 +00001483
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001484 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1486 // to an rvalue a prvalue of the first of the following types that can
1487 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001488 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001490 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001491 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001492 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001493 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001494 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001495 // Determine whether the type we're converting from is signed or
1496 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001497 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001498 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001499
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001500 // The types we'll try to promote to, in the appropriate
1501 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001502 QualType PromoteTypes[6] = {
1503 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001504 Context.LongTy, Context.UnsignedLongTy ,
1505 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001506 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001507 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001508 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1509 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001510 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001511 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1512 // We found the type that we can promote to. If this is the
1513 // type we wanted, we have a promotion. Otherwise, no
1514 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001515 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001516 }
1517 }
1518 }
1519
1520 // An rvalue for an integral bit-field (9.6) can be converted to an
1521 // rvalue of type int if int can represent all the values of the
1522 // bit-field; otherwise, it can be converted to unsigned int if
1523 // unsigned int can represent all the values of the bit-field. If
1524 // the bit-field is larger yet, no integral promotion applies to
1525 // it. If the bit-field has an enumerated type, it is treated as any
1526 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001527 // FIXME: We should delay checking of bit-fields until we actually perform the
1528 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001529 using llvm::APSInt;
1530 if (From)
1531 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001532 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001533 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001534 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1535 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1536 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001537
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001538 // Are we promoting to an int from a bitfield that fits in an int?
1539 if (BitWidth < ToSize ||
1540 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1541 return To->getKind() == BuiltinType::Int;
1542 }
Mike Stump11289f42009-09-09 15:08:12 +00001543
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001544 // Are we promoting to an unsigned int from an unsigned bitfield
1545 // that fits into an unsigned int?
1546 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1547 return To->getKind() == BuiltinType::UInt;
1548 }
Mike Stump11289f42009-09-09 15:08:12 +00001549
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001550 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001551 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001552 }
Mike Stump11289f42009-09-09 15:08:12 +00001553
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001554 // An rvalue of type bool can be converted to an rvalue of type int,
1555 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001556 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001558 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559
1560 return false;
1561}
1562
1563/// IsFloatingPointPromotion - Determines whether the conversion from
1564/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1565/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001566bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001567 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1568 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001569 /// An rvalue of type float can be converted to an rvalue of type
1570 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571 if (FromBuiltin->getKind() == BuiltinType::Float &&
1572 ToBuiltin->getKind() == BuiltinType::Double)
1573 return true;
1574
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001575 // C99 6.3.1.5p1:
1576 // When a float is promoted to double or long double, or a
1577 // double is promoted to long double [...].
1578 if (!getLangOptions().CPlusPlus &&
1579 (FromBuiltin->getKind() == BuiltinType::Float ||
1580 FromBuiltin->getKind() == BuiltinType::Double) &&
1581 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1582 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001583
1584 // Half can be promoted to float.
1585 if (FromBuiltin->getKind() == BuiltinType::Half &&
1586 ToBuiltin->getKind() == BuiltinType::Float)
1587 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001588 }
1589
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 return false;
1591}
1592
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001593/// \brief Determine if a conversion is a complex promotion.
1594///
1595/// A complex promotion is defined as a complex -> complex conversion
1596/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001597/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001598bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001599 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001600 if (!FromComplex)
1601 return false;
1602
John McCall9dd450b2009-09-21 23:43:11 +00001603 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001604 if (!ToComplex)
1605 return false;
1606
1607 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001608 ToComplex->getElementType()) ||
1609 IsIntegralPromotion(0, FromComplex->getElementType(),
1610 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001611}
1612
Douglas Gregor237f96c2008-11-26 23:31:11 +00001613/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1614/// the pointer type FromPtr to a pointer to type ToPointee, with the
1615/// same type qualifiers as FromPtr has on its pointee type. ToType,
1616/// if non-empty, will be a pointer to ToType that may or may not have
1617/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001618///
Mike Stump11289f42009-09-09 15:08:12 +00001619static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001620BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001621 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001622 ASTContext &Context,
1623 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001624 assert((FromPtr->getTypeClass() == Type::Pointer ||
1625 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1626 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001627
John McCall31168b02011-06-15 23:02:42 +00001628 /// Conversions to 'id' subsume cv-qualifier conversions.
1629 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001630 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631
1632 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001633 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001634 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001635 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001636
John McCall31168b02011-06-15 23:02:42 +00001637 if (StripObjCLifetime)
1638 Quals.removeObjCLifetime();
1639
Mike Stump11289f42009-09-09 15:08:12 +00001640 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001641 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001642 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001643 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001644 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001645
1646 // Build a pointer to ToPointee. It has the right qualifiers
1647 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001648 if (isa<ObjCObjectPointerType>(ToType))
1649 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001650 return Context.getPointerType(ToPointee);
1651 }
1652
1653 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001654 QualType QualifiedCanonToPointee
1655 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001657 if (isa<ObjCObjectPointerType>(ToType))
1658 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1659 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001660}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001661
Mike Stump11289f42009-09-09 15:08:12 +00001662static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001663 bool InOverloadResolution,
1664 ASTContext &Context) {
1665 // Handle value-dependent integral null pointer constants correctly.
1666 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1667 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001668 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001669 return !InOverloadResolution;
1670
Douglas Gregor56751b52009-09-25 04:25:58 +00001671 return Expr->isNullPointerConstant(Context,
1672 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1673 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001674}
Mike Stump11289f42009-09-09 15:08:12 +00001675
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676/// IsPointerConversion - Determines whether the conversion of the
1677/// expression From, which has the (possibly adjusted) type FromType,
1678/// can be converted to the type ToType via a pointer conversion (C++
1679/// 4.10). If so, returns true and places the converted type (that
1680/// might differ from ToType in its cv-qualifiers at some level) into
1681/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001682///
Douglas Gregora29dc052008-11-27 01:19:21 +00001683/// This routine also supports conversions to and from block pointers
1684/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1685/// pointers to interfaces. FIXME: Once we've determined the
1686/// appropriate overloading rules for Objective-C, we may want to
1687/// split the Objective-C checks into a different routine; however,
1688/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001689/// conversions, so for now they live here. IncompatibleObjC will be
1690/// set if the conversion is an allowed Objective-C conversion that
1691/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001692bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001693 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001694 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001695 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001696 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001697 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1698 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001699 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001700
Mike Stump11289f42009-09-09 15:08:12 +00001701 // Conversion from a null pointer constant to any Objective-C pointer type.
1702 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001703 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001704 ConvertedType = ToType;
1705 return true;
1706 }
1707
Douglas Gregor231d1c62008-11-27 00:15:41 +00001708 // Blocks: Block pointers can be converted to void*.
1709 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001710 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001711 ConvertedType = ToType;
1712 return true;
1713 }
1714 // Blocks: A null pointer constant can be converted to a block
1715 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001716 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001717 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001718 ConvertedType = ToType;
1719 return true;
1720 }
1721
Sebastian Redl576fd422009-05-10 18:38:11 +00001722 // If the left-hand-side is nullptr_t, the right side can be a null
1723 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001724 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001725 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001726 ConvertedType = ToType;
1727 return true;
1728 }
1729
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001730 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001731 if (!ToTypePtr)
1732 return false;
1733
1734 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001735 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001736 ConvertedType = ToType;
1737 return true;
1738 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001739
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001740 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001741 // , including objective-c pointers.
1742 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001743 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1744 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001745 ConvertedType = BuildSimilarlyQualifiedPointerType(
1746 FromType->getAs<ObjCObjectPointerType>(),
1747 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001748 ToType, Context);
1749 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001750 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001751 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001752 if (!FromTypePtr)
1753 return false;
1754
1755 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001756
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001757 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001758 // pointer conversion, so don't do all of the work below.
1759 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1760 return false;
1761
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001762 // An rvalue of type "pointer to cv T," where T is an object type,
1763 // can be converted to an rvalue of type "pointer to cv void" (C++
1764 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001765 if (FromPointeeType->isIncompleteOrObjectType() &&
1766 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001767 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001768 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001769 ToType, Context,
1770 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001771 return true;
1772 }
1773
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001774 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001775 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001776 ToPointeeType->isVoidType()) {
1777 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1778 ToPointeeType,
1779 ToType, Context);
1780 return true;
1781 }
1782
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001783 // When we're overloading in C, we allow a special kind of pointer
1784 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001785 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001786 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001787 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001788 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001789 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001790 return true;
1791 }
1792
Douglas Gregor5c407d92008-10-23 00:40:37 +00001793 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001794 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001795 // An rvalue of type "pointer to cv D," where D is a class type,
1796 // can be converted to an rvalue of type "pointer to cv B," where
1797 // B is a base class (clause 10) of D. If B is an inaccessible
1798 // (clause 11) or ambiguous (10.2) base class of D, a program that
1799 // necessitates this conversion is ill-formed. The result of the
1800 // conversion is a pointer to the base class sub-object of the
1801 // derived class object. The null pointer value is converted to
1802 // the null pointer value of the destination type.
1803 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001804 // Note that we do not check for ambiguity or inaccessibility
1805 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001806 if (getLangOptions().CPlusPlus &&
1807 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001808 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001809 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001810 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001811 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001812 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001813 ToType, Context);
1814 return true;
1815 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001816
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001817 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1818 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1819 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1820 ToPointeeType,
1821 ToType, Context);
1822 return true;
1823 }
1824
Douglas Gregora119f102008-12-19 19:13:09 +00001825 return false;
1826}
Douglas Gregoraec25842011-04-26 23:16:46 +00001827
1828/// \brief Adopt the given qualifiers for the given type.
1829static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1830 Qualifiers TQs = T.getQualifiers();
1831
1832 // Check whether qualifiers already match.
1833 if (TQs == Qs)
1834 return T;
1835
1836 if (Qs.compatiblyIncludes(TQs))
1837 return Context.getQualifiedType(T, Qs);
1838
1839 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1840}
Douglas Gregora119f102008-12-19 19:13:09 +00001841
1842/// isObjCPointerConversion - Determines whether this is an
1843/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1844/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001845bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001846 QualType& ConvertedType,
1847 bool &IncompatibleObjC) {
1848 if (!getLangOptions().ObjC1)
1849 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001850
Douglas Gregoraec25842011-04-26 23:16:46 +00001851 // The set of qualifiers on the type we're converting from.
1852 Qualifiers FromQualifiers = FromType.getQualifiers();
1853
Steve Naroff7cae42b2009-07-10 23:34:53 +00001854 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001855 const ObjCObjectPointerType* ToObjCPtr =
1856 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001857 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001858 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001859
Steve Naroff7cae42b2009-07-10 23:34:53 +00001860 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001861 // If the pointee types are the same (ignoring qualifications),
1862 // then this is not a pointer conversion.
1863 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1864 FromObjCPtr->getPointeeType()))
1865 return false;
1866
Douglas Gregoraec25842011-04-26 23:16:46 +00001867 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001868 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001869 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001870 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001871 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001872 return true;
1873 }
1874 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001875 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001876 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001877 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001878 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001879 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001880 return true;
1881 }
1882 // Objective C++: We're able to convert from a pointer to an
1883 // interface to a pointer to a different interface.
1884 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001885 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1886 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1887 if (getLangOptions().CPlusPlus && LHS && RHS &&
1888 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1889 FromObjCPtr->getPointeeType()))
1890 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001892 ToObjCPtr->getPointeeType(),
1893 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001894 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001895 return true;
1896 }
1897
1898 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1899 // Okay: this is some kind of implicit downcast of Objective-C
1900 // interfaces, which is permitted. However, we're going to
1901 // complain about it.
1902 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001904 ToObjCPtr->getPointeeType(),
1905 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001906 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001907 return true;
1908 }
Mike Stump11289f42009-09-09 15:08:12 +00001909 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001910 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001911 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001912 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001913 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001914 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001915 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001916 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001917 // to a block pointer type.
1918 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001919 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001920 return true;
1921 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001922 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001925 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001926 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001927 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001928 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001929 return true;
1930 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001931 else
Douglas Gregora119f102008-12-19 19:13:09 +00001932 return false;
1933
Douglas Gregor033f56d2008-12-23 00:53:59 +00001934 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001935 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001936 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001937 else if (const BlockPointerType *FromBlockPtr =
1938 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001939 FromPointeeType = FromBlockPtr->getPointeeType();
1940 else
Douglas Gregora119f102008-12-19 19:13:09 +00001941 return false;
1942
Douglas Gregora119f102008-12-19 19:13:09 +00001943 // If we have pointers to pointers, recursively check whether this
1944 // is an Objective-C conversion.
1945 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1946 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1947 IncompatibleObjC)) {
1948 // We always complain about this conversion.
1949 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001950 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001951 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001952 return true;
1953 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001954 // Allow conversion of pointee being objective-c pointer to another one;
1955 // as in I* to id.
1956 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1957 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1958 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1959 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001960
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001961 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001962 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001963 return true;
1964 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001965
Douglas Gregor033f56d2008-12-23 00:53:59 +00001966 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001967 // differences in the argument and result types are in Objective-C
1968 // pointer conversions. If so, we permit the conversion (but
1969 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001970 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001971 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001972 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001973 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001974 if (FromFunctionType && ToFunctionType) {
1975 // If the function types are exactly the same, this isn't an
1976 // Objective-C pointer conversion.
1977 if (Context.getCanonicalType(FromPointeeType)
1978 == Context.getCanonicalType(ToPointeeType))
1979 return false;
1980
1981 // Perform the quick checks that will tell us whether these
1982 // function types are obviously different.
1983 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1984 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1985 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1986 return false;
1987
1988 bool HasObjCConversion = false;
1989 if (Context.getCanonicalType(FromFunctionType->getResultType())
1990 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1991 // Okay, the types match exactly. Nothing to do.
1992 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1993 ToFunctionType->getResultType(),
1994 ConvertedType, IncompatibleObjC)) {
1995 // Okay, we have an Objective-C pointer conversion.
1996 HasObjCConversion = true;
1997 } else {
1998 // Function types are too different. Abort.
1999 return false;
2000 }
Mike Stump11289f42009-09-09 15:08:12 +00002001
Douglas Gregora119f102008-12-19 19:13:09 +00002002 // Check argument types.
2003 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2004 ArgIdx != NumArgs; ++ArgIdx) {
2005 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2006 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2007 if (Context.getCanonicalType(FromArgType)
2008 == Context.getCanonicalType(ToArgType)) {
2009 // Okay, the types match exactly. Nothing to do.
2010 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2011 ConvertedType, IncompatibleObjC)) {
2012 // Okay, we have an Objective-C pointer conversion.
2013 HasObjCConversion = true;
2014 } else {
2015 // Argument types are too different. Abort.
2016 return false;
2017 }
2018 }
2019
2020 if (HasObjCConversion) {
2021 // We had an Objective-C conversion. Allow this pointer
2022 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002023 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002024 IncompatibleObjC = true;
2025 return true;
2026 }
2027 }
2028
Sebastian Redl72b597d2009-01-25 19:43:20 +00002029 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002030}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002031
John McCall31168b02011-06-15 23:02:42 +00002032/// \brief Determine whether this is an Objective-C writeback conversion,
2033/// used for parameter passing when performing automatic reference counting.
2034///
2035/// \param FromType The type we're converting form.
2036///
2037/// \param ToType The type we're converting to.
2038///
2039/// \param ConvertedType The type that will be produced after applying
2040/// this conversion.
2041bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2042 QualType &ConvertedType) {
2043 if (!getLangOptions().ObjCAutoRefCount ||
2044 Context.hasSameUnqualifiedType(FromType, ToType))
2045 return false;
2046
2047 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2048 QualType ToPointee;
2049 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2050 ToPointee = ToPointer->getPointeeType();
2051 else
2052 return false;
2053
2054 Qualifiers ToQuals = ToPointee.getQualifiers();
2055 if (!ToPointee->isObjCLifetimeType() ||
2056 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2057 !ToQuals.withoutObjCGLifetime().empty())
2058 return false;
2059
2060 // Argument must be a pointer to __strong to __weak.
2061 QualType FromPointee;
2062 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2063 FromPointee = FromPointer->getPointeeType();
2064 else
2065 return false;
2066
2067 Qualifiers FromQuals = FromPointee.getQualifiers();
2068 if (!FromPointee->isObjCLifetimeType() ||
2069 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2070 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2071 return false;
2072
2073 // Make sure that we have compatible qualifiers.
2074 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2075 if (!ToQuals.compatiblyIncludes(FromQuals))
2076 return false;
2077
2078 // Remove qualifiers from the pointee type we're converting from; they
2079 // aren't used in the compatibility check belong, and we'll be adding back
2080 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2081 FromPointee = FromPointee.getUnqualifiedType();
2082
2083 // The unqualified form of the pointee types must be compatible.
2084 ToPointee = ToPointee.getUnqualifiedType();
2085 bool IncompatibleObjC;
2086 if (Context.typesAreCompatible(FromPointee, ToPointee))
2087 FromPointee = ToPointee;
2088 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2089 IncompatibleObjC))
2090 return false;
2091
2092 /// \brief Construct the type we're converting to, which is a pointer to
2093 /// __autoreleasing pointee.
2094 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2095 ConvertedType = Context.getPointerType(FromPointee);
2096 return true;
2097}
2098
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002099bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2100 QualType& ConvertedType) {
2101 QualType ToPointeeType;
2102 if (const BlockPointerType *ToBlockPtr =
2103 ToType->getAs<BlockPointerType>())
2104 ToPointeeType = ToBlockPtr->getPointeeType();
2105 else
2106 return false;
2107
2108 QualType FromPointeeType;
2109 if (const BlockPointerType *FromBlockPtr =
2110 FromType->getAs<BlockPointerType>())
2111 FromPointeeType = FromBlockPtr->getPointeeType();
2112 else
2113 return false;
2114 // We have pointer to blocks, check whether the only
2115 // differences in the argument and result types are in Objective-C
2116 // pointer conversions. If so, we permit the conversion.
2117
2118 const FunctionProtoType *FromFunctionType
2119 = FromPointeeType->getAs<FunctionProtoType>();
2120 const FunctionProtoType *ToFunctionType
2121 = ToPointeeType->getAs<FunctionProtoType>();
2122
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002123 if (!FromFunctionType || !ToFunctionType)
2124 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002125
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002126 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002127 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002128
2129 // Perform the quick checks that will tell us whether these
2130 // function types are obviously different.
2131 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2132 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2133 return false;
2134
2135 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2136 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2137 if (FromEInfo != ToEInfo)
2138 return false;
2139
2140 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002141 if (Context.hasSameType(FromFunctionType->getResultType(),
2142 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002143 // Okay, the types match exactly. Nothing to do.
2144 } else {
2145 QualType RHS = FromFunctionType->getResultType();
2146 QualType LHS = ToFunctionType->getResultType();
2147 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2148 !RHS.hasQualifiers() && LHS.hasQualifiers())
2149 LHS = LHS.getUnqualifiedType();
2150
2151 if (Context.hasSameType(RHS,LHS)) {
2152 // OK exact match.
2153 } else if (isObjCPointerConversion(RHS, LHS,
2154 ConvertedType, IncompatibleObjC)) {
2155 if (IncompatibleObjC)
2156 return false;
2157 // Okay, we have an Objective-C pointer conversion.
2158 }
2159 else
2160 return false;
2161 }
2162
2163 // Check argument types.
2164 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2165 ArgIdx != NumArgs; ++ArgIdx) {
2166 IncompatibleObjC = false;
2167 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2168 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2169 if (Context.hasSameType(FromArgType, ToArgType)) {
2170 // Okay, the types match exactly. Nothing to do.
2171 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2172 ConvertedType, IncompatibleObjC)) {
2173 if (IncompatibleObjC)
2174 return false;
2175 // Okay, we have an Objective-C pointer conversion.
2176 } else
2177 // Argument types are too different. Abort.
2178 return false;
2179 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002180 if (LangOpts.ObjCAutoRefCount &&
2181 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2182 ToFunctionType))
2183 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002184
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002185 ConvertedType = ToType;
2186 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002187}
2188
Richard Trieucaff2472011-11-23 22:32:32 +00002189enum {
2190 ft_default,
2191 ft_different_class,
2192 ft_parameter_arity,
2193 ft_parameter_mismatch,
2194 ft_return_type,
2195 ft_qualifer_mismatch
2196};
2197
2198/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2199/// function types. Catches different number of parameter, mismatch in
2200/// parameter types, and different return types.
2201void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2202 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002203 // If either type is not valid, include no extra info.
2204 if (FromType.isNull() || ToType.isNull()) {
2205 PDiag << ft_default;
2206 return;
2207 }
2208
Richard Trieucaff2472011-11-23 22:32:32 +00002209 // Get the function type from the pointers.
2210 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2211 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2212 *ToMember = ToType->getAs<MemberPointerType>();
2213 if (FromMember->getClass() != ToMember->getClass()) {
2214 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2215 << QualType(FromMember->getClass(), 0);
2216 return;
2217 }
2218 FromType = FromMember->getPointeeType();
2219 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002220 }
2221
Richard Trieu96ed5b62011-12-13 23:19:45 +00002222 if (FromType->isPointerType())
2223 FromType = FromType->getPointeeType();
2224 if (ToType->isPointerType())
2225 ToType = ToType->getPointeeType();
2226
2227 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002228 FromType = FromType.getNonReferenceType();
2229 ToType = ToType.getNonReferenceType();
2230
Richard Trieucaff2472011-11-23 22:32:32 +00002231 // Don't print extra info for non-specialized template functions.
2232 if (FromType->isInstantiationDependentType() &&
2233 !FromType->getAs<TemplateSpecializationType>()) {
2234 PDiag << ft_default;
2235 return;
2236 }
2237
Richard Trieu96ed5b62011-12-13 23:19:45 +00002238 // No extra info for same types.
2239 if (Context.hasSameType(FromType, ToType)) {
2240 PDiag << ft_default;
2241 return;
2242 }
2243
Richard Trieucaff2472011-11-23 22:32:32 +00002244 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2245 *ToFunction = ToType->getAs<FunctionProtoType>();
2246
2247 // Both types need to be function types.
2248 if (!FromFunction || !ToFunction) {
2249 PDiag << ft_default;
2250 return;
2251 }
2252
2253 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2254 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2255 << FromFunction->getNumArgs();
2256 return;
2257 }
2258
2259 // Handle different parameter types.
2260 unsigned ArgPos;
2261 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2262 PDiag << ft_parameter_mismatch << ArgPos + 1
2263 << ToFunction->getArgType(ArgPos)
2264 << FromFunction->getArgType(ArgPos);
2265 return;
2266 }
2267
2268 // Handle different return type.
2269 if (!Context.hasSameType(FromFunction->getResultType(),
2270 ToFunction->getResultType())) {
2271 PDiag << ft_return_type << ToFunction->getResultType()
2272 << FromFunction->getResultType();
2273 return;
2274 }
2275
2276 unsigned FromQuals = FromFunction->getTypeQuals(),
2277 ToQuals = ToFunction->getTypeQuals();
2278 if (FromQuals != ToQuals) {
2279 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2280 return;
2281 }
2282
2283 // Unable to find a difference, so add no extra info.
2284 PDiag << ft_default;
2285}
2286
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002287/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002288/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002289/// they have same number of arguments. This routine assumes that Objective-C
2290/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002291/// If the parameters are different, ArgPos will have the the parameter index
2292/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002293bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002294 const FunctionProtoType *NewType,
2295 unsigned *ArgPos) {
2296 if (!getLangOptions().ObjC1) {
2297 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2298 N = NewType->arg_type_begin(),
2299 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2300 if (!Context.hasSameType(*O, *N)) {
2301 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2302 return false;
2303 }
2304 }
2305 return true;
2306 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002308 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2309 N = NewType->arg_type_begin(),
2310 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2311 QualType ToType = (*O);
2312 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002313 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002314 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2315 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002316 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2317 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2318 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2319 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002320 continue;
2321 }
John McCall8b07ec22010-05-15 11:32:37 +00002322 else if (const ObjCObjectPointerType *PTTo =
2323 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002324 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002325 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002326 if (Context.hasSameUnqualifiedType(
2327 PTTo->getObjectType()->getBaseType(),
2328 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002329 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002330 }
Richard Trieucaff2472011-11-23 22:32:32 +00002331 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002332 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002333 }
2334 }
2335 return true;
2336}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002337
Douglas Gregor39c16d42008-10-24 04:54:22 +00002338/// CheckPointerConversion - Check the pointer conversion from the
2339/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002340/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002341/// conversions for which IsPointerConversion has already returned
2342/// true. It returns true and produces a diagnostic if there was an
2343/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002344bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002345 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002346 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002347 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002348 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002349 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002350
John McCall8cb679e2010-11-15 09:13:47 +00002351 Kind = CK_BitCast;
2352
Chandler Carruthffab8732011-04-09 07:32:05 +00002353 if (!IsCStyleOrFunctionalCast &&
2354 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2355 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2356 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002357 PDiag(diag::warn_impcast_bool_to_null_pointer)
2358 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002359
John McCall9320b872011-09-09 05:25:32 +00002360 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2361 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002362 QualType FromPointeeType = FromPtrType->getPointeeType(),
2363 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002364
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002365 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2366 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002367 // We must have a derived-to-base conversion. Check an
2368 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002369 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2370 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002371 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002372 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002373 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002374
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002375 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002376 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002377 }
2378 }
John McCall9320b872011-09-09 05:25:32 +00002379 } else if (const ObjCObjectPointerType *ToPtrType =
2380 ToType->getAs<ObjCObjectPointerType>()) {
2381 if (const ObjCObjectPointerType *FromPtrType =
2382 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002383 // Objective-C++ conversions are always okay.
2384 // FIXME: We should have a different class of conversions for the
2385 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002386 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002387 return false;
John McCall9320b872011-09-09 05:25:32 +00002388 } else if (FromType->isBlockPointerType()) {
2389 Kind = CK_BlockPointerToObjCPointerCast;
2390 } else {
2391 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002392 }
John McCall9320b872011-09-09 05:25:32 +00002393 } else if (ToType->isBlockPointerType()) {
2394 if (!FromType->isBlockPointerType())
2395 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002396 }
John McCall8cb679e2010-11-15 09:13:47 +00002397
2398 // We shouldn't fall into this case unless it's valid for other
2399 // reasons.
2400 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2401 Kind = CK_NullToPointer;
2402
Douglas Gregor39c16d42008-10-24 04:54:22 +00002403 return false;
2404}
2405
Sebastian Redl72b597d2009-01-25 19:43:20 +00002406/// IsMemberPointerConversion - Determines whether the conversion of the
2407/// expression From, which has the (possibly adjusted) type FromType, can be
2408/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2409/// If so, returns true and places the converted type (that might differ from
2410/// ToType in its cv-qualifiers at some level) into ConvertedType.
2411bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002412 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002413 bool InOverloadResolution,
2414 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002415 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002416 if (!ToTypePtr)
2417 return false;
2418
2419 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002420 if (From->isNullPointerConstant(Context,
2421 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2422 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002423 ConvertedType = ToType;
2424 return true;
2425 }
2426
2427 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002428 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002429 if (!FromTypePtr)
2430 return false;
2431
2432 // A pointer to member of B can be converted to a pointer to member of D,
2433 // where D is derived from B (C++ 4.11p2).
2434 QualType FromClass(FromTypePtr->getClass(), 0);
2435 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002436
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002437 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2438 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2439 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002440 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2441 ToClass.getTypePtr());
2442 return true;
2443 }
2444
2445 return false;
2446}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002447
Sebastian Redl72b597d2009-01-25 19:43:20 +00002448/// CheckMemberPointerConversion - Check the member pointer conversion from the
2449/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002450/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002451/// for which IsMemberPointerConversion has already returned true. It returns
2452/// true and produces a diagnostic if there was an error, or returns false
2453/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002454bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002455 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002456 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002457 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002458 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002459 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002460 if (!FromPtrType) {
2461 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002462 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002463 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002464 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002465 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002466 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002467 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002468
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002469 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002470 assert(ToPtrType && "No member pointer cast has a target type "
2471 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002472
Sebastian Redled8f2002009-01-28 18:33:18 +00002473 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2474 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002475
Sebastian Redled8f2002009-01-28 18:33:18 +00002476 // FIXME: What about dependent types?
2477 assert(FromClass->isRecordType() && "Pointer into non-class.");
2478 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002479
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002480 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002481 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002482 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2483 assert(DerivationOkay &&
2484 "Should not have been called if derivation isn't OK.");
2485 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002486
Sebastian Redled8f2002009-01-28 18:33:18 +00002487 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2488 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002489 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2490 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2491 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2492 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002493 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002494
Douglas Gregor89ee6822009-02-28 01:32:25 +00002495 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002496 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2497 << FromClass << ToClass << QualType(VBase, 0)
2498 << From->getSourceRange();
2499 return true;
2500 }
2501
John McCall5b0829a2010-02-10 09:31:12 +00002502 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002503 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2504 Paths.front(),
2505 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002506
Anders Carlssond7923c62009-08-22 23:33:40 +00002507 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002508 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002509 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002510 return false;
2511}
2512
Douglas Gregor9a657932008-10-21 23:43:52 +00002513/// IsQualificationConversion - Determines whether the conversion from
2514/// an rvalue of type FromType to ToType is a qualification conversion
2515/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002516///
2517/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2518/// when the qualification conversion involves a change in the Objective-C
2519/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002520bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002521Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002522 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002523 FromType = Context.getCanonicalType(FromType);
2524 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002525 ObjCLifetimeConversion = false;
2526
Douglas Gregor9a657932008-10-21 23:43:52 +00002527 // If FromType and ToType are the same type, this is not a
2528 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002529 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002530 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002531
Douglas Gregor9a657932008-10-21 23:43:52 +00002532 // (C++ 4.4p4):
2533 // A conversion can add cv-qualifiers at levels other than the first
2534 // in multi-level pointers, subject to the following rules: [...]
2535 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002536 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002537 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002538 // Within each iteration of the loop, we check the qualifiers to
2539 // determine if this still looks like a qualification
2540 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002541 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002542 // until there are no more pointers or pointers-to-members left to
2543 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002544 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002545
Douglas Gregor90609aa2011-04-25 18:40:17 +00002546 Qualifiers FromQuals = FromType.getQualifiers();
2547 Qualifiers ToQuals = ToType.getQualifiers();
2548
John McCall31168b02011-06-15 23:02:42 +00002549 // Objective-C ARC:
2550 // Check Objective-C lifetime conversions.
2551 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2552 UnwrappedAnyPointer) {
2553 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2554 ObjCLifetimeConversion = true;
2555 FromQuals.removeObjCLifetime();
2556 ToQuals.removeObjCLifetime();
2557 } else {
2558 // Qualification conversions cannot cast between different
2559 // Objective-C lifetime qualifiers.
2560 return false;
2561 }
2562 }
2563
Douglas Gregorf30053d2011-05-08 06:09:53 +00002564 // Allow addition/removal of GC attributes but not changing GC attributes.
2565 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2566 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2567 FromQuals.removeObjCGCAttr();
2568 ToQuals.removeObjCGCAttr();
2569 }
2570
Douglas Gregor9a657932008-10-21 23:43:52 +00002571 // -- for every j > 0, if const is in cv 1,j then const is in cv
2572 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002573 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002574 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002575
Douglas Gregor9a657932008-10-21 23:43:52 +00002576 // -- if the cv 1,j and cv 2,j are different, then const is in
2577 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002578 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002579 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002580 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002581
Douglas Gregor9a657932008-10-21 23:43:52 +00002582 // Keep track of whether all prior cv-qualifiers in the "to" type
2583 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002584 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002585 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002586 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002587
2588 // We are left with FromType and ToType being the pointee types
2589 // after unwrapping the original FromType and ToType the same number
2590 // of types. If we unwrapped any pointers, and if FromType and
2591 // ToType have the same unqualified type (since we checked
2592 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002593 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002594}
2595
Douglas Gregor576e98c2009-01-30 23:27:23 +00002596/// Determines whether there is a user-defined conversion sequence
2597/// (C++ [over.ics.user]) that converts expression From to the type
2598/// ToType. If such a conversion exists, User will contain the
2599/// user-defined conversion sequence that performs such a conversion
2600/// and this routine will return true. Otherwise, this routine returns
2601/// false and User is unspecified.
2602///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002603/// \param AllowExplicit true if the conversion should consider C++0x
2604/// "explicit" conversion functions as well as non-explicit conversion
2605/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002606static OverloadingResult
2607IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2608 UserDefinedConversionSequence& User,
2609 OverloadCandidateSet& CandidateSet,
2610 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002611 // Whether we will only visit constructors.
2612 bool ConstructorsOnly = false;
2613
2614 // If the type we are conversion to is a class type, enumerate its
2615 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002616 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002617 // C++ [over.match.ctor]p1:
2618 // When objects of class type are direct-initialized (8.5), or
2619 // copy-initialized from an expression of the same or a
2620 // derived class type (8.5), overload resolution selects the
2621 // constructor. [...] For copy-initialization, the candidate
2622 // functions are all the converting constructors (12.3.1) of
2623 // that class. The argument list is the expression-list within
2624 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002625 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002626 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002627 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002628 ConstructorsOnly = true;
2629
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002630 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2631 // RequireCompleteType may have returned true due to some invalid decl
2632 // during template instantiation, but ToType may be complete enough now
2633 // to try to recover.
2634 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002635 // We're not going to find any constructors.
2636 } else if (CXXRecordDecl *ToRecordDecl
2637 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002638
2639 Expr **Args = &From;
2640 unsigned NumArgs = 1;
2641 bool ListInitializing = false;
2642 // If we're list-initializing, we pass the individual elements as
2643 // arguments, not the entire list.
2644 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2645 Args = InitList->getInits();
2646 NumArgs = InitList->getNumInits();
2647 ListInitializing = true;
2648 }
2649
Douglas Gregor89ee6822009-02-28 01:32:25 +00002650 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002651 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002652 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002653 NamedDecl *D = *Con;
2654 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2655
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002656 // Find the constructor (which may be a template).
2657 CXXConstructorDecl *Constructor = 0;
2658 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002659 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002660 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002661 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002662 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2663 else
John McCalla0296f72010-03-19 07:35:19 +00002664 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002666 bool Usable = !Constructor->isInvalidDecl();
2667 if (ListInitializing)
2668 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2669 else
2670 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2671 if (Usable) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002672 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002673 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2674 /*ExplicitArgs*/ 0,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002675 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002676 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002677 !ConstructorsOnly &&
2678 !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002679 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002680 // Allow one user-defined conversion when user specifies a
2681 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002682 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002683 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002684 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002685 !ConstructorsOnly && !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002686 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002687 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002688 }
2689 }
2690
Douglas Gregor5ab11652010-04-17 22:01:05 +00002691 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002692 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002693 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2694 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002695 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002696 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002697 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002698 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002699 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2700 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002701 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002702 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002703 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002704 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002705 DeclAccessPair FoundDecl = I.getPair();
2706 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002707 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2708 if (isa<UsingShadowDecl>(D))
2709 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2710
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002711 CXXConversionDecl *Conv;
2712 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002713 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2714 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002715 else
John McCallda4458e2010-03-31 01:36:47 +00002716 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002717
2718 if (AllowExplicit || !Conv->isExplicit()) {
2719 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002720 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2721 ActingContext, From, ToType,
2722 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002723 else
John McCall5c32be02010-08-24 20:38:10 +00002724 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2725 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002726 }
2727 }
2728 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002729 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002730
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002731 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2732
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002733 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002734 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002735 case OR_Success:
2736 // Record the standard conversion we used and the conversion function.
2737 if (CXXConstructorDecl *Constructor
2738 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002739 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2740
John McCall5c32be02010-08-24 20:38:10 +00002741 // C++ [over.ics.user]p1:
2742 // If the user-defined conversion is specified by a
2743 // constructor (12.3.1), the initial standard conversion
2744 // sequence converts the source type to the type required by
2745 // the argument of the constructor.
2746 //
2747 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002748 if (isa<InitListExpr>(From)) {
2749 // Initializer lists don't have conversions as such.
2750 User.Before.setAsIdentityConversion();
2751 } else {
2752 if (Best->Conversions[0].isEllipsis())
2753 User.EllipsisConversion = true;
2754 else {
2755 User.Before = Best->Conversions[0].Standard;
2756 User.EllipsisConversion = false;
2757 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002758 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002759 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002760 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002761 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002762 User.After.setAsIdentityConversion();
2763 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2764 User.After.setAllToTypes(ToType);
2765 return OR_Success;
2766 } else if (CXXConversionDecl *Conversion
2767 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002768 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2769
John McCall5c32be02010-08-24 20:38:10 +00002770 // C++ [over.ics.user]p1:
2771 //
2772 // [...] If the user-defined conversion is specified by a
2773 // conversion function (12.3.2), the initial standard
2774 // conversion sequence converts the source type to the
2775 // implicit object parameter of the conversion function.
2776 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002777 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002778 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002779 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002780 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002781
John McCall5c32be02010-08-24 20:38:10 +00002782 // C++ [over.ics.user]p2:
2783 // The second standard conversion sequence converts the
2784 // result of the user-defined conversion to the target type
2785 // for the sequence. Since an implicit conversion sequence
2786 // is an initialization, the special rules for
2787 // initialization by user-defined conversion apply when
2788 // selecting the best user-defined conversion for a
2789 // user-defined conversion sequence (see 13.3.3 and
2790 // 13.3.3.1).
2791 User.After = Best->FinalConversion;
2792 return OR_Success;
2793 } else {
2794 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002795 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002796 }
2797
John McCall5c32be02010-08-24 20:38:10 +00002798 case OR_No_Viable_Function:
2799 return OR_No_Viable_Function;
2800 case OR_Deleted:
2801 // No conversion here! We're done.
2802 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803
John McCall5c32be02010-08-24 20:38:10 +00002804 case OR_Ambiguous:
2805 return OR_Ambiguous;
2806 }
2807
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002808 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002809}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002810
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002811bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002812Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002813 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002814 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002815 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002816 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002817 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002818 if (OvResult == OR_Ambiguous)
2819 Diag(From->getSourceRange().getBegin(),
2820 diag::err_typecheck_ambiguous_condition)
2821 << From->getType() << ToType << From->getSourceRange();
2822 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2823 Diag(From->getSourceRange().getBegin(),
2824 diag::err_typecheck_nonviable_condition)
2825 << From->getType() << ToType << From->getSourceRange();
2826 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002827 return false;
John McCall5c32be02010-08-24 20:38:10 +00002828 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002829 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002830}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002831
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002832/// CompareImplicitConversionSequences - Compare two implicit
2833/// conversion sequences to determine whether one is better than the
2834/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002835static ImplicitConversionSequence::CompareKind
2836CompareImplicitConversionSequences(Sema &S,
2837 const ImplicitConversionSequence& ICS1,
2838 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002839{
2840 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2841 // conversion sequences (as defined in 13.3.3.1)
2842 // -- a standard conversion sequence (13.3.3.1.1) is a better
2843 // conversion sequence than a user-defined conversion sequence or
2844 // an ellipsis conversion sequence, and
2845 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2846 // conversion sequence than an ellipsis conversion sequence
2847 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002848 //
John McCall0d1da222010-01-12 00:44:57 +00002849 // C++0x [over.best.ics]p10:
2850 // For the purpose of ranking implicit conversion sequences as
2851 // described in 13.3.3.2, the ambiguous conversion sequence is
2852 // treated as a user-defined sequence that is indistinguishable
2853 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002854 if (ICS1.getKindRank() < ICS2.getKindRank())
2855 return ImplicitConversionSequence::Better;
2856 else if (ICS2.getKindRank() < ICS1.getKindRank())
2857 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002858
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002859 // The following checks require both conversion sequences to be of
2860 // the same kind.
2861 if (ICS1.getKind() != ICS2.getKind())
2862 return ImplicitConversionSequence::Indistinguishable;
2863
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002864 ImplicitConversionSequence::CompareKind Result =
2865 ImplicitConversionSequence::Indistinguishable;
2866
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002867 // Two implicit conversion sequences of the same form are
2868 // indistinguishable conversion sequences unless one of the
2869 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002870 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002871 Result = CompareStandardConversionSequences(S,
2872 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002873 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002874 // User-defined conversion sequence U1 is a better conversion
2875 // sequence than another user-defined conversion sequence U2 if
2876 // they contain the same user-defined conversion function or
2877 // constructor and if the second standard conversion sequence of
2878 // U1 is better than the second standard conversion sequence of
2879 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002880 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002881 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002882 Result = CompareStandardConversionSequences(S,
2883 ICS1.UserDefined.After,
2884 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002885 }
2886
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002887 // List-initialization sequence L1 is a better conversion sequence than
2888 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2889 // for some X and L2 does not.
2890 if (Result == ImplicitConversionSequence::Indistinguishable &&
2891 ICS1.isListInitializationSequence() &&
2892 ICS2.isListInitializationSequence()) {
2893 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2894 }
2895
2896 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002897}
2898
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002899static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2900 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2901 Qualifiers Quals;
2902 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002903 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002904 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002905
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002906 return Context.hasSameUnqualifiedType(T1, T2);
2907}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002908
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002909// Per 13.3.3.2p3, compare the given standard conversion sequences to
2910// determine if one is a proper subset of the other.
2911static ImplicitConversionSequence::CompareKind
2912compareStandardConversionSubsets(ASTContext &Context,
2913 const StandardConversionSequence& SCS1,
2914 const StandardConversionSequence& SCS2) {
2915 ImplicitConversionSequence::CompareKind Result
2916 = ImplicitConversionSequence::Indistinguishable;
2917
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002918 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002919 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002920 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2921 return ImplicitConversionSequence::Better;
2922 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2923 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002924
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002925 if (SCS1.Second != SCS2.Second) {
2926 if (SCS1.Second == ICK_Identity)
2927 Result = ImplicitConversionSequence::Better;
2928 else if (SCS2.Second == ICK_Identity)
2929 Result = ImplicitConversionSequence::Worse;
2930 else
2931 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002932 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002933 return ImplicitConversionSequence::Indistinguishable;
2934
2935 if (SCS1.Third == SCS2.Third) {
2936 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2937 : ImplicitConversionSequence::Indistinguishable;
2938 }
2939
2940 if (SCS1.Third == ICK_Identity)
2941 return Result == ImplicitConversionSequence::Worse
2942 ? ImplicitConversionSequence::Indistinguishable
2943 : ImplicitConversionSequence::Better;
2944
2945 if (SCS2.Third == ICK_Identity)
2946 return Result == ImplicitConversionSequence::Better
2947 ? ImplicitConversionSequence::Indistinguishable
2948 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002949
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002950 return ImplicitConversionSequence::Indistinguishable;
2951}
2952
Douglas Gregore696ebb2011-01-26 14:52:12 +00002953/// \brief Determine whether one of the given reference bindings is better
2954/// than the other based on what kind of bindings they are.
2955static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2956 const StandardConversionSequence &SCS2) {
2957 // C++0x [over.ics.rank]p3b4:
2958 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2959 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002960 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002961 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002962 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002963 // reference*.
2964 //
2965 // FIXME: Rvalue references. We're going rogue with the above edits,
2966 // because the semantics in the current C++0x working paper (N3225 at the
2967 // time of this writing) break the standard definition of std::forward
2968 // and std::reference_wrapper when dealing with references to functions.
2969 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002970 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2971 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2972 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002973
Douglas Gregore696ebb2011-01-26 14:52:12 +00002974 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2975 SCS2.IsLvalueReference) ||
2976 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2977 !SCS2.IsLvalueReference);
2978}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002979
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002980/// CompareStandardConversionSequences - Compare two standard
2981/// conversion sequences to determine whether one is better than the
2982/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002983static ImplicitConversionSequence::CompareKind
2984CompareStandardConversionSequences(Sema &S,
2985 const StandardConversionSequence& SCS1,
2986 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002987{
2988 // Standard conversion sequence S1 is a better conversion sequence
2989 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2990
2991 // -- S1 is a proper subsequence of S2 (comparing the conversion
2992 // sequences in the canonical form defined by 13.3.3.1.1,
2993 // excluding any Lvalue Transformation; the identity conversion
2994 // sequence is considered to be a subsequence of any
2995 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002996 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002997 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002998 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002999
3000 // -- the rank of S1 is better than the rank of S2 (by the rules
3001 // defined below), or, if not that,
3002 ImplicitConversionRank Rank1 = SCS1.getRank();
3003 ImplicitConversionRank Rank2 = SCS2.getRank();
3004 if (Rank1 < Rank2)
3005 return ImplicitConversionSequence::Better;
3006 else if (Rank2 < Rank1)
3007 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003008
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003009 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3010 // are indistinguishable unless one of the following rules
3011 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003012
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003013 // A conversion that is not a conversion of a pointer, or
3014 // pointer to member, to bool is better than another conversion
3015 // that is such a conversion.
3016 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3017 return SCS2.isPointerConversionToBool()
3018 ? ImplicitConversionSequence::Better
3019 : ImplicitConversionSequence::Worse;
3020
Douglas Gregor5c407d92008-10-23 00:40:37 +00003021 // C++ [over.ics.rank]p4b2:
3022 //
3023 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003024 // conversion of B* to A* is better than conversion of B* to
3025 // void*, and conversion of A* to void* is better than conversion
3026 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003027 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003028 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003029 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003030 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003031 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3032 // Exactly one of the conversion sequences is a conversion to
3033 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003034 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3035 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003036 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3037 // Neither conversion sequence converts to a void pointer; compare
3038 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003039 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003040 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003041 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003042 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3043 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003044 // Both conversion sequences are conversions to void
3045 // pointers. Compare the source types to determine if there's an
3046 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003047 QualType FromType1 = SCS1.getFromType();
3048 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003049
3050 // Adjust the types we're converting from via the array-to-pointer
3051 // conversion, if we need to.
3052 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003053 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003054 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003055 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003056
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003057 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3058 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003059
John McCall5c32be02010-08-24 20:38:10 +00003060 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003061 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003062 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003063 return ImplicitConversionSequence::Worse;
3064
3065 // Objective-C++: If one interface is more specific than the
3066 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003067 const ObjCObjectPointerType* FromObjCPtr1
3068 = FromType1->getAs<ObjCObjectPointerType>();
3069 const ObjCObjectPointerType* FromObjCPtr2
3070 = FromType2->getAs<ObjCObjectPointerType>();
3071 if (FromObjCPtr1 && FromObjCPtr2) {
3072 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3073 FromObjCPtr2);
3074 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3075 FromObjCPtr1);
3076 if (AssignLeft != AssignRight) {
3077 return AssignLeft? ImplicitConversionSequence::Better
3078 : ImplicitConversionSequence::Worse;
3079 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003080 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003081 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003082
3083 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3084 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003085 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003086 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003087 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003088
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003089 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003090 // Check for a better reference binding based on the kind of bindings.
3091 if (isBetterReferenceBindingKind(SCS1, SCS2))
3092 return ImplicitConversionSequence::Better;
3093 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3094 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003095
Sebastian Redlb28b4072009-03-22 23:49:27 +00003096 // C++ [over.ics.rank]p3b4:
3097 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3098 // which the references refer are the same type except for
3099 // top-level cv-qualifiers, and the type to which the reference
3100 // initialized by S2 refers is more cv-qualified than the type
3101 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003102 QualType T1 = SCS1.getToType(2);
3103 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003104 T1 = S.Context.getCanonicalType(T1);
3105 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003106 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003107 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3108 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003109 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003110 // Objective-C++ ARC: If the references refer to objects with different
3111 // lifetimes, prefer bindings that don't change lifetime.
3112 if (SCS1.ObjCLifetimeConversionBinding !=
3113 SCS2.ObjCLifetimeConversionBinding) {
3114 return SCS1.ObjCLifetimeConversionBinding
3115 ? ImplicitConversionSequence::Worse
3116 : ImplicitConversionSequence::Better;
3117 }
3118
Chandler Carruth8e543b32010-12-12 08:17:55 +00003119 // If the type is an array type, promote the element qualifiers to the
3120 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003121 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003122 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003123 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003124 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003125 if (T2.isMoreQualifiedThan(T1))
3126 return ImplicitConversionSequence::Better;
3127 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003128 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003129 }
3130 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003131
Francois Pichet08d2fa02011-09-18 21:37:37 +00003132 // In Microsoft mode, prefer an integral conversion to a
3133 // floating-to-integral conversion if the integral conversion
3134 // is between types of the same size.
3135 // For example:
3136 // void f(float);
3137 // void f(int);
3138 // int main {
3139 // long a;
3140 // f(a);
3141 // }
3142 // Here, MSVC will call f(int) instead of generating a compile error
3143 // as clang will do in standard mode.
3144 if (S.getLangOptions().MicrosoftMode &&
3145 SCS1.Second == ICK_Integral_Conversion &&
3146 SCS2.Second == ICK_Floating_Integral &&
3147 S.Context.getTypeSize(SCS1.getFromType()) ==
3148 S.Context.getTypeSize(SCS1.getToType(2)))
3149 return ImplicitConversionSequence::Better;
3150
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003151 return ImplicitConversionSequence::Indistinguishable;
3152}
3153
3154/// CompareQualificationConversions - Compares two standard conversion
3155/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003156/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3157ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003158CompareQualificationConversions(Sema &S,
3159 const StandardConversionSequence& SCS1,
3160 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003161 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003162 // -- S1 and S2 differ only in their qualification conversion and
3163 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3164 // cv-qualification signature of type T1 is a proper subset of
3165 // the cv-qualification signature of type T2, and S1 is not the
3166 // deprecated string literal array-to-pointer conversion (4.2).
3167 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3168 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3169 return ImplicitConversionSequence::Indistinguishable;
3170
3171 // FIXME: the example in the standard doesn't use a qualification
3172 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003173 QualType T1 = SCS1.getToType(2);
3174 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003175 T1 = S.Context.getCanonicalType(T1);
3176 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003177 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003178 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3179 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003180
3181 // If the types are the same, we won't learn anything by unwrapped
3182 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003183 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003184 return ImplicitConversionSequence::Indistinguishable;
3185
Chandler Carruth607f38e2009-12-29 07:16:59 +00003186 // If the type is an array type, promote the element qualifiers to the type
3187 // for comparison.
3188 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003189 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003190 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003191 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003192
Mike Stump11289f42009-09-09 15:08:12 +00003193 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003194 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003195
3196 // Objective-C++ ARC:
3197 // Prefer qualification conversions not involving a change in lifetime
3198 // to qualification conversions that do not change lifetime.
3199 if (SCS1.QualificationIncludesObjCLifetime !=
3200 SCS2.QualificationIncludesObjCLifetime) {
3201 Result = SCS1.QualificationIncludesObjCLifetime
3202 ? ImplicitConversionSequence::Worse
3203 : ImplicitConversionSequence::Better;
3204 }
3205
John McCall5c32be02010-08-24 20:38:10 +00003206 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003207 // Within each iteration of the loop, we check the qualifiers to
3208 // determine if this still looks like a qualification
3209 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003210 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003211 // until there are no more pointers or pointers-to-members left
3212 // to unwrap. This essentially mimics what
3213 // IsQualificationConversion does, but here we're checking for a
3214 // strict subset of qualifiers.
3215 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3216 // The qualifiers are the same, so this doesn't tell us anything
3217 // about how the sequences rank.
3218 ;
3219 else if (T2.isMoreQualifiedThan(T1)) {
3220 // T1 has fewer qualifiers, so it could be the better sequence.
3221 if (Result == ImplicitConversionSequence::Worse)
3222 // Neither has qualifiers that are a subset of the other's
3223 // qualifiers.
3224 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003225
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003226 Result = ImplicitConversionSequence::Better;
3227 } else if (T1.isMoreQualifiedThan(T2)) {
3228 // T2 has fewer qualifiers, so it could be the better sequence.
3229 if (Result == ImplicitConversionSequence::Better)
3230 // Neither has qualifiers that are a subset of the other's
3231 // qualifiers.
3232 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003233
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003234 Result = ImplicitConversionSequence::Worse;
3235 } else {
3236 // Qualifiers are disjoint.
3237 return ImplicitConversionSequence::Indistinguishable;
3238 }
3239
3240 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003241 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003242 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003243 }
3244
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003245 // Check that the winning standard conversion sequence isn't using
3246 // the deprecated string literal array to pointer conversion.
3247 switch (Result) {
3248 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003249 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003250 Result = ImplicitConversionSequence::Indistinguishable;
3251 break;
3252
3253 case ImplicitConversionSequence::Indistinguishable:
3254 break;
3255
3256 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003257 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003258 Result = ImplicitConversionSequence::Indistinguishable;
3259 break;
3260 }
3261
3262 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003263}
3264
Douglas Gregor5c407d92008-10-23 00:40:37 +00003265/// CompareDerivedToBaseConversions - Compares two standard conversion
3266/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003267/// various kinds of derived-to-base conversions (C++
3268/// [over.ics.rank]p4b3). As part of these checks, we also look at
3269/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003270ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003271CompareDerivedToBaseConversions(Sema &S,
3272 const StandardConversionSequence& SCS1,
3273 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003274 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003275 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003276 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003277 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003278
3279 // Adjust the types we're converting from via the array-to-pointer
3280 // conversion, if we need to.
3281 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003282 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003283 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003284 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003285
3286 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003287 FromType1 = S.Context.getCanonicalType(FromType1);
3288 ToType1 = S.Context.getCanonicalType(ToType1);
3289 FromType2 = S.Context.getCanonicalType(FromType2);
3290 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003291
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003292 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003293 //
3294 // If class B is derived directly or indirectly from class A and
3295 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003296 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003297 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003298 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003299 SCS2.Second == ICK_Pointer_Conversion &&
3300 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3301 FromType1->isPointerType() && FromType2->isPointerType() &&
3302 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003303 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003304 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003305 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003306 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003307 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003308 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003309 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003310 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003311
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003312 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003313 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003314 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003315 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003316 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003317 return ImplicitConversionSequence::Worse;
3318 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003319
3320 // -- conversion of B* to A* is better than conversion of C* to A*,
3321 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003322 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003323 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003324 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003325 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003326 }
3327 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3328 SCS2.Second == ICK_Pointer_Conversion) {
3329 const ObjCObjectPointerType *FromPtr1
3330 = FromType1->getAs<ObjCObjectPointerType>();
3331 const ObjCObjectPointerType *FromPtr2
3332 = FromType2->getAs<ObjCObjectPointerType>();
3333 const ObjCObjectPointerType *ToPtr1
3334 = ToType1->getAs<ObjCObjectPointerType>();
3335 const ObjCObjectPointerType *ToPtr2
3336 = ToType2->getAs<ObjCObjectPointerType>();
3337
3338 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3339 // Apply the same conversion ranking rules for Objective-C pointer types
3340 // that we do for C++ pointers to class types. However, we employ the
3341 // Objective-C pseudo-subtyping relationship used for assignment of
3342 // Objective-C pointer types.
3343 bool FromAssignLeft
3344 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3345 bool FromAssignRight
3346 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3347 bool ToAssignLeft
3348 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3349 bool ToAssignRight
3350 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3351
3352 // A conversion to an a non-id object pointer type or qualified 'id'
3353 // type is better than a conversion to 'id'.
3354 if (ToPtr1->isObjCIdType() &&
3355 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3356 return ImplicitConversionSequence::Worse;
3357 if (ToPtr2->isObjCIdType() &&
3358 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3359 return ImplicitConversionSequence::Better;
3360
3361 // A conversion to a non-id object pointer type is better than a
3362 // conversion to a qualified 'id' type
3363 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3364 return ImplicitConversionSequence::Worse;
3365 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3366 return ImplicitConversionSequence::Better;
3367
3368 // A conversion to an a non-Class object pointer type or qualified 'Class'
3369 // type is better than a conversion to 'Class'.
3370 if (ToPtr1->isObjCClassType() &&
3371 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3372 return ImplicitConversionSequence::Worse;
3373 if (ToPtr2->isObjCClassType() &&
3374 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3375 return ImplicitConversionSequence::Better;
3376
3377 // A conversion to a non-Class object pointer type is better than a
3378 // conversion to a qualified 'Class' type.
3379 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3380 return ImplicitConversionSequence::Worse;
3381 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3382 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003383
Douglas Gregor058d3de2011-01-31 18:51:41 +00003384 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3385 if (S.Context.hasSameType(FromType1, FromType2) &&
3386 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3387 (ToAssignLeft != ToAssignRight))
3388 return ToAssignLeft? ImplicitConversionSequence::Worse
3389 : ImplicitConversionSequence::Better;
3390
3391 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3392 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3393 (FromAssignLeft != FromAssignRight))
3394 return FromAssignLeft? ImplicitConversionSequence::Better
3395 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003396 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003397 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003398
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003399 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003400 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3401 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3402 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003404 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003406 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003408 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003410 ToType2->getAs<MemberPointerType>();
3411 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3412 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3413 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3414 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3415 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3416 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3417 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3418 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003419 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003420 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003421 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003422 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003423 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003424 return ImplicitConversionSequence::Better;
3425 }
3426 // conversion of B::* to C::* is better than conversion of A::* to C::*
3427 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003428 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003429 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003430 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003431 return ImplicitConversionSequence::Worse;
3432 }
3433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003434
Douglas Gregor5ab11652010-04-17 22:01:05 +00003435 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003436 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003437 // -- binding of an expression of type C to a reference of type
3438 // B& is better than binding an expression of type C to a
3439 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003440 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3441 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3442 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003443 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003444 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003445 return ImplicitConversionSequence::Worse;
3446 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003447
Douglas Gregor2fe98832008-11-03 19:09:14 +00003448 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003449 // -- binding of an expression of type B to a reference of type
3450 // A& is better than binding an expression of type C to a
3451 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003452 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3453 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3454 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003455 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003456 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003457 return ImplicitConversionSequence::Worse;
3458 }
3459 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003460
Douglas Gregor5c407d92008-10-23 00:40:37 +00003461 return ImplicitConversionSequence::Indistinguishable;
3462}
3463
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003464/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3465/// determine whether they are reference-related,
3466/// reference-compatible, reference-compatible with added
3467/// qualification, or incompatible, for use in C++ initialization by
3468/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3469/// type, and the first type (T1) is the pointee type of the reference
3470/// type being initialized.
3471Sema::ReferenceCompareResult
3472Sema::CompareReferenceRelationship(SourceLocation Loc,
3473 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003474 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003475 bool &ObjCConversion,
3476 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003477 assert(!OrigT1->isReferenceType() &&
3478 "T1 must be the pointee type of the reference type");
3479 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3480
3481 QualType T1 = Context.getCanonicalType(OrigT1);
3482 QualType T2 = Context.getCanonicalType(OrigT2);
3483 Qualifiers T1Quals, T2Quals;
3484 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3485 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3486
3487 // C++ [dcl.init.ref]p4:
3488 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3489 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3490 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003491 DerivedToBase = false;
3492 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003493 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003494 if (UnqualT1 == UnqualT2) {
3495 // Nothing to do.
3496 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003497 IsDerivedFrom(UnqualT2, UnqualT1))
3498 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003499 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3500 UnqualT2->isObjCObjectOrInterfaceType() &&
3501 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3502 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003503 else
3504 return Ref_Incompatible;
3505
3506 // At this point, we know that T1 and T2 are reference-related (at
3507 // least).
3508
3509 // If the type is an array type, promote the element qualifiers to the type
3510 // for comparison.
3511 if (isa<ArrayType>(T1) && T1Quals)
3512 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3513 if (isa<ArrayType>(T2) && T2Quals)
3514 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3515
3516 // C++ [dcl.init.ref]p4:
3517 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3518 // reference-related to T2 and cv1 is the same cv-qualification
3519 // as, or greater cv-qualification than, cv2. For purposes of
3520 // overload resolution, cases for which cv1 is greater
3521 // cv-qualification than cv2 are identified as
3522 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003523 //
3524 // Note that we also require equivalence of Objective-C GC and address-space
3525 // qualifiers when performing these computations, so that e.g., an int in
3526 // address space 1 is not reference-compatible with an int in address
3527 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003528 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3529 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3530 T1Quals.removeObjCLifetime();
3531 T2Quals.removeObjCLifetime();
3532 ObjCLifetimeConversion = true;
3533 }
3534
Douglas Gregord517d552011-04-28 17:56:11 +00003535 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003536 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003537 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003538 return Ref_Compatible_With_Added_Qualification;
3539 else
3540 return Ref_Related;
3541}
3542
Douglas Gregor836a7e82010-08-11 02:15:33 +00003543/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003544/// with DeclType. Return true if something definite is found.
3545static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003546FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3547 QualType DeclType, SourceLocation DeclLoc,
3548 Expr *Init, QualType T2, bool AllowRvalues,
3549 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003550 assert(T2->isRecordType() && "Can only find conversions of record types.");
3551 CXXRecordDecl *T2RecordDecl
3552 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3553
3554 OverloadCandidateSet CandidateSet(DeclLoc);
3555 const UnresolvedSetImpl *Conversions
3556 = T2RecordDecl->getVisibleConversionFunctions();
3557 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3558 E = Conversions->end(); I != E; ++I) {
3559 NamedDecl *D = *I;
3560 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3561 if (isa<UsingShadowDecl>(D))
3562 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3563
3564 FunctionTemplateDecl *ConvTemplate
3565 = dyn_cast<FunctionTemplateDecl>(D);
3566 CXXConversionDecl *Conv;
3567 if (ConvTemplate)
3568 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3569 else
3570 Conv = cast<CXXConversionDecl>(D);
3571
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003573 // explicit conversions, skip it.
3574 if (!AllowExplicit && Conv->isExplicit())
3575 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003576
Douglas Gregor836a7e82010-08-11 02:15:33 +00003577 if (AllowRvalues) {
3578 bool DerivedToBase = false;
3579 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003580 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003581
3582 // If we are initializing an rvalue reference, don't permit conversion
3583 // functions that return lvalues.
3584 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3585 const ReferenceType *RefType
3586 = Conv->getConversionType()->getAs<LValueReferenceType>();
3587 if (RefType && !RefType->getPointeeType()->isFunctionType())
3588 continue;
3589 }
3590
Douglas Gregor836a7e82010-08-11 02:15:33 +00003591 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003592 S.CompareReferenceRelationship(
3593 DeclLoc,
3594 Conv->getConversionType().getNonReferenceType()
3595 .getUnqualifiedType(),
3596 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003597 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003598 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003599 continue;
3600 } else {
3601 // If the conversion function doesn't return a reference type,
3602 // it can't be considered for this conversion. An rvalue reference
3603 // is only acceptable if its referencee is a function type.
3604
3605 const ReferenceType *RefType =
3606 Conv->getConversionType()->getAs<ReferenceType>();
3607 if (!RefType ||
3608 (!RefType->isLValueReferenceType() &&
3609 !RefType->getPointeeType()->isFunctionType()))
3610 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003612
Douglas Gregor836a7e82010-08-11 02:15:33 +00003613 if (ConvTemplate)
3614 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003615 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003616 else
3617 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003618 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003619 }
3620
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003621 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3622
Sebastian Redld92badf2010-06-30 18:13:39 +00003623 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003624 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003625 case OR_Success:
3626 // C++ [over.ics.ref]p1:
3627 //
3628 // [...] If the parameter binds directly to the result of
3629 // applying a conversion function to the argument
3630 // expression, the implicit conversion sequence is a
3631 // user-defined conversion sequence (13.3.3.1.2), with the
3632 // second standard conversion sequence either an identity
3633 // conversion or, if the conversion function returns an
3634 // entity of a type that is a derived class of the parameter
3635 // type, a derived-to-base Conversion.
3636 if (!Best->FinalConversion.DirectBinding)
3637 return false;
3638
Chandler Carruth30141632011-02-25 19:41:05 +00003639 if (Best->Function)
3640 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003641 ICS.setUserDefined();
3642 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3643 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003644 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003645 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003646 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003647 ICS.UserDefined.EllipsisConversion = false;
3648 assert(ICS.UserDefined.After.ReferenceBinding &&
3649 ICS.UserDefined.After.DirectBinding &&
3650 "Expected a direct reference binding!");
3651 return true;
3652
3653 case OR_Ambiguous:
3654 ICS.setAmbiguous();
3655 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3656 Cand != CandidateSet.end(); ++Cand)
3657 if (Cand->Viable)
3658 ICS.Ambiguous.addConversion(Cand->Function);
3659 return true;
3660
3661 case OR_No_Viable_Function:
3662 case OR_Deleted:
3663 // There was no suitable conversion, or we found a deleted
3664 // conversion; continue with other checks.
3665 return false;
3666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667
Eric Christopheraba9fb22010-06-30 18:36:32 +00003668 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003669}
3670
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003671/// \brief Compute an implicit conversion sequence for reference
3672/// initialization.
3673static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003674TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003675 SourceLocation DeclLoc,
3676 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003677 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003678 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3679
3680 // Most paths end in a failed conversion.
3681 ImplicitConversionSequence ICS;
3682 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3683
3684 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3685 QualType T2 = Init->getType();
3686
3687 // If the initializer is the address of an overloaded function, try
3688 // to resolve the overloaded function. If all goes well, T2 is the
3689 // type of the resulting function.
3690 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3691 DeclAccessPair Found;
3692 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3693 false, Found))
3694 T2 = Fn->getType();
3695 }
3696
3697 // Compute some basic properties of the types and the initializer.
3698 bool isRValRef = DeclType->isRValueReferenceType();
3699 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003700 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003701 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003702 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003703 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003704 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003705 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003706
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003707
Sebastian Redld92badf2010-06-30 18:13:39 +00003708 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003709 // A reference to type "cv1 T1" is initialized by an expression
3710 // of type "cv2 T2" as follows:
3711
Sebastian Redld92badf2010-06-30 18:13:39 +00003712 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003713 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003714 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3715 // reference-compatible with "cv2 T2," or
3716 //
3717 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3718 if (InitCategory.isLValue() &&
3719 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003720 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003721 // When a parameter of reference type binds directly (8.5.3)
3722 // to an argument expression, the implicit conversion sequence
3723 // is the identity conversion, unless the argument expression
3724 // has a type that is a derived class of the parameter type,
3725 // in which case the implicit conversion sequence is a
3726 // derived-to-base Conversion (13.3.3.1).
3727 ICS.setStandard();
3728 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003729 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3730 : ObjCConversion? ICK_Compatible_Conversion
3731 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003732 ICS.Standard.Third = ICK_Identity;
3733 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3734 ICS.Standard.setToType(0, T2);
3735 ICS.Standard.setToType(1, T1);
3736 ICS.Standard.setToType(2, T1);
3737 ICS.Standard.ReferenceBinding = true;
3738 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003739 ICS.Standard.IsLvalueReference = !isRValRef;
3740 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3741 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003742 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003743 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003744 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003745
Sebastian Redld92badf2010-06-30 18:13:39 +00003746 // Nothing more to do: the inaccessibility/ambiguity check for
3747 // derived-to-base conversions is suppressed when we're
3748 // computing the implicit conversion sequence (C++
3749 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003750 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003751 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003752
Sebastian Redld92badf2010-06-30 18:13:39 +00003753 // -- has a class type (i.e., T2 is a class type), where T1 is
3754 // not reference-related to T2, and can be implicitly
3755 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3756 // is reference-compatible with "cv3 T3" 92) (this
3757 // conversion is selected by enumerating the applicable
3758 // conversion functions (13.3.1.6) and choosing the best
3759 // one through overload resolution (13.3)),
3760 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003761 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003762 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003763 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3764 Init, T2, /*AllowRvalues=*/false,
3765 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003766 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003767 }
3768 }
3769
Sebastian Redld92badf2010-06-30 18:13:39 +00003770 // -- Otherwise, the reference shall be an lvalue reference to a
3771 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003772 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003773 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003774 // We actually handle one oddity of C++ [over.ics.ref] at this
3775 // point, which is that, due to p2 (which short-circuits reference
3776 // binding by only attempting a simple conversion for non-direct
3777 // bindings) and p3's strange wording, we allow a const volatile
3778 // reference to bind to an rvalue. Hence the check for the presence
3779 // of "const" rather than checking for "const" being the only
3780 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003781 // This is also the point where rvalue references and lvalue inits no longer
3782 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003783 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003784 return ICS;
3785
Douglas Gregorf143cd52011-01-24 16:14:37 +00003786 // -- If the initializer expression
3787 //
3788 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003789 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003790 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3791 (InitCategory.isXValue() ||
3792 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3793 (InitCategory.isLValue() && T2->isFunctionType()))) {
3794 ICS.setStandard();
3795 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003796 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003797 : ObjCConversion? ICK_Compatible_Conversion
3798 : ICK_Identity;
3799 ICS.Standard.Third = ICK_Identity;
3800 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3801 ICS.Standard.setToType(0, T2);
3802 ICS.Standard.setToType(1, T1);
3803 ICS.Standard.setToType(2, T1);
3804 ICS.Standard.ReferenceBinding = true;
3805 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3806 // binding unless we're binding to a class prvalue.
3807 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3808 // allow the use of rvalue references in C++98/03 for the benefit of
3809 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003810 ICS.Standard.DirectBinding =
3811 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003812 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003813 ICS.Standard.IsLvalueReference = !isRValRef;
3814 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003816 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003817 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003818 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003821
Douglas Gregorf143cd52011-01-24 16:14:37 +00003822 // -- has a class type (i.e., T2 is a class type), where T1 is not
3823 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 // an xvalue, class prvalue, or function lvalue of type
3825 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003826 // "cv3 T3",
3827 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003829 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003830 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003831 // class subobject).
3832 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003833 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003834 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3835 Init, T2, /*AllowRvalues=*/true,
3836 AllowExplicit)) {
3837 // In the second case, if the reference is an rvalue reference
3838 // and the second standard conversion sequence of the
3839 // user-defined conversion sequence includes an lvalue-to-rvalue
3840 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003841 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003842 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3843 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3844
Douglas Gregor95273c32011-01-21 16:36:05 +00003845 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003846 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003847
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003848 // -- Otherwise, a temporary of type "cv1 T1" is created and
3849 // initialized from the initializer expression using the
3850 // rules for a non-reference copy initialization (8.5). The
3851 // reference is then bound to the temporary. If T1 is
3852 // reference-related to T2, cv1 must be the same
3853 // cv-qualification as, or greater cv-qualification than,
3854 // cv2; otherwise, the program is ill-formed.
3855 if (RefRelationship == Sema::Ref_Related) {
3856 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3857 // we would be reference-compatible or reference-compatible with
3858 // added qualification. But that wasn't the case, so the reference
3859 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003860 //
3861 // Note that we only want to check address spaces and cvr-qualifiers here.
3862 // ObjC GC and lifetime qualifiers aren't important.
3863 Qualifiers T1Quals = T1.getQualifiers();
3864 Qualifiers T2Quals = T2.getQualifiers();
3865 T1Quals.removeObjCGCAttr();
3866 T1Quals.removeObjCLifetime();
3867 T2Quals.removeObjCGCAttr();
3868 T2Quals.removeObjCLifetime();
3869 if (!T1Quals.compatiblyIncludes(T2Quals))
3870 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003871 }
3872
3873 // If at least one of the types is a class type, the types are not
3874 // related, and we aren't allowed any user conversions, the
3875 // reference binding fails. This case is important for breaking
3876 // recursion, since TryImplicitConversion below will attempt to
3877 // create a temporary through the use of a copy constructor.
3878 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3879 (T1->isRecordType() || T2->isRecordType()))
3880 return ICS;
3881
Douglas Gregorcba72b12011-01-21 05:18:22 +00003882 // If T1 is reference-related to T2 and the reference is an rvalue
3883 // reference, the initializer expression shall not be an lvalue.
3884 if (RefRelationship >= Sema::Ref_Related &&
3885 isRValRef && Init->Classify(S.Context).isLValue())
3886 return ICS;
3887
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003888 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003889 // When a parameter of reference type is not bound directly to
3890 // an argument expression, the conversion sequence is the one
3891 // required to convert the argument expression to the
3892 // underlying type of the reference according to
3893 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3894 // to copy-initializing a temporary of the underlying type with
3895 // the argument expression. Any difference in top-level
3896 // cv-qualification is subsumed by the initialization itself
3897 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003898 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3899 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003900 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003901 /*CStyle=*/false,
3902 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003903
3904 // Of course, that's still a reference binding.
3905 if (ICS.isStandard()) {
3906 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003907 ICS.Standard.IsLvalueReference = !isRValRef;
3908 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3909 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003910 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003911 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003912 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003913 // Don't allow rvalue references to bind to lvalues.
3914 if (DeclType->isRValueReferenceType()) {
3915 if (const ReferenceType *RefType
3916 = ICS.UserDefined.ConversionFunction->getResultType()
3917 ->getAs<LValueReferenceType>()) {
3918 if (!RefType->getPointeeType()->isFunctionType()) {
3919 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3920 DeclType);
3921 return ICS;
3922 }
3923 }
3924 }
3925
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003926 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003927 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3928 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3929 ICS.UserDefined.After.BindsToRvalue = true;
3930 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3931 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003932 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003933
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003934 return ICS;
3935}
3936
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003937static ImplicitConversionSequence
3938TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3939 bool SuppressUserConversions,
3940 bool InOverloadResolution,
3941 bool AllowObjCWritebackConversion);
3942
3943/// TryListConversion - Try to copy-initialize a value of type ToType from the
3944/// initializer list From.
3945static ImplicitConversionSequence
3946TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3947 bool SuppressUserConversions,
3948 bool InOverloadResolution,
3949 bool AllowObjCWritebackConversion) {
3950 // C++11 [over.ics.list]p1:
3951 // When an argument is an initializer list, it is not an expression and
3952 // special rules apply for converting it to a parameter type.
3953
3954 ImplicitConversionSequence Result;
3955 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003956 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003957
3958 // C++11 [over.ics.list]p2:
3959 // If the parameter type is std::initializer_list<X> or "array of X" and
3960 // all the elements can be implicitly converted to X, the implicit
3961 // conversion sequence is the worst conversion necessary to convert an
3962 // element of the list to X.
3963 // FIXME: Recognize std::initializer_list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003964 // FIXME: Implement arrays.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003965 if (ToType->isArrayType())
3966 return Result;
3967
3968 // C++11 [over.ics.list]p3:
3969 // Otherwise, if the parameter is a non-aggregate class X and overload
3970 // resolution chooses a single best constructor [...] the implicit
3971 // conversion sequence is a user-defined conversion sequence. If multiple
3972 // constructors are viable but none is better than the others, the
3973 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003974 if (ToType->isRecordType() && !ToType->isAggregateType()) {
3975 // This function can deal with initializer lists.
3976 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
3977 /*AllowExplicit=*/false,
3978 InOverloadResolution, /*CStyle=*/false,
3979 AllowObjCWritebackConversion);
3980 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003981 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003982 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003983
3984 // C++11 [over.ics.list]p4:
3985 // Otherwise, if the parameter has an aggregate type which can be
3986 // initialized from the initializer list [...] the implicit conversion
3987 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003988 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003989 // Type is an aggregate, argument is an init list. At this point it comes
3990 // down to checking whether the initialization works.
3991 // FIXME: Find out whether this parameter is consumed or not.
3992 InitializedEntity Entity =
3993 InitializedEntity::InitializeParameter(S.Context, ToType,
3994 /*Consumed=*/false);
3995 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3996 Result.setUserDefined();
3997 Result.UserDefined.Before.setAsIdentityConversion();
3998 // Initializer lists don't have a type.
3999 Result.UserDefined.Before.setFromType(QualType());
4000 Result.UserDefined.Before.setAllToTypes(QualType());
4001
4002 Result.UserDefined.After.setAsIdentityConversion();
4003 Result.UserDefined.After.setFromType(ToType);
4004 Result.UserDefined.After.setAllToTypes(ToType);
4005 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004006 return Result;
4007 }
4008
4009 // C++11 [over.ics.list]p5:
4010 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004011 if (ToType->isReferenceType()) {
4012 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4013 // mention initializer lists in any way. So we go by what list-
4014 // initialization would do and try to extrapolate from that.
4015
4016 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4017
4018 // If the initializer list has a single element that is reference-related
4019 // to the parameter type, we initialize the reference from that.
4020 if (From->getNumInits() == 1) {
4021 Expr *Init = From->getInit(0);
4022
4023 QualType T2 = Init->getType();
4024
4025 // If the initializer is the address of an overloaded function, try
4026 // to resolve the overloaded function. If all goes well, T2 is the
4027 // type of the resulting function.
4028 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4029 DeclAccessPair Found;
4030 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4031 Init, ToType, false, Found))
4032 T2 = Fn->getType();
4033 }
4034
4035 // Compute some basic properties of the types and the initializer.
4036 bool dummy1 = false;
4037 bool dummy2 = false;
4038 bool dummy3 = false;
4039 Sema::ReferenceCompareResult RefRelationship
4040 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4041 dummy2, dummy3);
4042
4043 if (RefRelationship >= Sema::Ref_Related)
4044 return TryReferenceInit(S, Init, ToType,
4045 /*FIXME:*/From->getLocStart(),
4046 SuppressUserConversions,
4047 /*AllowExplicit=*/false);
4048 }
4049
4050 // Otherwise, we bind the reference to a temporary created from the
4051 // initializer list.
4052 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4053 InOverloadResolution,
4054 AllowObjCWritebackConversion);
4055 if (Result.isFailure())
4056 return Result;
4057 assert(!Result.isEllipsis() &&
4058 "Sub-initialization cannot result in ellipsis conversion.");
4059
4060 // Can we even bind to a temporary?
4061 if (ToType->isRValueReferenceType() ||
4062 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4063 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4064 Result.UserDefined.After;
4065 SCS.ReferenceBinding = true;
4066 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4067 SCS.BindsToRvalue = true;
4068 SCS.BindsToFunctionLvalue = false;
4069 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4070 SCS.ObjCLifetimeConversionBinding = false;
4071 } else
4072 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4073 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004074 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004075 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004076
4077 // C++11 [over.ics.list]p6:
4078 // Otherwise, if the parameter type is not a class:
4079 if (!ToType->isRecordType()) {
4080 // - if the initializer list has one element, the implicit conversion
4081 // sequence is the one required to convert the element to the
4082 // parameter type.
4083 // FIXME: Catch narrowing here?
4084 unsigned NumInits = From->getNumInits();
4085 if (NumInits == 1)
4086 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4087 SuppressUserConversions,
4088 InOverloadResolution,
4089 AllowObjCWritebackConversion);
4090 // - if the initializer list has no elements, the implicit conversion
4091 // sequence is the identity conversion.
4092 else if (NumInits == 0) {
4093 Result.setStandard();
4094 Result.Standard.setAsIdentityConversion();
4095 }
4096 return Result;
4097 }
4098
4099 // C++11 [over.ics.list]p7:
4100 // In all cases other than those enumerated above, no conversion is possible
4101 return Result;
4102}
4103
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004104/// TryCopyInitialization - Try to copy-initialize a value of type
4105/// ToType from the expression From. Return the implicit conversion
4106/// sequence required to pass this argument, which may be a bad
4107/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004108/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004109/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004110static ImplicitConversionSequence
4111TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004112 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004113 bool InOverloadResolution,
4114 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004115 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4116 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4117 InOverloadResolution,AllowObjCWritebackConversion);
4118
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004119 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004120 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004121 /*FIXME:*/From->getLocStart(),
4122 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004123 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004124
John McCall5c32be02010-08-24 20:38:10 +00004125 return TryImplicitConversion(S, From, ToType,
4126 SuppressUserConversions,
4127 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004128 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004129 /*CStyle=*/false,
4130 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004131}
4132
Anna Zaks1b068122011-07-28 19:46:48 +00004133static bool TryCopyInitialization(const CanQualType FromQTy,
4134 const CanQualType ToQTy,
4135 Sema &S,
4136 SourceLocation Loc,
4137 ExprValueKind FromVK) {
4138 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4139 ImplicitConversionSequence ICS =
4140 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4141
4142 return !ICS.isBad();
4143}
4144
Douglas Gregor436424c2008-11-18 23:14:02 +00004145/// TryObjectArgumentInitialization - Try to initialize the object
4146/// parameter of the given member function (@c Method) from the
4147/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004148static ImplicitConversionSequence
4149TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004150 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004151 CXXMethodDecl *Method,
4152 CXXRecordDecl *ActingContext) {
4153 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004154 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4155 // const volatile object.
4156 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4157 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004158 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004159
4160 // Set up the conversion sequence as a "bad" conversion, to allow us
4161 // to exit early.
4162 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004163
4164 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004165 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004166 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004167 FromType = PT->getPointeeType();
4168
Douglas Gregor02824322011-01-26 19:30:28 +00004169 // When we had a pointer, it's implicitly dereferenced, so we
4170 // better have an lvalue.
4171 assert(FromClassification.isLValue());
4172 }
4173
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004174 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004175
Douglas Gregor02824322011-01-26 19:30:28 +00004176 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004178 // parameter is
4179 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004180 // - "lvalue reference to cv X" for functions declared without a
4181 // ref-qualifier or with the & ref-qualifier
4182 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004183 // ref-qualifier
4184 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004185 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004186 // cv-qualification on the member function declaration.
4187 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004189 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004190 // (C++ [over.match.funcs]p5). We perform a simplified version of
4191 // reference binding here, that allows class rvalues to bind to
4192 // non-constant references.
4193
Douglas Gregor02824322011-01-26 19:30:28 +00004194 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004195 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004196 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004197 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004198 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004199 ICS.setBad(BadConversionSequence::bad_qualifiers,
4200 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004201 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004202 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004203
4204 // Check that we have either the same type or a derived type. It
4205 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004206 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004207 ImplicitConversionKind SecondKind;
4208 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4209 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004210 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004211 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004212 else {
John McCall65eb8792010-02-25 01:37:24 +00004213 ICS.setBad(BadConversionSequence::unrelated_class,
4214 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004215 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004216 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004217
Douglas Gregor02824322011-01-26 19:30:28 +00004218 // Check the ref-qualifier.
4219 switch (Method->getRefQualifier()) {
4220 case RQ_None:
4221 // Do nothing; we don't care about lvalueness or rvalueness.
4222 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223
Douglas Gregor02824322011-01-26 19:30:28 +00004224 case RQ_LValue:
4225 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4226 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004228 ImplicitParamType);
4229 return ICS;
4230 }
4231 break;
4232
4233 case RQ_RValue:
4234 if (!FromClassification.isRValue()) {
4235 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004236 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004237 ImplicitParamType);
4238 return ICS;
4239 }
4240 break;
4241 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004242
Douglas Gregor436424c2008-11-18 23:14:02 +00004243 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004244 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004245 ICS.Standard.setAsIdentityConversion();
4246 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004247 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004248 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004249 ICS.Standard.ReferenceBinding = true;
4250 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004251 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004252 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004253 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4254 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4255 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004256 return ICS;
4257}
4258
4259/// PerformObjectArgumentInitialization - Perform initialization of
4260/// the implicit object parameter for the given Method with the given
4261/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004262ExprResult
4263Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004264 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004265 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004266 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004267 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004268 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004269 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004270
Douglas Gregor02824322011-01-26 19:30:28 +00004271 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004272 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004273 FromRecordType = PT->getPointeeType();
4274 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004275 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004276 } else {
4277 FromRecordType = From->getType();
4278 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004279 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004280 }
4281
John McCall6e9f8f62009-12-03 04:06:58 +00004282 // Note that we always use the true parent context when performing
4283 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004284 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004285 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4286 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004287 if (ICS.isBad()) {
4288 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4289 Qualifiers FromQs = FromRecordType.getQualifiers();
4290 Qualifiers ToQs = DestType.getQualifiers();
4291 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4292 if (CVR) {
4293 Diag(From->getSourceRange().getBegin(),
4294 diag::err_member_function_call_bad_cvr)
4295 << Method->getDeclName() << FromRecordType << (CVR - 1)
4296 << From->getSourceRange();
4297 Diag(Method->getLocation(), diag::note_previous_decl)
4298 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004299 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004300 }
4301 }
4302
Douglas Gregor436424c2008-11-18 23:14:02 +00004303 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004304 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004305 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004306 }
Mike Stump11289f42009-09-09 15:08:12 +00004307
John Wiegley01296292011-04-08 18:41:53 +00004308 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4309 ExprResult FromRes =
4310 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4311 if (FromRes.isInvalid())
4312 return ExprError();
4313 From = FromRes.take();
4314 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004315
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004316 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004317 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004318 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004319 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004320}
4321
Douglas Gregor5fb53972009-01-14 15:45:31 +00004322/// TryContextuallyConvertToBool - Attempt to contextually convert the
4323/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004324static ImplicitConversionSequence
4325TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004326 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004327 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004328 // FIXME: Are these flags correct?
4329 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004330 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004331 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004332 /*CStyle=*/false,
4333 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004334}
4335
4336/// PerformContextuallyConvertToBool - Perform a contextual conversion
4337/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004338ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004339 if (checkPlaceholderForOverload(*this, From))
4340 return ExprError();
4341
John McCall5c32be02010-08-24 20:38:10 +00004342 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004343 if (!ICS.isBad())
4344 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004345
Fariborz Jahanian76197412009-11-18 18:26:29 +00004346 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004347 return Diag(From->getSourceRange().getBegin(),
4348 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004349 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004350 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004351}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004352
John McCallfec112d2011-09-09 06:11:02 +00004353/// dropPointerConversions - If the given standard conversion sequence
4354/// involves any pointer conversions, remove them. This may change
4355/// the result type of the conversion sequence.
4356static void dropPointerConversion(StandardConversionSequence &SCS) {
4357 if (SCS.Second == ICK_Pointer_Conversion) {
4358 SCS.Second = ICK_Identity;
4359 SCS.Third = ICK_Identity;
4360 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4361 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004362}
John McCall5c32be02010-08-24 20:38:10 +00004363
John McCallfec112d2011-09-09 06:11:02 +00004364/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4365/// convert the expression From to an Objective-C pointer type.
4366static ImplicitConversionSequence
4367TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4368 // Do an implicit conversion to 'id'.
4369 QualType Ty = S.Context.getObjCIdType();
4370 ImplicitConversionSequence ICS
4371 = TryImplicitConversion(S, From, Ty,
4372 // FIXME: Are these flags correct?
4373 /*SuppressUserConversions=*/false,
4374 /*AllowExplicit=*/true,
4375 /*InOverloadResolution=*/false,
4376 /*CStyle=*/false,
4377 /*AllowObjCWritebackConversion=*/false);
4378
4379 // Strip off any final conversions to 'id'.
4380 switch (ICS.getKind()) {
4381 case ImplicitConversionSequence::BadConversion:
4382 case ImplicitConversionSequence::AmbiguousConversion:
4383 case ImplicitConversionSequence::EllipsisConversion:
4384 break;
4385
4386 case ImplicitConversionSequence::UserDefinedConversion:
4387 dropPointerConversion(ICS.UserDefined.After);
4388 break;
4389
4390 case ImplicitConversionSequence::StandardConversion:
4391 dropPointerConversion(ICS.Standard);
4392 break;
4393 }
4394
4395 return ICS;
4396}
4397
4398/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4399/// conversion of the expression From to an Objective-C pointer type.
4400ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004401 if (checkPlaceholderForOverload(*this, From))
4402 return ExprError();
4403
John McCall8b07ec22010-05-15 11:32:37 +00004404 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004405 ImplicitConversionSequence ICS =
4406 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004407 if (!ICS.isBad())
4408 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004409 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004410}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004411
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004412/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004413/// enumeration type.
4414///
4415/// This routine will attempt to convert an expression of class type to an
4416/// integral or enumeration type, if that class type only has a single
4417/// conversion to an integral or enumeration type.
4418///
Douglas Gregor4799d032010-06-30 00:20:43 +00004419/// \param Loc The source location of the construct that requires the
4420/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004421///
Douglas Gregor4799d032010-06-30 00:20:43 +00004422/// \param FromE The expression we're converting from.
4423///
4424/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4425/// have integral or enumeration type.
4426///
4427/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4428/// incomplete class type.
4429///
4430/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4431/// explicit conversion function (because no implicit conversion functions
4432/// were available). This is a recovery mode.
4433///
4434/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4435/// showing which conversion was picked.
4436///
4437/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4438/// conversion function that could convert to integral or enumeration type.
4439///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004440/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004441/// usable conversion function.
4442///
4443/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4444/// function, which may be an extension in this case.
4445///
4446/// \returns The expression, converted to an integral or enumeration type if
4447/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448ExprResult
John McCallb268a282010-08-23 23:25:46 +00004449Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004450 const PartialDiagnostic &NotIntDiag,
4451 const PartialDiagnostic &IncompleteDiag,
4452 const PartialDiagnostic &ExplicitConvDiag,
4453 const PartialDiagnostic &ExplicitConvNote,
4454 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004455 const PartialDiagnostic &AmbigNote,
4456 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004457 // We can't perform any more checking for type-dependent expressions.
4458 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004459 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004460
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004461 // If the expression already has integral or enumeration type, we're golden.
4462 QualType T = From->getType();
4463 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004464 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004465
4466 // FIXME: Check for missing '()' if T is a function type?
4467
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468 // 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 +00004469 // expression of integral or enumeration type.
4470 const RecordType *RecordTy = T->getAs<RecordType>();
4471 if (!RecordTy || !getLangOptions().CPlusPlus) {
4472 Diag(Loc, NotIntDiag)
4473 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004474 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004475 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004477 // We must have a complete class type.
4478 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004479 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004480
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004481 // Look for a conversion to an integral or enumeration type.
4482 UnresolvedSet<4> ViableConversions;
4483 UnresolvedSet<4> ExplicitConversions;
4484 const UnresolvedSetImpl *Conversions
4485 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004486
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004487 bool HadMultipleCandidates = (Conversions->size() > 1);
4488
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004489 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004490 E = Conversions->end();
4491 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004492 ++I) {
4493 if (CXXConversionDecl *Conversion
4494 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4495 if (Conversion->getConversionType().getNonReferenceType()
4496 ->isIntegralOrEnumerationType()) {
4497 if (Conversion->isExplicit())
4498 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4499 else
4500 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4501 }
4502 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004503
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004504 switch (ViableConversions.size()) {
4505 case 0:
4506 if (ExplicitConversions.size() == 1) {
4507 DeclAccessPair Found = ExplicitConversions[0];
4508 CXXConversionDecl *Conversion
4509 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004511 // The user probably meant to invoke the given explicit
4512 // conversion; use it.
4513 QualType ConvTy
4514 = Conversion->getConversionType().getNonReferenceType();
4515 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004516 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004518 Diag(Loc, ExplicitConvDiag)
4519 << T << ConvTy
4520 << FixItHint::CreateInsertion(From->getLocStart(),
4521 "static_cast<" + TypeStr + ">(")
4522 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4523 ")");
4524 Diag(Conversion->getLocation(), ExplicitConvNote)
4525 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526
4527 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004528 // explicit conversion function.
4529 if (isSFINAEContext())
4530 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004531
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004532 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004533 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4534 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004535 if (Result.isInvalid())
4536 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004537 // Record usage of conversion in an implicit cast.
4538 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4539 CK_UserDefinedConversion,
4540 Result.get(), 0,
4541 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004544 // We'll complain below about a non-integral condition type.
4545 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004547 case 1: {
4548 // Apply this conversion.
4549 DeclAccessPair Found = ViableConversions[0];
4550 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551
Douglas Gregor4799d032010-06-30 00:20:43 +00004552 CXXConversionDecl *Conversion
4553 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4554 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004555 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004556 if (ConvDiag.getDiagID()) {
4557 if (isSFINAEContext())
4558 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559
Douglas Gregor4799d032010-06-30 00:20:43 +00004560 Diag(Loc, ConvDiag)
4561 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4562 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004563
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004564 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4565 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004566 if (Result.isInvalid())
4567 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004568 // Record usage of conversion in an implicit cast.
4569 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4570 CK_UserDefinedConversion,
4571 Result.get(), 0,
4572 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004573 break;
4574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004576 default:
4577 Diag(Loc, AmbigDiag)
4578 << T << From->getSourceRange();
4579 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4580 CXXConversionDecl *Conv
4581 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4582 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4583 Diag(Conv->getLocation(), AmbigNote)
4584 << ConvTy->isEnumeralType() << ConvTy;
4585 }
John McCallb268a282010-08-23 23:25:46 +00004586 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004587 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004588
Douglas Gregor5823da32010-06-29 23:25:20 +00004589 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004590 Diag(Loc, NotIntDiag)
4591 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004592
John McCallb268a282010-08-23 23:25:46 +00004593 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004594}
4595
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004596/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004597/// candidate functions, using the given function call arguments. If
4598/// @p SuppressUserConversions, then don't allow user-defined
4599/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004600///
4601/// \para PartialOverloading true if we are performing "partial" overloading
4602/// based on an incomplete set of function arguments. This feature is used by
4603/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004604void
4605Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004606 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004607 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004608 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004609 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004610 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004611 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004612 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004613 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004614 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004615 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004616
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004618 if (!isa<CXXConstructorDecl>(Method)) {
4619 // If we get here, it's because we're calling a member function
4620 // that is named without a member access expression (e.g.,
4621 // "this->f") that was either written explicitly or created
4622 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004623 // function, e.g., X::f(). We use an empty type for the implied
4624 // object argument (C++ [over.call.func]p3), and the acting context
4625 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004626 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004627 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004628 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004629 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004630 return;
4631 }
4632 // We treat a constructor like a non-member function, since its object
4633 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004634 }
4635
Douglas Gregorff7028a2009-11-13 23:59:09 +00004636 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004637 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004638
Douglas Gregor27381f32009-11-23 12:27:39 +00004639 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004640 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004641
Douglas Gregorffe14e32009-11-14 01:20:54 +00004642 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4643 // C++ [class.copy]p3:
4644 // A member function template is never instantiated to perform the copy
4645 // of a class object to an object of its class type.
4646 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004647 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004648 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004649 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4650 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004651 return;
4652 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004653
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004654 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004655 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00004656 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004657 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004658 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004659 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004660 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004661 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004663 unsigned NumArgsInProto = Proto->getNumArgs();
4664
4665 // (C++ 13.3.2p2): A candidate function having fewer than m
4666 // parameters is viable only if it has an ellipsis in its parameter
4667 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004669 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004670 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004671 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004672 return;
4673 }
4674
4675 // (C++ 13.3.2p2): A candidate function having more than m parameters
4676 // is viable only if the (m+1)st parameter has a default argument
4677 // (8.3.6). For the purposes of overload resolution, the
4678 // parameter list is truncated on the right, so that there are
4679 // exactly m parameters.
4680 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004681 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004682 // Not enough arguments.
4683 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004684 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004685 return;
4686 }
4687
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004688 // (CUDA B.1): Check for invalid calls between targets.
4689 if (getLangOptions().CUDA)
4690 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4691 if (CheckCUDATarget(Caller, Function)) {
4692 Candidate.Viable = false;
4693 Candidate.FailureKind = ovl_fail_bad_target;
4694 return;
4695 }
4696
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004697 // Determine the implicit conversion sequences for each of the
4698 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004699 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4700 if (ArgIdx < NumArgsInProto) {
4701 // (C++ 13.3.2p3): for F to be a viable function, there shall
4702 // exist for each argument an implicit conversion sequence
4703 // (13.3.3.1) that converts that argument to the corresponding
4704 // parameter of F.
4705 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004706 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004707 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004709 /*InOverloadResolution=*/true,
4710 /*AllowObjCWritebackConversion=*/
4711 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004712 if (Candidate.Conversions[ArgIdx].isBad()) {
4713 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004714 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004715 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004716 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004717 } else {
4718 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4719 // argument for which there is no corresponding parameter is
4720 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004721 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004722 }
4723 }
4724}
4725
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004726/// \brief Add all of the function declarations in the given function set to
4727/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004728void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004729 Expr **Args, unsigned NumArgs,
4730 OverloadCandidateSet& CandidateSet,
4731 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004732 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004733 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4734 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004735 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004736 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004737 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004738 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004739 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004740 CandidateSet, SuppressUserConversions);
4741 else
John McCalla0296f72010-03-19 07:35:19 +00004742 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004743 SuppressUserConversions);
4744 } else {
John McCalla0296f72010-03-19 07:35:19 +00004745 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004746 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4747 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004748 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004749 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004750 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004751 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004752 Args[0]->Classify(Context),
4753 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004754 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004755 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004756 else
John McCalla0296f72010-03-19 07:35:19 +00004757 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004758 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004759 Args, NumArgs, CandidateSet,
4760 SuppressUserConversions);
4761 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004762 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004763}
4764
John McCallf0f1cf02009-11-17 07:50:12 +00004765/// AddMethodCandidate - Adds a named decl (which is some kind of
4766/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004767void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004768 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004769 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004770 Expr **Args, unsigned NumArgs,
4771 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004772 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004773 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004774 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004775
4776 if (isa<UsingShadowDecl>(Decl))
4777 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
John McCallf0f1cf02009-11-17 07:50:12 +00004779 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4780 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4781 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004782 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4783 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004784 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004785 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004786 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004787 } else {
John McCalla0296f72010-03-19 07:35:19 +00004788 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004789 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004790 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004791 }
4792}
4793
Douglas Gregor436424c2008-11-18 23:14:02 +00004794/// AddMethodCandidate - Adds the given C++ member function to the set
4795/// of candidate functions, using the given function call arguments
4796/// and the object argument (@c Object). For example, in a call
4797/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4798/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4799/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004800/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004801void
John McCalla0296f72010-03-19 07:35:19 +00004802Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004803 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004804 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004805 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004806 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004807 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004808 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004809 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004810 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004811 assert(!isa<CXXConstructorDecl>(Method) &&
4812 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004813
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004814 if (!CandidateSet.isNewCandidate(Method))
4815 return;
4816
Douglas Gregor27381f32009-11-23 12:27:39 +00004817 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004818 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004819
Douglas Gregor436424c2008-11-18 23:14:02 +00004820 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004821 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00004822 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004823 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004824 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004825 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004826 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004827
4828 unsigned NumArgsInProto = Proto->getNumArgs();
4829
4830 // (C++ 13.3.2p2): A candidate function having fewer than m
4831 // parameters is viable only if it has an ellipsis in its parameter
4832 // list (8.3.5).
4833 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4834 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004835 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004836 return;
4837 }
4838
4839 // (C++ 13.3.2p2): A candidate function having more than m parameters
4840 // is viable only if the (m+1)st parameter has a default argument
4841 // (8.3.6). For the purposes of overload resolution, the
4842 // parameter list is truncated on the right, so that there are
4843 // exactly m parameters.
4844 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4845 if (NumArgs < MinRequiredArgs) {
4846 // Not enough arguments.
4847 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004848 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004849 return;
4850 }
4851
4852 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00004853
John McCall6e9f8f62009-12-03 04:06:58 +00004854 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004855 // The implicit object argument is ignored.
4856 Candidate.IgnoreObjectArgument = true;
4857 else {
4858 // Determine the implicit conversion sequence for the object
4859 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004860 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004861 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4862 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004863 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004864 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004865 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004866 return;
4867 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004868 }
4869
4870 // Determine the implicit conversion sequences for each of the
4871 // arguments.
4872 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4873 if (ArgIdx < NumArgsInProto) {
4874 // (C++ 13.3.2p3): for F to be a viable function, there shall
4875 // exist for each argument an implicit conversion sequence
4876 // (13.3.3.1) that converts that argument to the corresponding
4877 // parameter of F.
4878 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004879 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004880 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004881 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004882 /*InOverloadResolution=*/true,
4883 /*AllowObjCWritebackConversion=*/
4884 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004885 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004886 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004887 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004888 break;
4889 }
4890 } else {
4891 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4892 // argument for which there is no corresponding parameter is
4893 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004894 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004895 }
4896 }
4897}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004898
Douglas Gregor97628d62009-08-21 00:16:32 +00004899/// \brief Add a C++ member function template as a candidate to the candidate
4900/// set, using template argument deduction to produce an appropriate member
4901/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004902void
Douglas Gregor97628d62009-08-21 00:16:32 +00004903Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004904 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004905 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004906 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004907 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004908 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004909 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004910 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004911 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004912 if (!CandidateSet.isNewCandidate(MethodTmpl))
4913 return;
4914
Douglas Gregor97628d62009-08-21 00:16:32 +00004915 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004916 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004917 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004918 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004919 // candidate functions in the usual way.113) A given name can refer to one
4920 // or more function templates and also to a set of overloaded non-template
4921 // functions. In such a case, the candidate functions generated from each
4922 // function template are combined with the set of non-template candidate
4923 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004924 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004925 FunctionDecl *Specialization = 0;
4926 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004927 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004928 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004929 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004930 Candidate.FoundDecl = FoundDecl;
4931 Candidate.Function = MethodTmpl->getTemplatedDecl();
4932 Candidate.Viable = false;
4933 Candidate.FailureKind = ovl_fail_bad_deduction;
4934 Candidate.IsSurrogate = false;
4935 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004936 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004937 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004938 Info);
4939 return;
4940 }
Mike Stump11289f42009-09-09 15:08:12 +00004941
Douglas Gregor97628d62009-08-21 00:16:32 +00004942 // Add the function template specialization produced by template argument
4943 // deduction as a candidate.
4944 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004945 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004946 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004947 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004948 ActingContext, ObjectType, ObjectClassification,
4949 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004950}
4951
Douglas Gregor05155d82009-08-21 23:19:43 +00004952/// \brief Add a C++ function template specialization as a candidate
4953/// in the candidate set, using template argument deduction to produce
4954/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004955void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004956Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004957 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004958 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004959 Expr **Args, unsigned NumArgs,
4960 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004961 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004962 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4963 return;
4964
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004965 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004966 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004967 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004968 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004969 // candidate functions in the usual way.113) A given name can refer to one
4970 // or more function templates and also to a set of overloaded non-template
4971 // functions. In such a case, the candidate functions generated from each
4972 // function template are combined with the set of non-template candidate
4973 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004974 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004975 FunctionDecl *Specialization = 0;
4976 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004977 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004978 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004979 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00004980 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004981 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4982 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004983 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004984 Candidate.IsSurrogate = false;
4985 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004986 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004988 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004989 return;
4990 }
Mike Stump11289f42009-09-09 15:08:12 +00004991
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004992 // Add the function template specialization produced by template argument
4993 // deduction as a candidate.
4994 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004995 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004996 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004997}
Mike Stump11289f42009-09-09 15:08:12 +00004998
Douglas Gregora1f013e2008-11-07 22:36:19 +00004999/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005000/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005001/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005002/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005003/// (which may or may not be the same type as the type that the
5004/// conversion function produces).
5005void
5006Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005007 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005008 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005009 Expr *From, QualType ToType,
5010 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005011 assert(!Conversion->getDescribedFunctionTemplate() &&
5012 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005013 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005014 if (!CandidateSet.isNewCandidate(Conversion))
5015 return;
5016
Douglas Gregor27381f32009-11-23 12:27:39 +00005017 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005018 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005019
Douglas Gregora1f013e2008-11-07 22:36:19 +00005020 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005021 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005022 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005023 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005024 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005025 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005026 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005027 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005028 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005029 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005030 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005031
Douglas Gregor6affc782010-08-19 15:37:02 +00005032 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033 // For conversion functions, the function is considered to be a member of
5034 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005035 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005036 //
5037 // Determine the implicit conversion sequence for the implicit
5038 // object parameter.
5039 QualType ImplicitParamType = From->getType();
5040 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5041 ImplicitParamType = FromPtrType->getPointeeType();
5042 CXXRecordDecl *ConversionContext
5043 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005045 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005046 = TryObjectArgumentInitialization(*this, From->getType(),
5047 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005048 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005049
John McCall0d1da222010-01-12 00:44:57 +00005050 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005051 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005052 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005053 return;
5054 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005055
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005056 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005057 // derived to base as such conversions are given Conversion Rank. They only
5058 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5059 QualType FromCanon
5060 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5061 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5062 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5063 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005064 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005065 return;
5066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
Douglas Gregora1f013e2008-11-07 22:36:19 +00005068 // To determine what the conversion from the result of calling the
5069 // conversion function to the type we're eventually trying to
5070 // convert to (ToType), we need to synthesize a call to the
5071 // conversion function and attempt copy initialization from it. This
5072 // makes sure that we get the right semantics with respect to
5073 // lvalues/rvalues and the type. Fortunately, we can allocate this
5074 // call on the stack and we don't need its arguments to be
5075 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005076 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005077 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005078 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5079 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005080 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005081 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005082
Richard Smith48d24642011-07-13 22:53:21 +00005083 QualType ConversionType = Conversion->getConversionType();
5084 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005085 Candidate.Viable = false;
5086 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5087 return;
5088 }
5089
Richard Smith48d24642011-07-13 22:53:21 +00005090 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005091
Mike Stump11289f42009-09-09 15:08:12 +00005092 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005093 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5094 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005095 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005096 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005097 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005098 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005099 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005100 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005101 /*InOverloadResolution=*/false,
5102 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005103
John McCall0d1da222010-01-12 00:44:57 +00005104 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005105 case ImplicitConversionSequence::StandardConversion:
5106 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005107
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005108 // C++ [over.ics.user]p3:
5109 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005110 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005111 // shall have exact match rank.
5112 if (Conversion->getPrimaryTemplate() &&
5113 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5114 Candidate.Viable = false;
5115 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117
Douglas Gregorcba72b12011-01-21 05:18:22 +00005118 // C++0x [dcl.init.ref]p5:
5119 // In the second case, if the reference is an rvalue reference and
5120 // the second standard conversion sequence of the user-defined
5121 // conversion sequence includes an lvalue-to-rvalue conversion, the
5122 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005123 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005124 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5125 Candidate.Viable = false;
5126 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5127 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005128 break;
5129
5130 case ImplicitConversionSequence::BadConversion:
5131 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005132 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005133 break;
5134
5135 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005136 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005137 "Can only end up with a standard conversion sequence or failure");
5138 }
5139}
5140
Douglas Gregor05155d82009-08-21 23:19:43 +00005141/// \brief Adds a conversion function template specialization
5142/// candidate to the overload set, using template argument deduction
5143/// to deduce the template arguments of the conversion function
5144/// template from the type that we are converting to (C++
5145/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005146void
Douglas Gregor05155d82009-08-21 23:19:43 +00005147Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005148 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005149 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005150 Expr *From, QualType ToType,
5151 OverloadCandidateSet &CandidateSet) {
5152 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5153 "Only conversion function templates permitted here");
5154
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005155 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5156 return;
5157
John McCallbc077cf2010-02-08 23:07:23 +00005158 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005159 CXXConversionDecl *Specialization = 0;
5160 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005161 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005162 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005163 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005164 Candidate.FoundDecl = FoundDecl;
5165 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5166 Candidate.Viable = false;
5167 Candidate.FailureKind = ovl_fail_bad_deduction;
5168 Candidate.IsSurrogate = false;
5169 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005170 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005172 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005173 return;
5174 }
Mike Stump11289f42009-09-09 15:08:12 +00005175
Douglas Gregor05155d82009-08-21 23:19:43 +00005176 // Add the conversion function template specialization produced by
5177 // template argument deduction as a candidate.
5178 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005179 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005180 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005181}
5182
Douglas Gregorab7897a2008-11-19 22:57:39 +00005183/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5184/// converts the given @c Object to a function pointer via the
5185/// conversion function @c Conversion, and then attempts to call it
5186/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5187/// the type of function that we'll eventually be calling.
5188void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005189 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005190 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005191 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005192 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005193 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005194 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005195 if (!CandidateSet.isNewCandidate(Conversion))
5196 return;
5197
Douglas Gregor27381f32009-11-23 12:27:39 +00005198 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005199 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005200
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005201 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005202 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005203 Candidate.Function = 0;
5204 Candidate.Surrogate = Conversion;
5205 Candidate.Viable = true;
5206 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005207 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005208 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005209
5210 // Determine the implicit conversion sequence for the implicit
5211 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005212 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005213 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005214 Object->Classify(Context),
5215 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005216 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005217 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005218 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005219 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005220 return;
5221 }
5222
5223 // The first conversion is actually a user-defined conversion whose
5224 // first conversion is ObjectInit's standard conversion (which is
5225 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005226 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005227 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005228 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005229 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005230 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005231 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005232 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005233 = Candidate.Conversions[0].UserDefined.Before;
5234 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5235
Mike Stump11289f42009-09-09 15:08:12 +00005236 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005237 unsigned NumArgsInProto = Proto->getNumArgs();
5238
5239 // (C++ 13.3.2p2): A candidate function having fewer than m
5240 // parameters is viable only if it has an ellipsis in its parameter
5241 // list (8.3.5).
5242 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5243 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005244 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005245 return;
5246 }
5247
5248 // Function types don't have any default arguments, so just check if
5249 // we have enough arguments.
5250 if (NumArgs < NumArgsInProto) {
5251 // Not enough arguments.
5252 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005253 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005254 return;
5255 }
5256
5257 // Determine the implicit conversion sequences for each of the
5258 // arguments.
5259 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5260 if (ArgIdx < NumArgsInProto) {
5261 // (C++ 13.3.2p3): for F to be a viable function, there shall
5262 // exist for each argument an implicit conversion sequence
5263 // (13.3.3.1) that converts that argument to the corresponding
5264 // parameter of F.
5265 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005266 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005267 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005268 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005269 /*InOverloadResolution=*/false,
5270 /*AllowObjCWritebackConversion=*/
5271 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005272 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005273 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005274 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005275 break;
5276 }
5277 } else {
5278 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5279 // argument for which there is no corresponding parameter is
5280 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005281 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005282 }
5283 }
5284}
5285
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005286/// \brief Add overload candidates for overloaded operators that are
5287/// member functions.
5288///
5289/// Add the overloaded operator candidates that are member functions
5290/// for the operator Op that was used in an operator expression such
5291/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5292/// CandidateSet will store the added overload candidates. (C++
5293/// [over.match.oper]).
5294void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5295 SourceLocation OpLoc,
5296 Expr **Args, unsigned NumArgs,
5297 OverloadCandidateSet& CandidateSet,
5298 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005299 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5300
5301 // C++ [over.match.oper]p3:
5302 // For a unary operator @ with an operand of a type whose
5303 // cv-unqualified version is T1, and for a binary operator @ with
5304 // a left operand of a type whose cv-unqualified version is T1 and
5305 // a right operand of a type whose cv-unqualified version is T2,
5306 // three sets of candidate functions, designated member
5307 // candidates, non-member candidates and built-in candidates, are
5308 // constructed as follows:
5309 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005310
5311 // -- If T1 is a class type, the set of member candidates is the
5312 // result of the qualified lookup of T1::operator@
5313 // (13.3.1.1.1); otherwise, the set of member candidates is
5314 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005315 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005316 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005317 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005318 return;
Mike Stump11289f42009-09-09 15:08:12 +00005319
John McCall27b18f82009-11-17 02:14:36 +00005320 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5321 LookupQualifiedName(Operators, T1Rec->getDecl());
5322 Operators.suppressDiagnostics();
5323
Mike Stump11289f42009-09-09 15:08:12 +00005324 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005325 OperEnd = Operators.end();
5326 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005327 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005328 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005329 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005330 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005331 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005332 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005333}
5334
Douglas Gregora11693b2008-11-12 17:17:38 +00005335/// AddBuiltinCandidate - Add a candidate for a built-in
5336/// operator. ResultTy and ParamTys are the result and parameter types
5337/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005338/// arguments being passed to the candidate. IsAssignmentOperator
5339/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005340/// operator. NumContextualBoolArguments is the number of arguments
5341/// (at the beginning of the argument list) that will be contextually
5342/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005343void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005344 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005345 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005346 bool IsAssignmentOperator,
5347 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005348 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005349 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005350
Douglas Gregora11693b2008-11-12 17:17:38 +00005351 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005352 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005353 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005354 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005355 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005356 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005357 Candidate.BuiltinTypes.ResultTy = ResultTy;
5358 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5359 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5360
5361 // Determine the implicit conversion sequences for each of the
5362 // arguments.
5363 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005364 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005365 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005366 // C++ [over.match.oper]p4:
5367 // For the built-in assignment operators, conversions of the
5368 // left operand are restricted as follows:
5369 // -- no temporaries are introduced to hold the left operand, and
5370 // -- no user-defined conversions are applied to the left
5371 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005372 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005373 //
5374 // We block these conversions by turning off user-defined
5375 // conversions, since that is the only way that initialization of
5376 // a reference to a non-class type can occur from something that
5377 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005378 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005379 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005380 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005381 Candidate.Conversions[ArgIdx]
5382 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005383 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005384 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005385 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005386 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005387 /*InOverloadResolution=*/false,
5388 /*AllowObjCWritebackConversion=*/
5389 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005390 }
John McCall0d1da222010-01-12 00:44:57 +00005391 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005392 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005393 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005394 break;
5395 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005396 }
5397}
5398
5399/// BuiltinCandidateTypeSet - A set of types that will be used for the
5400/// candidate operator functions for built-in operators (C++
5401/// [over.built]). The types are separated into pointer types and
5402/// enumeration types.
5403class BuiltinCandidateTypeSet {
5404 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005405 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005406
5407 /// PointerTypes - The set of pointer types that will be used in the
5408 /// built-in candidates.
5409 TypeSet PointerTypes;
5410
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005411 /// MemberPointerTypes - The set of member pointer types that will be
5412 /// used in the built-in candidates.
5413 TypeSet MemberPointerTypes;
5414
Douglas Gregora11693b2008-11-12 17:17:38 +00005415 /// EnumerationTypes - The set of enumeration types that will be
5416 /// used in the built-in candidates.
5417 TypeSet EnumerationTypes;
5418
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005419 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005420 /// candidates.
5421 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005422
5423 /// \brief A flag indicating non-record types are viable candidates
5424 bool HasNonRecordTypes;
5425
5426 /// \brief A flag indicating whether either arithmetic or enumeration types
5427 /// were present in the candidate set.
5428 bool HasArithmeticOrEnumeralTypes;
5429
Douglas Gregor80af3132011-05-21 23:15:46 +00005430 /// \brief A flag indicating whether the nullptr type was present in the
5431 /// candidate set.
5432 bool HasNullPtrType;
5433
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005434 /// Sema - The semantic analysis instance where we are building the
5435 /// candidate type set.
5436 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005437
Douglas Gregora11693b2008-11-12 17:17:38 +00005438 /// Context - The AST context in which we will build the type sets.
5439 ASTContext &Context;
5440
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005441 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5442 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005443 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005444
5445public:
5446 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005447 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005448
Mike Stump11289f42009-09-09 15:08:12 +00005449 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005450 : HasNonRecordTypes(false),
5451 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005452 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005453 SemaRef(SemaRef),
5454 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005455
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005456 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005457 SourceLocation Loc,
5458 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005459 bool AllowExplicitConversions,
5460 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005461
5462 /// pointer_begin - First pointer type found;
5463 iterator pointer_begin() { return PointerTypes.begin(); }
5464
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005465 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005466 iterator pointer_end() { return PointerTypes.end(); }
5467
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005468 /// member_pointer_begin - First member pointer type found;
5469 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5470
5471 /// member_pointer_end - Past the last member pointer type found;
5472 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5473
Douglas Gregora11693b2008-11-12 17:17:38 +00005474 /// enumeration_begin - First enumeration type found;
5475 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5476
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005477 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005478 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005479
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005480 iterator vector_begin() { return VectorTypes.begin(); }
5481 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005482
5483 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5484 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005485 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005486};
5487
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005488/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005489/// the set of pointer types along with any more-qualified variants of
5490/// that type. For example, if @p Ty is "int const *", this routine
5491/// will add "int const *", "int const volatile *", "int const
5492/// restrict *", and "int const volatile restrict *" to the set of
5493/// pointer types. Returns true if the add of @p Ty itself succeeded,
5494/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005495///
5496/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005497bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005498BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5499 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005500
Douglas Gregora11693b2008-11-12 17:17:38 +00005501 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005502 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005503 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005504
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005505 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005506 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005507 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005508 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005509 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005510 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005511 buildObjCPtr = true;
5512 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005513 else
David Blaikie83d382b2011-09-23 05:06:16 +00005514 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005515 }
5516 else
5517 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005518
Sebastian Redl4990a632009-11-18 20:39:26 +00005519 // Don't add qualified variants of arrays. For one, they're not allowed
5520 // (the qualifier would sink to the element type), and for another, the
5521 // only overload situation where it matters is subscript or pointer +- int,
5522 // and those shouldn't have qualifier variants anyway.
5523 if (PointeeTy->isArrayType())
5524 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005525 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005526 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005527 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005528 bool hasVolatile = VisibleQuals.hasVolatile();
5529 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005530
John McCall8ccfcb52009-09-24 19:53:00 +00005531 // Iterate through all strict supersets of BaseCVR.
5532 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5533 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005534 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5535 // in the types.
5536 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5537 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005538 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005539 if (!buildObjCPtr)
5540 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5541 else
5542 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005543 }
5544
5545 return true;
5546}
5547
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005548/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5549/// to the set of pointer types along with any more-qualified variants of
5550/// that type. For example, if @p Ty is "int const *", this routine
5551/// will add "int const *", "int const volatile *", "int const
5552/// restrict *", and "int const volatile restrict *" to the set of
5553/// pointer types. Returns true if the add of @p Ty itself succeeded,
5554/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005555///
5556/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005557bool
5558BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5559 QualType Ty) {
5560 // Insert this type.
5561 if (!MemberPointerTypes.insert(Ty))
5562 return false;
5563
John McCall8ccfcb52009-09-24 19:53:00 +00005564 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5565 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005566
John McCall8ccfcb52009-09-24 19:53:00 +00005567 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005568 // Don't add qualified variants of arrays. For one, they're not allowed
5569 // (the qualifier would sink to the element type), and for another, the
5570 // only overload situation where it matters is subscript or pointer +- int,
5571 // and those shouldn't have qualifier variants anyway.
5572 if (PointeeTy->isArrayType())
5573 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005574 const Type *ClassTy = PointerTy->getClass();
5575
5576 // Iterate through all strict supersets of the pointee type's CVR
5577 // qualifiers.
5578 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5579 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5580 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005581
John McCall8ccfcb52009-09-24 19:53:00 +00005582 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005583 MemberPointerTypes.insert(
5584 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005585 }
5586
5587 return true;
5588}
5589
Douglas Gregora11693b2008-11-12 17:17:38 +00005590/// AddTypesConvertedFrom - Add each of the types to which the type @p
5591/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005592/// primarily interested in pointer types and enumeration types. We also
5593/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005594/// AllowUserConversions is true if we should look at the conversion
5595/// functions of a class type, and AllowExplicitConversions if we
5596/// should also include the explicit conversion functions of a class
5597/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005598void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005599BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005600 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005601 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005602 bool AllowExplicitConversions,
5603 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005604 // Only deal with canonical types.
5605 Ty = Context.getCanonicalType(Ty);
5606
5607 // Look through reference types; they aren't part of the type of an
5608 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005609 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005610 Ty = RefTy->getPointeeType();
5611
John McCall33ddac02011-01-19 10:06:00 +00005612 // If we're dealing with an array type, decay to the pointer.
5613 if (Ty->isArrayType())
5614 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5615
5616 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005617 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005618
Chandler Carruth00a38332010-12-13 01:44:01 +00005619 // Flag if we ever add a non-record type.
5620 const RecordType *TyRec = Ty->getAs<RecordType>();
5621 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5622
Chandler Carruth00a38332010-12-13 01:44:01 +00005623 // Flag if we encounter an arithmetic type.
5624 HasArithmeticOrEnumeralTypes =
5625 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5626
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005627 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5628 PointerTypes.insert(Ty);
5629 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005630 // Insert our type, and its more-qualified variants, into the set
5631 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005632 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005633 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005634 } else if (Ty->isMemberPointerType()) {
5635 // Member pointers are far easier, since the pointee can't be converted.
5636 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5637 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005638 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005639 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005640 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005641 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005642 // We treat vector types as arithmetic types in many contexts as an
5643 // extension.
5644 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005645 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005646 } else if (Ty->isNullPtrType()) {
5647 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005648 } else if (AllowUserConversions && TyRec) {
5649 // No conversion functions in incomplete types.
5650 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5651 return;
Mike Stump11289f42009-09-09 15:08:12 +00005652
Chandler Carruth00a38332010-12-13 01:44:01 +00005653 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5654 const UnresolvedSetImpl *Conversions
5655 = ClassDecl->getVisibleConversionFunctions();
5656 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5657 E = Conversions->end(); I != E; ++I) {
5658 NamedDecl *D = I.getDecl();
5659 if (isa<UsingShadowDecl>(D))
5660 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005661
Chandler Carruth00a38332010-12-13 01:44:01 +00005662 // Skip conversion function templates; they don't tell us anything
5663 // about which builtin types we can convert to.
5664 if (isa<FunctionTemplateDecl>(D))
5665 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005666
Chandler Carruth00a38332010-12-13 01:44:01 +00005667 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5668 if (AllowExplicitConversions || !Conv->isExplicit()) {
5669 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5670 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005671 }
5672 }
5673 }
5674}
5675
Douglas Gregor84605ae2009-08-24 13:43:27 +00005676/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5677/// the volatile- and non-volatile-qualified assignment operators for the
5678/// given type to the candidate set.
5679static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5680 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005681 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005682 unsigned NumArgs,
5683 OverloadCandidateSet &CandidateSet) {
5684 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005685
Douglas Gregor84605ae2009-08-24 13:43:27 +00005686 // T& operator=(T&, T)
5687 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5688 ParamTypes[1] = T;
5689 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5690 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005691
Douglas Gregor84605ae2009-08-24 13:43:27 +00005692 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5693 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005694 ParamTypes[0]
5695 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005696 ParamTypes[1] = T;
5697 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005698 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005699 }
5700}
Mike Stump11289f42009-09-09 15:08:12 +00005701
Sebastian Redl1054fae2009-10-25 17:03:50 +00005702/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5703/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005704static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5705 Qualifiers VRQuals;
5706 const RecordType *TyRec;
5707 if (const MemberPointerType *RHSMPType =
5708 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005709 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005710 else
5711 TyRec = ArgExpr->getType()->getAs<RecordType>();
5712 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005713 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005714 VRQuals.addVolatile();
5715 VRQuals.addRestrict();
5716 return VRQuals;
5717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005718
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005719 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005720 if (!ClassDecl->hasDefinition())
5721 return VRQuals;
5722
John McCallad371252010-01-20 00:46:10 +00005723 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005724 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005725
John McCallad371252010-01-20 00:46:10 +00005726 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005727 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005728 NamedDecl *D = I.getDecl();
5729 if (isa<UsingShadowDecl>(D))
5730 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5731 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005732 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5733 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5734 CanTy = ResTypeRef->getPointeeType();
5735 // Need to go down the pointer/mempointer chain and add qualifiers
5736 // as see them.
5737 bool done = false;
5738 while (!done) {
5739 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5740 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005742 CanTy->getAs<MemberPointerType>())
5743 CanTy = ResTypeMPtr->getPointeeType();
5744 else
5745 done = true;
5746 if (CanTy.isVolatileQualified())
5747 VRQuals.addVolatile();
5748 if (CanTy.isRestrictQualified())
5749 VRQuals.addRestrict();
5750 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5751 return VRQuals;
5752 }
5753 }
5754 }
5755 return VRQuals;
5756}
John McCall52872982010-11-13 05:51:15 +00005757
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005758namespace {
John McCall52872982010-11-13 05:51:15 +00005759
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005760/// \brief Helper class to manage the addition of builtin operator overload
5761/// candidates. It provides shared state and utility methods used throughout
5762/// the process, as well as a helper method to add each group of builtin
5763/// operator overloads from the standard to a candidate set.
5764class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005765 // Common instance state available to all overload candidate addition methods.
5766 Sema &S;
5767 Expr **Args;
5768 unsigned NumArgs;
5769 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005770 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005771 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005772 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005773
Chandler Carruthc6586e52010-12-12 10:35:00 +00005774 // Define some constants used to index and iterate over the arithemetic types
5775 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005776 // The "promoted arithmetic types" are the arithmetic
5777 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005778 static const unsigned FirstIntegralType = 3;
5779 static const unsigned LastIntegralType = 18;
5780 static const unsigned FirstPromotedIntegralType = 3,
5781 LastPromotedIntegralType = 9;
5782 static const unsigned FirstPromotedArithmeticType = 0,
5783 LastPromotedArithmeticType = 9;
5784 static const unsigned NumArithmeticTypes = 18;
5785
Chandler Carruthc6586e52010-12-12 10:35:00 +00005786 /// \brief Get the canonical type for a given arithmetic type index.
5787 CanQualType getArithmeticType(unsigned index) {
5788 assert(index < NumArithmeticTypes);
5789 static CanQualType ASTContext::* const
5790 ArithmeticTypes[NumArithmeticTypes] = {
5791 // Start of promoted types.
5792 &ASTContext::FloatTy,
5793 &ASTContext::DoubleTy,
5794 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005795
Chandler Carruthc6586e52010-12-12 10:35:00 +00005796 // Start of integral types.
5797 &ASTContext::IntTy,
5798 &ASTContext::LongTy,
5799 &ASTContext::LongLongTy,
5800 &ASTContext::UnsignedIntTy,
5801 &ASTContext::UnsignedLongTy,
5802 &ASTContext::UnsignedLongLongTy,
5803 // End of promoted types.
5804
5805 &ASTContext::BoolTy,
5806 &ASTContext::CharTy,
5807 &ASTContext::WCharTy,
5808 &ASTContext::Char16Ty,
5809 &ASTContext::Char32Ty,
5810 &ASTContext::SignedCharTy,
5811 &ASTContext::ShortTy,
5812 &ASTContext::UnsignedCharTy,
5813 &ASTContext::UnsignedShortTy,
5814 // End of integral types.
5815 // FIXME: What about complex?
5816 };
5817 return S.Context.*ArithmeticTypes[index];
5818 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005819
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005820 /// \brief Gets the canonical type resulting from the usual arithemetic
5821 /// converions for the given arithmetic types.
5822 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5823 // Accelerator table for performing the usual arithmetic conversions.
5824 // The rules are basically:
5825 // - if either is floating-point, use the wider floating-point
5826 // - if same signedness, use the higher rank
5827 // - if same size, use unsigned of the higher rank
5828 // - use the larger type
5829 // These rules, together with the axiom that higher ranks are
5830 // never smaller, are sufficient to precompute all of these results
5831 // *except* when dealing with signed types of higher rank.
5832 // (we could precompute SLL x UI for all known platforms, but it's
5833 // better not to make any assumptions).
5834 enum PromotedType {
5835 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5836 };
5837 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5838 [LastPromotedArithmeticType] = {
5839 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5840 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5841 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5842 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5843 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5844 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5845 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5846 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5847 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5848 };
5849
5850 assert(L < LastPromotedArithmeticType);
5851 assert(R < LastPromotedArithmeticType);
5852 int Idx = ConversionsTable[L][R];
5853
5854 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005855 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005856
5857 // Slow path: we need to compare widths.
5858 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005859 CanQualType LT = getArithmeticType(L),
5860 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005861 unsigned LW = S.Context.getIntWidth(LT),
5862 RW = S.Context.getIntWidth(RT);
5863
5864 // If they're different widths, use the signed type.
5865 if (LW > RW) return LT;
5866 else if (LW < RW) return RT;
5867
5868 // Otherwise, use the unsigned type of the signed type's rank.
5869 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5870 assert(L == SLL || R == SLL);
5871 return S.Context.UnsignedLongLongTy;
5872 }
5873
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005874 /// \brief Helper method to factor out the common pattern of adding overloads
5875 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005876 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5877 bool HasVolatile) {
5878 QualType ParamTypes[2] = {
5879 S.Context.getLValueReferenceType(CandidateTy),
5880 S.Context.IntTy
5881 };
5882
5883 // Non-volatile version.
5884 if (NumArgs == 1)
5885 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5886 else
5887 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5888
5889 // Use a heuristic to reduce number of builtin candidates in the set:
5890 // add volatile version only if there are conversions to a volatile type.
5891 if (HasVolatile) {
5892 ParamTypes[0] =
5893 S.Context.getLValueReferenceType(
5894 S.Context.getVolatileType(CandidateTy));
5895 if (NumArgs == 1)
5896 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5897 else
5898 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5899 }
5900 }
5901
5902public:
5903 BuiltinOperatorOverloadBuilder(
5904 Sema &S, Expr **Args, unsigned NumArgs,
5905 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005906 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005907 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005908 OverloadCandidateSet &CandidateSet)
5909 : S(S), Args(Args), NumArgs(NumArgs),
5910 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005911 HasArithmeticOrEnumeralCandidateType(
5912 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005913 CandidateTypes(CandidateTypes),
5914 CandidateSet(CandidateSet) {
5915 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005916 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005917 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005918 assert(getArithmeticType(LastPromotedIntegralType - 1)
5919 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005920 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005921 assert(getArithmeticType(FirstPromotedArithmeticType)
5922 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005923 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005924 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5925 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005926 "Invalid last promoted arithmetic type");
5927 }
5928
5929 // C++ [over.built]p3:
5930 //
5931 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5932 // is either volatile or empty, there exist candidate operator
5933 // functions of the form
5934 //
5935 // VQ T& operator++(VQ T&);
5936 // T operator++(VQ T&, int);
5937 //
5938 // C++ [over.built]p4:
5939 //
5940 // For every pair (T, VQ), where T is an arithmetic type other
5941 // than bool, and VQ is either volatile or empty, there exist
5942 // candidate operator functions of the form
5943 //
5944 // VQ T& operator--(VQ T&);
5945 // T operator--(VQ T&, int);
5946 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005947 if (!HasArithmeticOrEnumeralCandidateType)
5948 return;
5949
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005950 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5951 Arith < NumArithmeticTypes; ++Arith) {
5952 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005953 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005954 VisibleTypeConversionsQuals.hasVolatile());
5955 }
5956 }
5957
5958 // C++ [over.built]p5:
5959 //
5960 // For every pair (T, VQ), where T is a cv-qualified or
5961 // cv-unqualified object type, and VQ is either volatile or
5962 // empty, there exist candidate operator functions of the form
5963 //
5964 // T*VQ& operator++(T*VQ&);
5965 // T*VQ& operator--(T*VQ&);
5966 // T* operator++(T*VQ&, int);
5967 // T* operator--(T*VQ&, int);
5968 void addPlusPlusMinusMinusPointerOverloads() {
5969 for (BuiltinCandidateTypeSet::iterator
5970 Ptr = CandidateTypes[0].pointer_begin(),
5971 PtrEnd = CandidateTypes[0].pointer_end();
5972 Ptr != PtrEnd; ++Ptr) {
5973 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005974 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005975 continue;
5976
5977 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5978 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5979 VisibleTypeConversionsQuals.hasVolatile()));
5980 }
5981 }
5982
5983 // C++ [over.built]p6:
5984 // For every cv-qualified or cv-unqualified object type T, there
5985 // exist candidate operator functions of the form
5986 //
5987 // T& operator*(T*);
5988 //
5989 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005990 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005991 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005992 // T& operator*(T*);
5993 void addUnaryStarPointerOverloads() {
5994 for (BuiltinCandidateTypeSet::iterator
5995 Ptr = CandidateTypes[0].pointer_begin(),
5996 PtrEnd = CandidateTypes[0].pointer_end();
5997 Ptr != PtrEnd; ++Ptr) {
5998 QualType ParamTy = *Ptr;
5999 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006000 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6001 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006002
Douglas Gregor02824322011-01-26 19:30:28 +00006003 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6004 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6005 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006006
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006007 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6008 &ParamTy, Args, 1, CandidateSet);
6009 }
6010 }
6011
6012 // C++ [over.built]p9:
6013 // For every promoted arithmetic type T, there exist candidate
6014 // operator functions of the form
6015 //
6016 // T operator+(T);
6017 // T operator-(T);
6018 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006019 if (!HasArithmeticOrEnumeralCandidateType)
6020 return;
6021
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006022 for (unsigned Arith = FirstPromotedArithmeticType;
6023 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006024 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006025 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6026 }
6027
6028 // Extension: We also add these operators for vector types.
6029 for (BuiltinCandidateTypeSet::iterator
6030 Vec = CandidateTypes[0].vector_begin(),
6031 VecEnd = CandidateTypes[0].vector_end();
6032 Vec != VecEnd; ++Vec) {
6033 QualType VecTy = *Vec;
6034 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6035 }
6036 }
6037
6038 // C++ [over.built]p8:
6039 // For every type T, there exist candidate operator functions of
6040 // the form
6041 //
6042 // T* operator+(T*);
6043 void addUnaryPlusPointerOverloads() {
6044 for (BuiltinCandidateTypeSet::iterator
6045 Ptr = CandidateTypes[0].pointer_begin(),
6046 PtrEnd = CandidateTypes[0].pointer_end();
6047 Ptr != PtrEnd; ++Ptr) {
6048 QualType ParamTy = *Ptr;
6049 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6050 }
6051 }
6052
6053 // C++ [over.built]p10:
6054 // For every promoted integral type T, there exist candidate
6055 // operator functions of the form
6056 //
6057 // T operator~(T);
6058 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006059 if (!HasArithmeticOrEnumeralCandidateType)
6060 return;
6061
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006062 for (unsigned Int = FirstPromotedIntegralType;
6063 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006064 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006065 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6066 }
6067
6068 // Extension: We also add this operator for vector types.
6069 for (BuiltinCandidateTypeSet::iterator
6070 Vec = CandidateTypes[0].vector_begin(),
6071 VecEnd = CandidateTypes[0].vector_end();
6072 Vec != VecEnd; ++Vec) {
6073 QualType VecTy = *Vec;
6074 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6075 }
6076 }
6077
6078 // C++ [over.match.oper]p16:
6079 // For every pointer to member type T, there exist candidate operator
6080 // functions of the form
6081 //
6082 // bool operator==(T,T);
6083 // bool operator!=(T,T);
6084 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6085 /// Set of (canonical) types that we've already handled.
6086 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6087
6088 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6089 for (BuiltinCandidateTypeSet::iterator
6090 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6091 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6092 MemPtr != MemPtrEnd;
6093 ++MemPtr) {
6094 // Don't add the same builtin candidate twice.
6095 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6096 continue;
6097
6098 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6099 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6100 CandidateSet);
6101 }
6102 }
6103 }
6104
6105 // C++ [over.built]p15:
6106 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006107 // For every T, where T is an enumeration type, a pointer type, or
6108 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006109 //
6110 // bool operator<(T, T);
6111 // bool operator>(T, T);
6112 // bool operator<=(T, T);
6113 // bool operator>=(T, T);
6114 // bool operator==(T, T);
6115 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006116 void addRelationalPointerOrEnumeralOverloads() {
6117 // C++ [over.built]p1:
6118 // If there is a user-written candidate with the same name and parameter
6119 // types as a built-in candidate operator function, the built-in operator
6120 // function is hidden and is not included in the set of candidate
6121 // functions.
6122 //
6123 // The text is actually in a note, but if we don't implement it then we end
6124 // up with ambiguities when the user provides an overloaded operator for
6125 // an enumeration type. Note that only enumeration types have this problem,
6126 // so we track which enumeration types we've seen operators for. Also, the
6127 // only other overloaded operator with enumeration argumenst, operator=,
6128 // cannot be overloaded for enumeration types, so this is the only place
6129 // where we must suppress candidates like this.
6130 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6131 UserDefinedBinaryOperators;
6132
6133 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6134 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6135 CandidateTypes[ArgIdx].enumeration_end()) {
6136 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6137 CEnd = CandidateSet.end();
6138 C != CEnd; ++C) {
6139 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6140 continue;
6141
6142 QualType FirstParamType =
6143 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6144 QualType SecondParamType =
6145 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6146
6147 // Skip if either parameter isn't of enumeral type.
6148 if (!FirstParamType->isEnumeralType() ||
6149 !SecondParamType->isEnumeralType())
6150 continue;
6151
6152 // Add this operator to the set of known user-defined operators.
6153 UserDefinedBinaryOperators.insert(
6154 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6155 S.Context.getCanonicalType(SecondParamType)));
6156 }
6157 }
6158 }
6159
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006160 /// Set of (canonical) types that we've already handled.
6161 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6162
6163 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6164 for (BuiltinCandidateTypeSet::iterator
6165 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6166 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6167 Ptr != PtrEnd; ++Ptr) {
6168 // Don't add the same builtin candidate twice.
6169 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6170 continue;
6171
6172 QualType ParamTypes[2] = { *Ptr, *Ptr };
6173 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6174 CandidateSet);
6175 }
6176 for (BuiltinCandidateTypeSet::iterator
6177 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6178 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6179 Enum != EnumEnd; ++Enum) {
6180 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6181
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006182 // Don't add the same builtin candidate twice, or if a user defined
6183 // candidate exists.
6184 if (!AddedTypes.insert(CanonType) ||
6185 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6186 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006187 continue;
6188
6189 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006190 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6191 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006192 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006193
6194 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6195 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6196 if (AddedTypes.insert(NullPtrTy) &&
6197 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6198 NullPtrTy))) {
6199 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6200 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6201 CandidateSet);
6202 }
6203 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006204 }
6205 }
6206
6207 // C++ [over.built]p13:
6208 //
6209 // For every cv-qualified or cv-unqualified object type T
6210 // there exist candidate operator functions of the form
6211 //
6212 // T* operator+(T*, ptrdiff_t);
6213 // T& operator[](T*, ptrdiff_t); [BELOW]
6214 // T* operator-(T*, ptrdiff_t);
6215 // T* operator+(ptrdiff_t, T*);
6216 // T& operator[](ptrdiff_t, T*); [BELOW]
6217 //
6218 // C++ [over.built]p14:
6219 //
6220 // For every T, where T is a pointer to object type, there
6221 // exist candidate operator functions of the form
6222 //
6223 // ptrdiff_t operator-(T, T);
6224 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6225 /// Set of (canonical) types that we've already handled.
6226 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6227
6228 for (int Arg = 0; Arg < 2; ++Arg) {
6229 QualType AsymetricParamTypes[2] = {
6230 S.Context.getPointerDiffType(),
6231 S.Context.getPointerDiffType(),
6232 };
6233 for (BuiltinCandidateTypeSet::iterator
6234 Ptr = CandidateTypes[Arg].pointer_begin(),
6235 PtrEnd = CandidateTypes[Arg].pointer_end();
6236 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006237 QualType PointeeTy = (*Ptr)->getPointeeType();
6238 if (!PointeeTy->isObjectType())
6239 continue;
6240
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006241 AsymetricParamTypes[Arg] = *Ptr;
6242 if (Arg == 0 || Op == OO_Plus) {
6243 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6244 // T* operator+(ptrdiff_t, T*);
6245 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6246 CandidateSet);
6247 }
6248 if (Op == OO_Minus) {
6249 // ptrdiff_t operator-(T, T);
6250 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6251 continue;
6252
6253 QualType ParamTypes[2] = { *Ptr, *Ptr };
6254 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6255 Args, 2, CandidateSet);
6256 }
6257 }
6258 }
6259 }
6260
6261 // C++ [over.built]p12:
6262 //
6263 // For every pair of promoted arithmetic types L and R, there
6264 // exist candidate operator functions of the form
6265 //
6266 // LR operator*(L, R);
6267 // LR operator/(L, R);
6268 // LR operator+(L, R);
6269 // LR operator-(L, R);
6270 // bool operator<(L, R);
6271 // bool operator>(L, R);
6272 // bool operator<=(L, R);
6273 // bool operator>=(L, R);
6274 // bool operator==(L, R);
6275 // bool operator!=(L, R);
6276 //
6277 // where LR is the result of the usual arithmetic conversions
6278 // between types L and R.
6279 //
6280 // C++ [over.built]p24:
6281 //
6282 // For every pair of promoted arithmetic types L and R, there exist
6283 // candidate operator functions of the form
6284 //
6285 // LR operator?(bool, L, R);
6286 //
6287 // where LR is the result of the usual arithmetic conversions
6288 // between types L and R.
6289 // Our candidates ignore the first parameter.
6290 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006291 if (!HasArithmeticOrEnumeralCandidateType)
6292 return;
6293
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006294 for (unsigned Left = FirstPromotedArithmeticType;
6295 Left < LastPromotedArithmeticType; ++Left) {
6296 for (unsigned Right = FirstPromotedArithmeticType;
6297 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006298 QualType LandR[2] = { getArithmeticType(Left),
6299 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006300 QualType Result =
6301 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006302 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006303 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6304 }
6305 }
6306
6307 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6308 // conditional operator for vector types.
6309 for (BuiltinCandidateTypeSet::iterator
6310 Vec1 = CandidateTypes[0].vector_begin(),
6311 Vec1End = CandidateTypes[0].vector_end();
6312 Vec1 != Vec1End; ++Vec1) {
6313 for (BuiltinCandidateTypeSet::iterator
6314 Vec2 = CandidateTypes[1].vector_begin(),
6315 Vec2End = CandidateTypes[1].vector_end();
6316 Vec2 != Vec2End; ++Vec2) {
6317 QualType LandR[2] = { *Vec1, *Vec2 };
6318 QualType Result = S.Context.BoolTy;
6319 if (!isComparison) {
6320 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6321 Result = *Vec1;
6322 else
6323 Result = *Vec2;
6324 }
6325
6326 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6327 }
6328 }
6329 }
6330
6331 // C++ [over.built]p17:
6332 //
6333 // For every pair of promoted integral types L and R, there
6334 // exist candidate operator functions of the form
6335 //
6336 // LR operator%(L, R);
6337 // LR operator&(L, R);
6338 // LR operator^(L, R);
6339 // LR operator|(L, R);
6340 // L operator<<(L, R);
6341 // L operator>>(L, R);
6342 //
6343 // where LR is the result of the usual arithmetic conversions
6344 // between types L and R.
6345 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006346 if (!HasArithmeticOrEnumeralCandidateType)
6347 return;
6348
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006349 for (unsigned Left = FirstPromotedIntegralType;
6350 Left < LastPromotedIntegralType; ++Left) {
6351 for (unsigned Right = FirstPromotedIntegralType;
6352 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006353 QualType LandR[2] = { getArithmeticType(Left),
6354 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006355 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6356 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006357 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006358 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6359 }
6360 }
6361 }
6362
6363 // C++ [over.built]p20:
6364 //
6365 // For every pair (T, VQ), where T is an enumeration or
6366 // pointer to member type and VQ is either volatile or
6367 // empty, there exist candidate operator functions of the form
6368 //
6369 // VQ T& operator=(VQ T&, T);
6370 void addAssignmentMemberPointerOrEnumeralOverloads() {
6371 /// Set of (canonical) types that we've already handled.
6372 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6373
6374 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6375 for (BuiltinCandidateTypeSet::iterator
6376 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6377 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6378 Enum != EnumEnd; ++Enum) {
6379 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6380 continue;
6381
6382 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6383 CandidateSet);
6384 }
6385
6386 for (BuiltinCandidateTypeSet::iterator
6387 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6388 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6389 MemPtr != MemPtrEnd; ++MemPtr) {
6390 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6391 continue;
6392
6393 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6394 CandidateSet);
6395 }
6396 }
6397 }
6398
6399 // C++ [over.built]p19:
6400 //
6401 // For every pair (T, VQ), where T is any type and VQ is either
6402 // volatile or empty, there exist candidate operator functions
6403 // of the form
6404 //
6405 // T*VQ& operator=(T*VQ&, T*);
6406 //
6407 // C++ [over.built]p21:
6408 //
6409 // For every pair (T, VQ), where T is a cv-qualified or
6410 // cv-unqualified object type and VQ is either volatile or
6411 // empty, there exist candidate operator functions of the form
6412 //
6413 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6414 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6415 void addAssignmentPointerOverloads(bool isEqualOp) {
6416 /// Set of (canonical) types that we've already handled.
6417 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6418
6419 for (BuiltinCandidateTypeSet::iterator
6420 Ptr = CandidateTypes[0].pointer_begin(),
6421 PtrEnd = CandidateTypes[0].pointer_end();
6422 Ptr != PtrEnd; ++Ptr) {
6423 // If this is operator=, keep track of the builtin candidates we added.
6424 if (isEqualOp)
6425 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006426 else if (!(*Ptr)->getPointeeType()->isObjectType())
6427 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006428
6429 // non-volatile version
6430 QualType ParamTypes[2] = {
6431 S.Context.getLValueReferenceType(*Ptr),
6432 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6433 };
6434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6435 /*IsAssigmentOperator=*/ isEqualOp);
6436
6437 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6438 VisibleTypeConversionsQuals.hasVolatile()) {
6439 // volatile version
6440 ParamTypes[0] =
6441 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6442 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6443 /*IsAssigmentOperator=*/isEqualOp);
6444 }
6445 }
6446
6447 if (isEqualOp) {
6448 for (BuiltinCandidateTypeSet::iterator
6449 Ptr = CandidateTypes[1].pointer_begin(),
6450 PtrEnd = CandidateTypes[1].pointer_end();
6451 Ptr != PtrEnd; ++Ptr) {
6452 // Make sure we don't add the same candidate twice.
6453 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6454 continue;
6455
Chandler Carruth8e543b32010-12-12 08:17:55 +00006456 QualType ParamTypes[2] = {
6457 S.Context.getLValueReferenceType(*Ptr),
6458 *Ptr,
6459 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006460
6461 // non-volatile version
6462 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6463 /*IsAssigmentOperator=*/true);
6464
6465 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6466 VisibleTypeConversionsQuals.hasVolatile()) {
6467 // volatile version
6468 ParamTypes[0] =
6469 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006470 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6471 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006472 }
6473 }
6474 }
6475 }
6476
6477 // C++ [over.built]p18:
6478 //
6479 // For every triple (L, VQ, R), where L is an arithmetic type,
6480 // VQ is either volatile or empty, and R is a promoted
6481 // arithmetic type, there exist candidate operator functions of
6482 // the form
6483 //
6484 // VQ L& operator=(VQ L&, R);
6485 // VQ L& operator*=(VQ L&, R);
6486 // VQ L& operator/=(VQ L&, R);
6487 // VQ L& operator+=(VQ L&, R);
6488 // VQ L& operator-=(VQ L&, R);
6489 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006490 if (!HasArithmeticOrEnumeralCandidateType)
6491 return;
6492
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006493 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6494 for (unsigned Right = FirstPromotedArithmeticType;
6495 Right < LastPromotedArithmeticType; ++Right) {
6496 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006497 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006498
6499 // Add this built-in operator as a candidate (VQ is empty).
6500 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006501 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006502 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6503 /*IsAssigmentOperator=*/isEqualOp);
6504
6505 // Add this built-in operator as a candidate (VQ is 'volatile').
6506 if (VisibleTypeConversionsQuals.hasVolatile()) {
6507 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006508 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006509 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006510 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6511 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006512 /*IsAssigmentOperator=*/isEqualOp);
6513 }
6514 }
6515 }
6516
6517 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6518 for (BuiltinCandidateTypeSet::iterator
6519 Vec1 = CandidateTypes[0].vector_begin(),
6520 Vec1End = CandidateTypes[0].vector_end();
6521 Vec1 != Vec1End; ++Vec1) {
6522 for (BuiltinCandidateTypeSet::iterator
6523 Vec2 = CandidateTypes[1].vector_begin(),
6524 Vec2End = CandidateTypes[1].vector_end();
6525 Vec2 != Vec2End; ++Vec2) {
6526 QualType ParamTypes[2];
6527 ParamTypes[1] = *Vec2;
6528 // Add this built-in operator as a candidate (VQ is empty).
6529 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6530 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6531 /*IsAssigmentOperator=*/isEqualOp);
6532
6533 // Add this built-in operator as a candidate (VQ is 'volatile').
6534 if (VisibleTypeConversionsQuals.hasVolatile()) {
6535 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6536 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006537 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6538 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006539 /*IsAssigmentOperator=*/isEqualOp);
6540 }
6541 }
6542 }
6543 }
6544
6545 // C++ [over.built]p22:
6546 //
6547 // For every triple (L, VQ, R), where L is an integral type, VQ
6548 // is either volatile or empty, and R is a promoted integral
6549 // type, there exist candidate operator functions of the form
6550 //
6551 // VQ L& operator%=(VQ L&, R);
6552 // VQ L& operator<<=(VQ L&, R);
6553 // VQ L& operator>>=(VQ L&, R);
6554 // VQ L& operator&=(VQ L&, R);
6555 // VQ L& operator^=(VQ L&, R);
6556 // VQ L& operator|=(VQ L&, R);
6557 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006558 if (!HasArithmeticOrEnumeralCandidateType)
6559 return;
6560
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006561 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6562 for (unsigned Right = FirstPromotedIntegralType;
6563 Right < LastPromotedIntegralType; ++Right) {
6564 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006565 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006566
6567 // Add this built-in operator as a candidate (VQ is empty).
6568 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006569 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006570 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6571 if (VisibleTypeConversionsQuals.hasVolatile()) {
6572 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006573 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006574 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6575 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6576 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6577 CandidateSet);
6578 }
6579 }
6580 }
6581 }
6582
6583 // C++ [over.operator]p23:
6584 //
6585 // There also exist candidate operator functions of the form
6586 //
6587 // bool operator!(bool);
6588 // bool operator&&(bool, bool);
6589 // bool operator||(bool, bool);
6590 void addExclaimOverload() {
6591 QualType ParamTy = S.Context.BoolTy;
6592 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6593 /*IsAssignmentOperator=*/false,
6594 /*NumContextualBoolArguments=*/1);
6595 }
6596 void addAmpAmpOrPipePipeOverload() {
6597 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6598 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6599 /*IsAssignmentOperator=*/false,
6600 /*NumContextualBoolArguments=*/2);
6601 }
6602
6603 // C++ [over.built]p13:
6604 //
6605 // For every cv-qualified or cv-unqualified object type T there
6606 // exist candidate operator functions of the form
6607 //
6608 // T* operator+(T*, ptrdiff_t); [ABOVE]
6609 // T& operator[](T*, ptrdiff_t);
6610 // T* operator-(T*, ptrdiff_t); [ABOVE]
6611 // T* operator+(ptrdiff_t, T*); [ABOVE]
6612 // T& operator[](ptrdiff_t, T*);
6613 void addSubscriptOverloads() {
6614 for (BuiltinCandidateTypeSet::iterator
6615 Ptr = CandidateTypes[0].pointer_begin(),
6616 PtrEnd = CandidateTypes[0].pointer_end();
6617 Ptr != PtrEnd; ++Ptr) {
6618 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6619 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006620 if (!PointeeType->isObjectType())
6621 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006623 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6624
6625 // T& operator[](T*, ptrdiff_t)
6626 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6627 }
6628
6629 for (BuiltinCandidateTypeSet::iterator
6630 Ptr = CandidateTypes[1].pointer_begin(),
6631 PtrEnd = CandidateTypes[1].pointer_end();
6632 Ptr != PtrEnd; ++Ptr) {
6633 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6634 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006635 if (!PointeeType->isObjectType())
6636 continue;
6637
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006638 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6639
6640 // T& operator[](ptrdiff_t, T*)
6641 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6642 }
6643 }
6644
6645 // C++ [over.built]p11:
6646 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6647 // C1 is the same type as C2 or is a derived class of C2, T is an object
6648 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6649 // there exist candidate operator functions of the form
6650 //
6651 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6652 //
6653 // where CV12 is the union of CV1 and CV2.
6654 void addArrowStarOverloads() {
6655 for (BuiltinCandidateTypeSet::iterator
6656 Ptr = CandidateTypes[0].pointer_begin(),
6657 PtrEnd = CandidateTypes[0].pointer_end();
6658 Ptr != PtrEnd; ++Ptr) {
6659 QualType C1Ty = (*Ptr);
6660 QualType C1;
6661 QualifierCollector Q1;
6662 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6663 if (!isa<RecordType>(C1))
6664 continue;
6665 // heuristic to reduce number of builtin candidates in the set.
6666 // Add volatile/restrict version only if there are conversions to a
6667 // volatile/restrict type.
6668 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6669 continue;
6670 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6671 continue;
6672 for (BuiltinCandidateTypeSet::iterator
6673 MemPtr = CandidateTypes[1].member_pointer_begin(),
6674 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6675 MemPtr != MemPtrEnd; ++MemPtr) {
6676 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6677 QualType C2 = QualType(mptr->getClass(), 0);
6678 C2 = C2.getUnqualifiedType();
6679 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6680 break;
6681 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6682 // build CV12 T&
6683 QualType T = mptr->getPointeeType();
6684 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6685 T.isVolatileQualified())
6686 continue;
6687 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6688 T.isRestrictQualified())
6689 continue;
6690 T = Q1.apply(S.Context, T);
6691 QualType ResultTy = S.Context.getLValueReferenceType(T);
6692 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6693 }
6694 }
6695 }
6696
6697 // Note that we don't consider the first argument, since it has been
6698 // contextually converted to bool long ago. The candidates below are
6699 // therefore added as binary.
6700 //
6701 // C++ [over.built]p25:
6702 // For every type T, where T is a pointer, pointer-to-member, or scoped
6703 // enumeration type, there exist candidate operator functions of the form
6704 //
6705 // T operator?(bool, T, T);
6706 //
6707 void addConditionalOperatorOverloads() {
6708 /// Set of (canonical) types that we've already handled.
6709 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6710
6711 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6712 for (BuiltinCandidateTypeSet::iterator
6713 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6714 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6715 Ptr != PtrEnd; ++Ptr) {
6716 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6717 continue;
6718
6719 QualType ParamTypes[2] = { *Ptr, *Ptr };
6720 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6721 }
6722
6723 for (BuiltinCandidateTypeSet::iterator
6724 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6725 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6726 MemPtr != MemPtrEnd; ++MemPtr) {
6727 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6728 continue;
6729
6730 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6731 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6732 }
6733
6734 if (S.getLangOptions().CPlusPlus0x) {
6735 for (BuiltinCandidateTypeSet::iterator
6736 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6737 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6738 Enum != EnumEnd; ++Enum) {
6739 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6740 continue;
6741
6742 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6743 continue;
6744
6745 QualType ParamTypes[2] = { *Enum, *Enum };
6746 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6747 }
6748 }
6749 }
6750 }
6751};
6752
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006753} // end anonymous namespace
6754
6755/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6756/// operator overloads to the candidate set (C++ [over.built]), based
6757/// on the operator @p Op and the arguments given. For example, if the
6758/// operator is a binary '+', this routine might add "int
6759/// operator+(int, int)" to cover integer addition.
6760void
6761Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6762 SourceLocation OpLoc,
6763 Expr **Args, unsigned NumArgs,
6764 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006765 // Find all of the types that the arguments can convert to, but only
6766 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006767 // that make use of these types. Also record whether we encounter non-record
6768 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006769 Qualifiers VisibleTypeConversionsQuals;
6770 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006771 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6772 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006773
6774 bool HasNonRecordCandidateType = false;
6775 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006776 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006777 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6778 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6779 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6780 OpLoc,
6781 true,
6782 (Op == OO_Exclaim ||
6783 Op == OO_AmpAmp ||
6784 Op == OO_PipePipe),
6785 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006786 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6787 CandidateTypes[ArgIdx].hasNonRecordTypes();
6788 HasArithmeticOrEnumeralCandidateType =
6789 HasArithmeticOrEnumeralCandidateType ||
6790 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006791 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006792
Chandler Carruth00a38332010-12-13 01:44:01 +00006793 // Exit early when no non-record types have been added to the candidate set
6794 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006795 //
6796 // We can't exit early for !, ||, or &&, since there we have always have
6797 // 'bool' overloads.
6798 if (!HasNonRecordCandidateType &&
6799 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006800 return;
6801
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006802 // Setup an object to manage the common state for building overloads.
6803 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6804 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006805 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006806 CandidateTypes, CandidateSet);
6807
6808 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006809 switch (Op) {
6810 case OO_None:
6811 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006812 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006813
Chandler Carruth5184de02010-12-12 08:51:33 +00006814 case OO_New:
6815 case OO_Delete:
6816 case OO_Array_New:
6817 case OO_Array_Delete:
6818 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006819 llvm_unreachable(
6820 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006821
6822 case OO_Comma:
6823 case OO_Arrow:
6824 // C++ [over.match.oper]p3:
6825 // -- For the operator ',', the unary operator '&', or the
6826 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006827 break;
6828
6829 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006830 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006831 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006832 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006833
6834 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006835 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006836 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006837 } else {
6838 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6839 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6840 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006841 break;
6842
Chandler Carruth5184de02010-12-12 08:51:33 +00006843 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006844 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006845 OpBuilder.addUnaryStarPointerOverloads();
6846 else
6847 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6848 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006849
Chandler Carruth5184de02010-12-12 08:51:33 +00006850 case OO_Slash:
6851 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006852 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006853
6854 case OO_PlusPlus:
6855 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006856 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6857 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006858 break;
6859
Douglas Gregor84605ae2009-08-24 13:43:27 +00006860 case OO_EqualEqual:
6861 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006862 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006863 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006864
Douglas Gregora11693b2008-11-12 17:17:38 +00006865 case OO_Less:
6866 case OO_Greater:
6867 case OO_LessEqual:
6868 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006869 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006870 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6871 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006872
Douglas Gregora11693b2008-11-12 17:17:38 +00006873 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006874 case OO_Caret:
6875 case OO_Pipe:
6876 case OO_LessLess:
6877 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006878 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006879 break;
6880
Chandler Carruth5184de02010-12-12 08:51:33 +00006881 case OO_Amp: // '&' is either unary or binary
6882 if (NumArgs == 1)
6883 // C++ [over.match.oper]p3:
6884 // -- For the operator ',', the unary operator '&', or the
6885 // operator '->', the built-in candidates set is empty.
6886 break;
6887
6888 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6889 break;
6890
6891 case OO_Tilde:
6892 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6893 break;
6894
Douglas Gregora11693b2008-11-12 17:17:38 +00006895 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006896 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006897 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006898
6899 case OO_PlusEqual:
6900 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006901 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006902 // Fall through.
6903
6904 case OO_StarEqual:
6905 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006906 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006907 break;
6908
6909 case OO_PercentEqual:
6910 case OO_LessLessEqual:
6911 case OO_GreaterGreaterEqual:
6912 case OO_AmpEqual:
6913 case OO_CaretEqual:
6914 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006915 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006916 break;
6917
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006918 case OO_Exclaim:
6919 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006920 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006921
Douglas Gregora11693b2008-11-12 17:17:38 +00006922 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006923 case OO_PipePipe:
6924 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006925 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006926
6927 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006928 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006929 break;
6930
6931 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006932 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006933 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006934
6935 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006936 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006937 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6938 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006939 }
6940}
6941
Douglas Gregore254f902009-02-04 00:32:51 +00006942/// \brief Add function candidates found via argument-dependent lookup
6943/// to the set of overloading candidates.
6944///
6945/// This routine performs argument-dependent name lookup based on the
6946/// given function name (which may also be an operator name) and adds
6947/// all of the overload candidates found by ADL to the overload
6948/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006949void
Douglas Gregore254f902009-02-04 00:32:51 +00006950Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006951 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006952 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006953 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006954 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006955 bool PartialOverloading,
6956 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006957 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006958
John McCall91f61fc2010-01-26 06:04:06 +00006959 // FIXME: This approach for uniquing ADL results (and removing
6960 // redundant candidates from the set) relies on pointer-equality,
6961 // which means we need to key off the canonical decl. However,
6962 // always going back to the canonical decl might not get us the
6963 // right set of default arguments. What default arguments are
6964 // we supposed to consider on ADL candidates, anyway?
6965
Douglas Gregorcabea402009-09-22 15:41:20 +00006966 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006967 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6968 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006969
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006970 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006971 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6972 CandEnd = CandidateSet.end();
6973 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006974 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006975 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006976 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006977 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006978 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006979
6980 // For each of the ADL candidates we found, add it to the overload
6981 // set.
John McCall8fe68082010-01-26 07:16:45 +00006982 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006983 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006984 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006985 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006986 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006987
John McCalla0296f72010-03-19 07:35:19 +00006988 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006989 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006990 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006991 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006992 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006993 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006994 }
Douglas Gregore254f902009-02-04 00:32:51 +00006995}
6996
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006997/// isBetterOverloadCandidate - Determines whether the first overload
6998/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006999bool
John McCall5c32be02010-08-24 20:38:10 +00007000isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007001 const OverloadCandidate &Cand1,
7002 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007003 SourceLocation Loc,
7004 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007005 // Define viable functions to be better candidates than non-viable
7006 // functions.
7007 if (!Cand2.Viable)
7008 return Cand1.Viable;
7009 else if (!Cand1.Viable)
7010 return false;
7011
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007012 // C++ [over.match.best]p1:
7013 //
7014 // -- if F is a static member function, ICS1(F) is defined such
7015 // that ICS1(F) is neither better nor worse than ICS1(G) for
7016 // any function G, and, symmetrically, ICS1(G) is neither
7017 // better nor worse than ICS1(F).
7018 unsigned StartArg = 0;
7019 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7020 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007021
Douglas Gregord3cb3562009-07-07 23:38:56 +00007022 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007023 // A viable function F1 is defined to be a better function than another
7024 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007025 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007026 unsigned NumArgs = Cand1.NumConversions;
7027 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007028 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007029 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007030 switch (CompareImplicitConversionSequences(S,
7031 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007032 Cand2.Conversions[ArgIdx])) {
7033 case ImplicitConversionSequence::Better:
7034 // Cand1 has a better conversion sequence.
7035 HasBetterConversion = true;
7036 break;
7037
7038 case ImplicitConversionSequence::Worse:
7039 // Cand1 can't be better than Cand2.
7040 return false;
7041
7042 case ImplicitConversionSequence::Indistinguishable:
7043 // Do nothing.
7044 break;
7045 }
7046 }
7047
Mike Stump11289f42009-09-09 15:08:12 +00007048 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007049 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007050 if (HasBetterConversion)
7051 return true;
7052
Mike Stump11289f42009-09-09 15:08:12 +00007053 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007054 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007055 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007056 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7057 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007058
7059 // -- F1 and F2 are function template specializations, and the function
7060 // template for F1 is more specialized than the template for F2
7061 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007062 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007063 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007064 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007065 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007066 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7067 Cand2.Function->getPrimaryTemplate(),
7068 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007069 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007070 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007071 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007072 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007073 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007074
Douglas Gregora1f013e2008-11-07 22:36:19 +00007075 // -- the context is an initialization by user-defined conversion
7076 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7077 // from the return type of F1 to the destination type (i.e.,
7078 // the type of the entity being initialized) is a better
7079 // conversion sequence than the standard conversion sequence
7080 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007081 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007082 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007083 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00007084 switch (CompareStandardConversionSequences(S,
7085 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007086 Cand2.FinalConversion)) {
7087 case ImplicitConversionSequence::Better:
7088 // Cand1 has a better conversion sequence.
7089 return true;
7090
7091 case ImplicitConversionSequence::Worse:
7092 // Cand1 can't be better than Cand2.
7093 return false;
7094
7095 case ImplicitConversionSequence::Indistinguishable:
7096 // Do nothing
7097 break;
7098 }
7099 }
7100
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007101 return false;
7102}
7103
Mike Stump11289f42009-09-09 15:08:12 +00007104/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007105/// within an overload candidate set.
7106///
7107/// \param CandidateSet the set of candidate functions.
7108///
7109/// \param Loc the location of the function name (or operator symbol) for
7110/// which overload resolution occurs.
7111///
Mike Stump11289f42009-09-09 15:08:12 +00007112/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007113/// function, Best points to the candidate function found.
7114///
7115/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007116OverloadingResult
7117OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007118 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007119 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007120 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007121 Best = end();
7122 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7123 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007124 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007125 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007126 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007127 }
7128
7129 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007130 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007131 return OR_No_Viable_Function;
7132
7133 // Make sure that this function is better than every other viable
7134 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007135 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007136 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007137 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007138 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007139 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007140 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007141 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007142 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007143 }
Mike Stump11289f42009-09-09 15:08:12 +00007144
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007145 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007146 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007147 (Best->Function->isDeleted() ||
7148 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007149 return OR_Deleted;
7150
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007151 return OR_Success;
7152}
7153
John McCall53262c92010-01-12 02:15:36 +00007154namespace {
7155
7156enum OverloadCandidateKind {
7157 oc_function,
7158 oc_method,
7159 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007160 oc_function_template,
7161 oc_method_template,
7162 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007163 oc_implicit_default_constructor,
7164 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007165 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007166 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007167 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007168 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007169};
7170
John McCalle1ac8d12010-01-13 00:25:19 +00007171OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7172 FunctionDecl *Fn,
7173 std::string &Description) {
7174 bool isTemplate = false;
7175
7176 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7177 isTemplate = true;
7178 Description = S.getTemplateArgumentBindingsText(
7179 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7180 }
John McCallfd0b2f82010-01-06 09:43:14 +00007181
7182 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007183 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007184 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007185
Sebastian Redl08905022011-02-05 19:23:19 +00007186 if (Ctor->getInheritedConstructor())
7187 return oc_implicit_inherited_constructor;
7188
Alexis Hunt119c10e2011-05-25 23:16:36 +00007189 if (Ctor->isDefaultConstructor())
7190 return oc_implicit_default_constructor;
7191
7192 if (Ctor->isMoveConstructor())
7193 return oc_implicit_move_constructor;
7194
7195 assert(Ctor->isCopyConstructor() &&
7196 "unexpected sort of implicit constructor");
7197 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007198 }
7199
7200 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7201 // This actually gets spelled 'candidate function' for now, but
7202 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007203 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007204 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007205
Alexis Hunt119c10e2011-05-25 23:16:36 +00007206 if (Meth->isMoveAssignmentOperator())
7207 return oc_implicit_move_assignment;
7208
Douglas Gregorec3bec02010-09-27 22:37:28 +00007209 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007210 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007211 return oc_implicit_copy_assignment;
7212 }
7213
John McCalle1ac8d12010-01-13 00:25:19 +00007214 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007215}
7216
Sebastian Redl08905022011-02-05 19:23:19 +00007217void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7218 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7219 if (!Ctor) return;
7220
7221 Ctor = Ctor->getInheritedConstructor();
7222 if (!Ctor) return;
7223
7224 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7225}
7226
John McCall53262c92010-01-12 02:15:36 +00007227} // end anonymous namespace
7228
7229// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007230void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007231 std::string FnDesc;
7232 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007233 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7234 << (unsigned) K << FnDesc;
7235 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7236 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007237 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007238}
7239
Douglas Gregorb491ed32011-02-19 21:32:49 +00007240//Notes the location of all overload candidates designated through
7241// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007242void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007243 assert(OverloadedExpr->getType() == Context.OverloadTy);
7244
7245 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7246 OverloadExpr *OvlExpr = Ovl.Expression;
7247
7248 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7249 IEnd = OvlExpr->decls_end();
7250 I != IEnd; ++I) {
7251 if (FunctionTemplateDecl *FunTmpl =
7252 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007253 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007254 } else if (FunctionDecl *Fun
7255 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007256 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007257 }
7258 }
7259}
7260
John McCall0d1da222010-01-12 00:44:57 +00007261/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7262/// "lead" diagnostic; it will be given two arguments, the source and
7263/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007264void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7265 Sema &S,
7266 SourceLocation CaretLoc,
7267 const PartialDiagnostic &PDiag) const {
7268 S.Diag(CaretLoc, PDiag)
7269 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007270 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007271 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7272 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007273 }
John McCall12f97bc2010-01-08 04:41:39 +00007274}
7275
John McCall0d1da222010-01-12 00:44:57 +00007276namespace {
7277
John McCall6a61b522010-01-13 09:16:55 +00007278void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7279 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7280 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007281 assert(Cand->Function && "for now, candidate must be a function");
7282 FunctionDecl *Fn = Cand->Function;
7283
7284 // There's a conversion slot for the object argument if this is a
7285 // non-constructor method. Note that 'I' corresponds the
7286 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007287 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007288 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007289 if (I == 0)
7290 isObjectArgument = true;
7291 else
7292 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007293 }
7294
John McCalle1ac8d12010-01-13 00:25:19 +00007295 std::string FnDesc;
7296 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7297
John McCall6a61b522010-01-13 09:16:55 +00007298 Expr *FromExpr = Conv.Bad.FromExpr;
7299 QualType FromTy = Conv.Bad.getFromType();
7300 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007301
John McCallfb7ad0f2010-02-02 02:42:52 +00007302 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007303 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007304 Expr *E = FromExpr->IgnoreParens();
7305 if (isa<UnaryOperator>(E))
7306 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007307 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007308
7309 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7310 << (unsigned) FnKind << FnDesc
7311 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7312 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007313 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007314 return;
7315 }
7316
John McCall6d174642010-01-23 08:10:49 +00007317 // Do some hand-waving analysis to see if the non-viability is due
7318 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007319 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7320 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7321 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7322 CToTy = RT->getPointeeType();
7323 else {
7324 // TODO: detect and diagnose the full richness of const mismatches.
7325 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7326 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7327 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7328 }
7329
7330 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7331 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7332 // It is dumb that we have to do this here.
7333 while (isa<ArrayType>(CFromTy))
7334 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7335 while (isa<ArrayType>(CToTy))
7336 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7337
7338 Qualifiers FromQs = CFromTy.getQualifiers();
7339 Qualifiers ToQs = CToTy.getQualifiers();
7340
7341 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7342 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7343 << (unsigned) FnKind << FnDesc
7344 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7345 << FromTy
7346 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7347 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007348 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007349 return;
7350 }
7351
John McCall31168b02011-06-15 23:02:42 +00007352 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007353 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007354 << (unsigned) FnKind << FnDesc
7355 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7356 << FromTy
7357 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7358 << (unsigned) isObjectArgument << I+1;
7359 MaybeEmitInheritedConstructorNote(S, Fn);
7360 return;
7361 }
7362
Douglas Gregoraec25842011-04-26 23:16:46 +00007363 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7364 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7365 << (unsigned) FnKind << FnDesc
7366 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7367 << FromTy
7368 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7369 << (unsigned) isObjectArgument << I+1;
7370 MaybeEmitInheritedConstructorNote(S, Fn);
7371 return;
7372 }
7373
John McCall47000992010-01-14 03:28:57 +00007374 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7375 assert(CVR && "unexpected qualifiers mismatch");
7376
7377 if (isObjectArgument) {
7378 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7379 << (unsigned) FnKind << FnDesc
7380 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7381 << FromTy << (CVR - 1);
7382 } else {
7383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7384 << (unsigned) FnKind << FnDesc
7385 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7386 << FromTy << (CVR - 1) << I+1;
7387 }
Sebastian Redl08905022011-02-05 19:23:19 +00007388 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007389 return;
7390 }
7391
Sebastian Redla72462c2011-09-24 17:48:32 +00007392 // Special diagnostic for failure to convert an initializer list, since
7393 // telling the user that it has type void is not useful.
7394 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7395 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7396 << (unsigned) FnKind << FnDesc
7397 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7398 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7399 MaybeEmitInheritedConstructorNote(S, Fn);
7400 return;
7401 }
7402
John McCall6d174642010-01-23 08:10:49 +00007403 // Diagnose references or pointers to incomplete types differently,
7404 // since it's far from impossible that the incompleteness triggered
7405 // the failure.
7406 QualType TempFromTy = FromTy.getNonReferenceType();
7407 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7408 TempFromTy = PTy->getPointeeType();
7409 if (TempFromTy->isIncompleteType()) {
7410 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7411 << (unsigned) FnKind << FnDesc
7412 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7413 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007414 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007415 return;
7416 }
7417
Douglas Gregor56f2e342010-06-30 23:01:39 +00007418 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007419 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007420 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7421 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7422 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7423 FromPtrTy->getPointeeType()) &&
7424 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7425 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007426 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007427 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007428 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007429 }
7430 } else if (const ObjCObjectPointerType *FromPtrTy
7431 = FromTy->getAs<ObjCObjectPointerType>()) {
7432 if (const ObjCObjectPointerType *ToPtrTy
7433 = ToTy->getAs<ObjCObjectPointerType>())
7434 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7435 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7436 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7437 FromPtrTy->getPointeeType()) &&
7438 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007439 BaseToDerivedConversion = 2;
7440 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7441 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7442 !FromTy->isIncompleteType() &&
7443 !ToRefTy->getPointeeType()->isIncompleteType() &&
7444 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7445 BaseToDerivedConversion = 3;
7446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007447
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007448 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007449 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007450 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007451 << (unsigned) FnKind << FnDesc
7452 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007453 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007454 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007455 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007456 return;
7457 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007458
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007459 if (isa<ObjCObjectPointerType>(CFromTy) &&
7460 isa<PointerType>(CToTy)) {
7461 Qualifiers FromQs = CFromTy.getQualifiers();
7462 Qualifiers ToQs = CToTy.getQualifiers();
7463 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7465 << (unsigned) FnKind << FnDesc
7466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7467 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7468 MaybeEmitInheritedConstructorNote(S, Fn);
7469 return;
7470 }
7471 }
7472
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007473 // Emit the generic diagnostic and, optionally, add the hints to it.
7474 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7475 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007476 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007477 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7478 << (unsigned) (Cand->Fix.Kind);
7479
7480 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007481 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007482 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7483 HI != HE; ++HI)
7484 FDiag << *HI;
7485 S.Diag(Fn->getLocation(), FDiag);
7486
Sebastian Redl08905022011-02-05 19:23:19 +00007487 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007488}
7489
7490void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7491 unsigned NumFormalArgs) {
7492 // TODO: treat calls to a missing default constructor as a special case
7493
7494 FunctionDecl *Fn = Cand->Function;
7495 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7496
7497 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007498
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007499 // With invalid overloaded operators, it's possible that we think we
7500 // have an arity mismatch when it fact it looks like we have the
7501 // right number of arguments, because only overloaded operators have
7502 // the weird behavior of overloading member and non-member functions.
7503 // Just don't report anything.
7504 if (Fn->isInvalidDecl() &&
7505 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7506 return;
7507
John McCall6a61b522010-01-13 09:16:55 +00007508 // at least / at most / exactly
7509 unsigned mode, modeCount;
7510 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007511 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7512 (Cand->FailureKind == ovl_fail_bad_deduction &&
7513 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007514 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007515 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007516 mode = 0; // "at least"
7517 else
7518 mode = 2; // "exactly"
7519 modeCount = MinParams;
7520 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007521 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7522 (Cand->FailureKind == ovl_fail_bad_deduction &&
7523 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007524 if (MinParams != FnTy->getNumArgs())
7525 mode = 1; // "at most"
7526 else
7527 mode = 2; // "exactly"
7528 modeCount = FnTy->getNumArgs();
7529 }
7530
7531 std::string Description;
7532 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7533
7534 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007535 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007536 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007537 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007538}
7539
John McCall8b9ed552010-02-01 18:53:26 +00007540/// Diagnose a failed template-argument deduction.
7541void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7542 Expr **Args, unsigned NumArgs) {
7543 FunctionDecl *Fn = Cand->Function; // pattern
7544
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007545 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007546 NamedDecl *ParamD;
7547 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7548 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7549 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007550 switch (Cand->DeductionFailure.Result) {
7551 case Sema::TDK_Success:
7552 llvm_unreachable("TDK_success while diagnosing bad deduction");
7553
7554 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007555 assert(ParamD && "no parameter found for incomplete deduction result");
7556 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7557 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007558 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007559 return;
7560 }
7561
John McCall42d7d192010-08-05 09:05:08 +00007562 case Sema::TDK_Underqualified: {
7563 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7564 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7565
7566 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7567
7568 // Param will have been canonicalized, but it should just be a
7569 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007570 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007571 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007572 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007573 assert(S.Context.hasSameType(Param, NonCanonParam));
7574
7575 // Arg has also been canonicalized, but there's nothing we can do
7576 // about that. It also doesn't matter as much, because it won't
7577 // have any template parameters in it (because deduction isn't
7578 // done on dependent types).
7579 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7580
7581 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7582 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007583 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007584 return;
7585 }
7586
7587 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007588 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007589 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007590 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007591 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007592 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007593 which = 1;
7594 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007595 which = 2;
7596 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007597
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007598 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007599 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007600 << *Cand->DeductionFailure.getFirstArg()
7601 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007602 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007603 return;
7604 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007605
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007606 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007607 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007608 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007609 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007610 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7611 << ParamD->getDeclName();
7612 else {
7613 int index = 0;
7614 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7615 index = TTP->getIndex();
7616 else if (NonTypeTemplateParmDecl *NTTP
7617 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7618 index = NTTP->getIndex();
7619 else
7620 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007621 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007622 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7623 << (index + 1);
7624 }
Sebastian Redl08905022011-02-05 19:23:19 +00007625 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007626 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007627
Douglas Gregor02eb4832010-05-08 18:13:28 +00007628 case Sema::TDK_TooManyArguments:
7629 case Sema::TDK_TooFewArguments:
7630 DiagnoseArityMismatch(S, Cand, NumArgs);
7631 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007632
7633 case Sema::TDK_InstantiationDepth:
7634 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007635 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007636 return;
7637
7638 case Sema::TDK_SubstitutionFailure: {
7639 std::string ArgString;
7640 if (TemplateArgumentList *Args
7641 = Cand->DeductionFailure.getTemplateArgumentList())
7642 ArgString = S.getTemplateArgumentBindingsText(
7643 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7644 *Args);
7645 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7646 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007647 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007648 return;
7649 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007650
John McCall8b9ed552010-02-01 18:53:26 +00007651 // TODO: diagnose these individually, then kill off
7652 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007653 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007654 case Sema::TDK_FailedOverloadResolution:
7655 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007656 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007657 return;
7658 }
7659}
7660
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007661/// CUDA: diagnose an invalid call across targets.
7662void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7663 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7664 FunctionDecl *Callee = Cand->Function;
7665
7666 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7667 CalleeTarget = S.IdentifyCUDATarget(Callee);
7668
7669 std::string FnDesc;
7670 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7671
7672 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7673 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7674}
7675
John McCall8b9ed552010-02-01 18:53:26 +00007676/// Generates a 'note' diagnostic for an overload candidate. We've
7677/// already generated a primary error at the call site.
7678///
7679/// It really does need to be a single diagnostic with its caret
7680/// pointed at the candidate declaration. Yes, this creates some
7681/// major challenges of technical writing. Yes, this makes pointing
7682/// out problems with specific arguments quite awkward. It's still
7683/// better than generating twenty screens of text for every failed
7684/// overload.
7685///
7686/// It would be great to be able to express per-candidate problems
7687/// more richly for those diagnostic clients that cared, but we'd
7688/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007689void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7690 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007691 FunctionDecl *Fn = Cand->Function;
7692
John McCall12f97bc2010-01-08 04:41:39 +00007693 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007694 if (Cand->Viable && (Fn->isDeleted() ||
7695 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007696 std::string FnDesc;
7697 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007698
7699 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007700 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007701 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007702 return;
John McCall12f97bc2010-01-08 04:41:39 +00007703 }
7704
John McCalle1ac8d12010-01-13 00:25:19 +00007705 // We don't really have anything else to say about viable candidates.
7706 if (Cand->Viable) {
7707 S.NoteOverloadCandidate(Fn);
7708 return;
7709 }
John McCall0d1da222010-01-12 00:44:57 +00007710
John McCall6a61b522010-01-13 09:16:55 +00007711 switch (Cand->FailureKind) {
7712 case ovl_fail_too_many_arguments:
7713 case ovl_fail_too_few_arguments:
7714 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007715
John McCall6a61b522010-01-13 09:16:55 +00007716 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007717 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7718
John McCallfe796dd2010-01-23 05:17:32 +00007719 case ovl_fail_trivial_conversion:
7720 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007721 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007722 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007723
John McCall65eb8792010-02-25 01:37:24 +00007724 case ovl_fail_bad_conversion: {
7725 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007726 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007727 if (Cand->Conversions[I].isBad())
7728 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007729
John McCall6a61b522010-01-13 09:16:55 +00007730 // FIXME: this currently happens when we're called from SemaInit
7731 // when user-conversion overload fails. Figure out how to handle
7732 // those conditions and diagnose them well.
7733 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007734 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007735
7736 case ovl_fail_bad_target:
7737 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007738 }
John McCalld3224162010-01-08 00:58:21 +00007739}
7740
7741void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7742 // Desugar the type of the surrogate down to a function type,
7743 // retaining as many typedefs as possible while still showing
7744 // the function type (and, therefore, its parameter types).
7745 QualType FnType = Cand->Surrogate->getConversionType();
7746 bool isLValueReference = false;
7747 bool isRValueReference = false;
7748 bool isPointer = false;
7749 if (const LValueReferenceType *FnTypeRef =
7750 FnType->getAs<LValueReferenceType>()) {
7751 FnType = FnTypeRef->getPointeeType();
7752 isLValueReference = true;
7753 } else if (const RValueReferenceType *FnTypeRef =
7754 FnType->getAs<RValueReferenceType>()) {
7755 FnType = FnTypeRef->getPointeeType();
7756 isRValueReference = true;
7757 }
7758 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7759 FnType = FnTypePtr->getPointeeType();
7760 isPointer = true;
7761 }
7762 // Desugar down to a function type.
7763 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7764 // Reconstruct the pointer/reference as appropriate.
7765 if (isPointer) FnType = S.Context.getPointerType(FnType);
7766 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7767 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7768
7769 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7770 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007771 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007772}
7773
7774void NoteBuiltinOperatorCandidate(Sema &S,
7775 const char *Opc,
7776 SourceLocation OpLoc,
7777 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00007778 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00007779 std::string TypeStr("operator");
7780 TypeStr += Opc;
7781 TypeStr += "(";
7782 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00007783 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00007784 TypeStr += ")";
7785 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7786 } else {
7787 TypeStr += ", ";
7788 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7789 TypeStr += ")";
7790 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7791 }
7792}
7793
7794void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7795 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00007796 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00007797 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7798 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007799 if (ICS.isBad()) break; // all meaningless after first invalid
7800 if (!ICS.isAmbiguous()) continue;
7801
John McCall5c32be02010-08-24 20:38:10 +00007802 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007803 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007804 }
7805}
7806
John McCall3712d9e2010-01-15 23:32:50 +00007807SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7808 if (Cand->Function)
7809 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007810 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007811 return Cand->Surrogate->getLocation();
7812 return SourceLocation();
7813}
7814
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007815static unsigned
7816RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007817 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007818 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007819 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007820
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007821 case Sema::TDK_Incomplete:
7822 return 1;
7823
7824 case Sema::TDK_Underqualified:
7825 case Sema::TDK_Inconsistent:
7826 return 2;
7827
7828 case Sema::TDK_SubstitutionFailure:
7829 case Sema::TDK_NonDeducedMismatch:
7830 return 3;
7831
7832 case Sema::TDK_InstantiationDepth:
7833 case Sema::TDK_FailedOverloadResolution:
7834 return 4;
7835
7836 case Sema::TDK_InvalidExplicitArguments:
7837 return 5;
7838
7839 case Sema::TDK_TooManyArguments:
7840 case Sema::TDK_TooFewArguments:
7841 return 6;
7842 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007843 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007844}
7845
John McCallad2587a2010-01-12 00:48:53 +00007846struct CompareOverloadCandidatesForDisplay {
7847 Sema &S;
7848 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007849
7850 bool operator()(const OverloadCandidate *L,
7851 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007852 // Fast-path this check.
7853 if (L == R) return false;
7854
John McCall12f97bc2010-01-08 04:41:39 +00007855 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007856 if (L->Viable) {
7857 if (!R->Viable) return true;
7858
7859 // TODO: introduce a tri-valued comparison for overload
7860 // candidates. Would be more worthwhile if we had a sort
7861 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007862 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7863 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007864 } else if (R->Viable)
7865 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007866
John McCall3712d9e2010-01-15 23:32:50 +00007867 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007868
John McCall3712d9e2010-01-15 23:32:50 +00007869 // Criteria by which we can sort non-viable candidates:
7870 if (!L->Viable) {
7871 // 1. Arity mismatches come after other candidates.
7872 if (L->FailureKind == ovl_fail_too_many_arguments ||
7873 L->FailureKind == ovl_fail_too_few_arguments)
7874 return false;
7875 if (R->FailureKind == ovl_fail_too_many_arguments ||
7876 R->FailureKind == ovl_fail_too_few_arguments)
7877 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007878
John McCallfe796dd2010-01-23 05:17:32 +00007879 // 2. Bad conversions come first and are ordered by the number
7880 // of bad conversions and quality of good conversions.
7881 if (L->FailureKind == ovl_fail_bad_conversion) {
7882 if (R->FailureKind != ovl_fail_bad_conversion)
7883 return true;
7884
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007885 // The conversion that can be fixed with a smaller number of changes,
7886 // comes first.
7887 unsigned numLFixes = L->Fix.NumConversionsFixed;
7888 unsigned numRFixes = R->Fix.NumConversionsFixed;
7889 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7890 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007891 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007892 if (numLFixes < numRFixes)
7893 return true;
7894 else
7895 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007896 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007897
John McCallfe796dd2010-01-23 05:17:32 +00007898 // If there's any ordering between the defined conversions...
7899 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00007900 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00007901
7902 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007903 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007904 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007905 switch (CompareImplicitConversionSequences(S,
7906 L->Conversions[I],
7907 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007908 case ImplicitConversionSequence::Better:
7909 leftBetter++;
7910 break;
7911
7912 case ImplicitConversionSequence::Worse:
7913 leftBetter--;
7914 break;
7915
7916 case ImplicitConversionSequence::Indistinguishable:
7917 break;
7918 }
7919 }
7920 if (leftBetter > 0) return true;
7921 if (leftBetter < 0) return false;
7922
7923 } else if (R->FailureKind == ovl_fail_bad_conversion)
7924 return false;
7925
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007926 if (L->FailureKind == ovl_fail_bad_deduction) {
7927 if (R->FailureKind != ovl_fail_bad_deduction)
7928 return true;
7929
7930 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7931 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007932 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007933 } else if (R->FailureKind == ovl_fail_bad_deduction)
7934 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007935
John McCall3712d9e2010-01-15 23:32:50 +00007936 // TODO: others?
7937 }
7938
7939 // Sort everything else by location.
7940 SourceLocation LLoc = GetLocationForCandidate(L);
7941 SourceLocation RLoc = GetLocationForCandidate(R);
7942
7943 // Put candidates without locations (e.g. builtins) at the end.
7944 if (LLoc.isInvalid()) return false;
7945 if (RLoc.isInvalid()) return true;
7946
7947 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007948 }
7949};
7950
John McCallfe796dd2010-01-23 05:17:32 +00007951/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007952/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007953void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7954 Expr **Args, unsigned NumArgs) {
7955 assert(!Cand->Viable);
7956
7957 // Don't do anything on failures other than bad conversion.
7958 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7959
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007960 // We only want the FixIts if all the arguments can be corrected.
7961 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007962 // Use a implicit copy initialization to check conversion fixes.
7963 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007964
John McCallfe796dd2010-01-23 05:17:32 +00007965 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007966 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007967 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00007968 while (true) {
7969 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7970 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007971 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007972 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007973 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007974 }
John McCallfe796dd2010-01-23 05:17:32 +00007975 }
7976
7977 if (ConvIdx == ConvCount)
7978 return;
7979
John McCall65eb8792010-02-25 01:37:24 +00007980 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7981 "remaining conversion is initialized?");
7982
Douglas Gregoradc7a702010-04-16 17:45:54 +00007983 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007984 // operation somehow.
7985 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007986
7987 const FunctionProtoType* Proto;
7988 unsigned ArgIdx = ConvIdx;
7989
7990 if (Cand->IsSurrogate) {
7991 QualType ConvType
7992 = Cand->Surrogate->getConversionType().getNonReferenceType();
7993 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7994 ConvType = ConvPtrType->getPointeeType();
7995 Proto = ConvType->getAs<FunctionProtoType>();
7996 ArgIdx--;
7997 } else if (Cand->Function) {
7998 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7999 if (isa<CXXMethodDecl>(Cand->Function) &&
8000 !isa<CXXConstructorDecl>(Cand->Function))
8001 ArgIdx--;
8002 } else {
8003 // Builtin binary operator with a bad first conversion.
8004 assert(ConvCount <= 3);
8005 for (; ConvIdx != ConvCount; ++ConvIdx)
8006 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008007 = TryCopyInitialization(S, Args[ConvIdx],
8008 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008009 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008010 /*InOverloadResolution*/ true,
8011 /*AllowObjCWritebackConversion=*/
8012 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008013 return;
8014 }
8015
8016 // Fill in the rest of the conversions.
8017 unsigned NumArgsInProto = Proto->getNumArgs();
8018 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008019 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008020 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008021 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008022 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008023 /*InOverloadResolution=*/true,
8024 /*AllowObjCWritebackConversion=*/
8025 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008026 // Store the FixIt in the candidate if it exists.
8027 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008028 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008029 }
John McCallfe796dd2010-01-23 05:17:32 +00008030 else
8031 Cand->Conversions[ConvIdx].setEllipsis();
8032 }
8033}
8034
John McCalld3224162010-01-08 00:58:21 +00008035} // end anonymous namespace
8036
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008037/// PrintOverloadCandidates - When overload resolution fails, prints
8038/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008039/// set.
John McCall5c32be02010-08-24 20:38:10 +00008040void OverloadCandidateSet::NoteCandidates(Sema &S,
8041 OverloadCandidateDisplayKind OCD,
8042 Expr **Args, unsigned NumArgs,
8043 const char *Opc,
8044 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008045 // Sort the candidates by viability and position. Sorting directly would
8046 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008047 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008048 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8049 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008050 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008051 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008052 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008053 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008054 if (Cand->Function || Cand->IsSurrogate)
8055 Cands.push_back(Cand);
8056 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8057 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008058 }
8059 }
8060
John McCallad2587a2010-01-12 00:48:53 +00008061 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008062 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008063
John McCall0d1da222010-01-12 00:44:57 +00008064 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008065
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008066 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008067 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8068 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008069 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008070 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8071 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008072
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008073 // Set an arbitrary limit on the number of candidate functions we'll spam
8074 // the user with. FIXME: This limit should depend on details of the
8075 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008076 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008077 break;
8078 }
8079 ++CandsShown;
8080
John McCalld3224162010-01-08 00:58:21 +00008081 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008082 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008083 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008084 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008085 else {
8086 assert(Cand->Viable &&
8087 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008088 // Generally we only see ambiguities including viable builtin
8089 // operators if overload resolution got screwed up by an
8090 // ambiguous user-defined conversion.
8091 //
8092 // FIXME: It's quite possible for different conversions to see
8093 // different ambiguities, though.
8094 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008095 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008096 ReportedAmbiguousConversions = true;
8097 }
John McCalld3224162010-01-08 00:58:21 +00008098
John McCall0d1da222010-01-12 00:44:57 +00008099 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008100 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008101 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008102 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008103
8104 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008105 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008106}
8107
Douglas Gregorb491ed32011-02-19 21:32:49 +00008108// [PossiblyAFunctionType] --> [Return]
8109// NonFunctionType --> NonFunctionType
8110// R (A) --> R(A)
8111// R (*)(A) --> R (A)
8112// R (&)(A) --> R (A)
8113// R (S::*)(A) --> R (A)
8114QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8115 QualType Ret = PossiblyAFunctionType;
8116 if (const PointerType *ToTypePtr =
8117 PossiblyAFunctionType->getAs<PointerType>())
8118 Ret = ToTypePtr->getPointeeType();
8119 else if (const ReferenceType *ToTypeRef =
8120 PossiblyAFunctionType->getAs<ReferenceType>())
8121 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008122 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008123 PossiblyAFunctionType->getAs<MemberPointerType>())
8124 Ret = MemTypePtr->getPointeeType();
8125 Ret =
8126 Context.getCanonicalType(Ret).getUnqualifiedType();
8127 return Ret;
8128}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008129
Douglas Gregorb491ed32011-02-19 21:32:49 +00008130// A helper class to help with address of function resolution
8131// - allows us to avoid passing around all those ugly parameters
8132class AddressOfFunctionResolver
8133{
8134 Sema& S;
8135 Expr* SourceExpr;
8136 const QualType& TargetType;
8137 QualType TargetFunctionType; // Extracted function type from target type
8138
8139 bool Complain;
8140 //DeclAccessPair& ResultFunctionAccessPair;
8141 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008142
Douglas Gregorb491ed32011-02-19 21:32:49 +00008143 bool TargetTypeIsNonStaticMemberFunction;
8144 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008145
Douglas Gregorb491ed32011-02-19 21:32:49 +00008146 OverloadExpr::FindResult OvlExprInfo;
8147 OverloadExpr *OvlExpr;
8148 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008149 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008150
Douglas Gregorb491ed32011-02-19 21:32:49 +00008151public:
8152 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8153 const QualType& TargetType, bool Complain)
8154 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8155 Complain(Complain), Context(S.getASTContext()),
8156 TargetTypeIsNonStaticMemberFunction(
8157 !!TargetType->getAs<MemberPointerType>()),
8158 FoundNonTemplateFunction(false),
8159 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8160 OvlExpr(OvlExprInfo.Expression)
8161 {
8162 ExtractUnqualifiedFunctionTypeFromTargetType();
8163
8164 if (!TargetFunctionType->isFunctionType()) {
8165 if (OvlExpr->hasExplicitTemplateArgs()) {
8166 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008167 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008168 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008169
8170 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8171 if (!Method->isStatic()) {
8172 // If the target type is a non-function type and the function
8173 // found is a non-static member function, pretend as if that was
8174 // the target, it's the only possible type to end up with.
8175 TargetTypeIsNonStaticMemberFunction = true;
8176
8177 // And skip adding the function if its not in the proper form.
8178 // We'll diagnose this due to an empty set of functions.
8179 if (!OvlExprInfo.HasFormOfMemberPointer)
8180 return;
8181 }
8182 }
8183
Douglas Gregorb491ed32011-02-19 21:32:49 +00008184 Matches.push_back(std::make_pair(dap,Fn));
8185 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008186 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008187 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008188 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008189
8190 if (OvlExpr->hasExplicitTemplateArgs())
8191 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008192
Douglas Gregorb491ed32011-02-19 21:32:49 +00008193 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8194 // C++ [over.over]p4:
8195 // If more than one function is selected, [...]
8196 if (Matches.size() > 1) {
8197 if (FoundNonTemplateFunction)
8198 EliminateAllTemplateMatches();
8199 else
8200 EliminateAllExceptMostSpecializedTemplate();
8201 }
8202 }
8203 }
8204
8205private:
8206 bool isTargetTypeAFunction() const {
8207 return TargetFunctionType->isFunctionType();
8208 }
8209
8210 // [ToType] [Return]
8211
8212 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8213 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8214 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8215 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8216 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8217 }
8218
8219 // return true if any matching specializations were found
8220 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8221 const DeclAccessPair& CurAccessFunPair) {
8222 if (CXXMethodDecl *Method
8223 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8224 // Skip non-static function templates when converting to pointer, and
8225 // static when converting to member pointer.
8226 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8227 return false;
8228 }
8229 else if (TargetTypeIsNonStaticMemberFunction)
8230 return false;
8231
8232 // C++ [over.over]p2:
8233 // If the name is a function template, template argument deduction is
8234 // done (14.8.2.2), and if the argument deduction succeeds, the
8235 // resulting template argument list is used to generate a single
8236 // function template specialization, which is added to the set of
8237 // overloaded functions considered.
8238 FunctionDecl *Specialization = 0;
8239 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8240 if (Sema::TemplateDeductionResult Result
8241 = S.DeduceTemplateArguments(FunctionTemplate,
8242 &OvlExplicitTemplateArgs,
8243 TargetFunctionType, Specialization,
8244 Info)) {
8245 // FIXME: make a note of the failed deduction for diagnostics.
8246 (void)Result;
8247 return false;
8248 }
8249
8250 // Template argument deduction ensures that we have an exact match.
8251 // This function template specicalization works.
8252 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8253 assert(TargetFunctionType
8254 == Context.getCanonicalType(Specialization->getType()));
8255 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8256 return true;
8257 }
8258
8259 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8260 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008261 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008262 // Skip non-static functions when converting to pointer, and static
8263 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008264 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8265 return false;
8266 }
8267 else if (TargetTypeIsNonStaticMemberFunction)
8268 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008269
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008270 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008271 if (S.getLangOptions().CUDA)
8272 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8273 if (S.CheckCUDATarget(Caller, FunDecl))
8274 return false;
8275
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008276 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008277 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8278 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008279 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8280 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008281 Matches.push_back(std::make_pair(CurAccessFunPair,
8282 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008283 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008284 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008285 }
Mike Stump11289f42009-09-09 15:08:12 +00008286 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008287
8288 return false;
8289 }
8290
8291 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8292 bool Ret = false;
8293
8294 // If the overload expression doesn't have the form of a pointer to
8295 // member, don't try to convert it to a pointer-to-member type.
8296 if (IsInvalidFormOfPointerToMemberFunction())
8297 return false;
8298
8299 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8300 E = OvlExpr->decls_end();
8301 I != E; ++I) {
8302 // Look through any using declarations to find the underlying function.
8303 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8304
8305 // C++ [over.over]p3:
8306 // Non-member functions and static member functions match
8307 // targets of type "pointer-to-function" or "reference-to-function."
8308 // Nonstatic member functions match targets of
8309 // type "pointer-to-member-function."
8310 // Note that according to DR 247, the containing class does not matter.
8311 if (FunctionTemplateDecl *FunctionTemplate
8312 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8313 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8314 Ret = true;
8315 }
8316 // If we have explicit template arguments supplied, skip non-templates.
8317 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8318 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8319 Ret = true;
8320 }
8321 assert(Ret || Matches.empty());
8322 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008323 }
8324
Douglas Gregorb491ed32011-02-19 21:32:49 +00008325 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008326 // [...] and any given function template specialization F1 is
8327 // eliminated if the set contains a second function template
8328 // specialization whose function template is more specialized
8329 // than the function template of F1 according to the partial
8330 // ordering rules of 14.5.5.2.
8331
8332 // The algorithm specified above is quadratic. We instead use a
8333 // two-pass algorithm (similar to the one used to identify the
8334 // best viable function in an overload set) that identifies the
8335 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008336
8337 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8338 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8339 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008340
John McCall58cc69d2010-01-27 01:50:18 +00008341 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008342 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8343 TPOC_Other, 0, SourceExpr->getLocStart(),
8344 S.PDiag(),
8345 S.PDiag(diag::err_addr_ovl_ambiguous)
8346 << Matches[0].second->getDeclName(),
8347 S.PDiag(diag::note_ovl_candidate)
8348 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008349 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008350
Douglas Gregorb491ed32011-02-19 21:32:49 +00008351 if (Result != MatchesCopy.end()) {
8352 // Make it the first and only element
8353 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8354 Matches[0].second = cast<FunctionDecl>(*Result);
8355 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008356 }
8357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008358
Douglas Gregorb491ed32011-02-19 21:32:49 +00008359 void EliminateAllTemplateMatches() {
8360 // [...] any function template specializations in the set are
8361 // eliminated if the set also contains a non-template function, [...]
8362 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8363 if (Matches[I].second->getPrimaryTemplate() == 0)
8364 ++I;
8365 else {
8366 Matches[I] = Matches[--N];
8367 Matches.set_size(N);
8368 }
8369 }
8370 }
8371
8372public:
8373 void ComplainNoMatchesFound() const {
8374 assert(Matches.empty());
8375 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8376 << OvlExpr->getName() << TargetFunctionType
8377 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008378 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008379 }
8380
8381 bool IsInvalidFormOfPointerToMemberFunction() const {
8382 return TargetTypeIsNonStaticMemberFunction &&
8383 !OvlExprInfo.HasFormOfMemberPointer;
8384 }
8385
8386 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8387 // TODO: Should we condition this on whether any functions might
8388 // have matched, or is it more appropriate to do that in callers?
8389 // TODO: a fixit wouldn't hurt.
8390 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8391 << TargetType << OvlExpr->getSourceRange();
8392 }
8393
8394 void ComplainOfInvalidConversion() const {
8395 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8396 << OvlExpr->getName() << TargetType;
8397 }
8398
8399 void ComplainMultipleMatchesFound() const {
8400 assert(Matches.size() > 1);
8401 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8402 << OvlExpr->getName()
8403 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008404 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008405 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008406
8407 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8408
Douglas Gregorb491ed32011-02-19 21:32:49 +00008409 int getNumMatches() const { return Matches.size(); }
8410
8411 FunctionDecl* getMatchingFunctionDecl() const {
8412 if (Matches.size() != 1) return 0;
8413 return Matches[0].second;
8414 }
8415
8416 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8417 if (Matches.size() != 1) return 0;
8418 return &Matches[0].first;
8419 }
8420};
8421
8422/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8423/// an overloaded function (C++ [over.over]), where @p From is an
8424/// expression with overloaded function type and @p ToType is the type
8425/// we're trying to resolve to. For example:
8426///
8427/// @code
8428/// int f(double);
8429/// int f(int);
8430///
8431/// int (*pfd)(double) = f; // selects f(double)
8432/// @endcode
8433///
8434/// This routine returns the resulting FunctionDecl if it could be
8435/// resolved, and NULL otherwise. When @p Complain is true, this
8436/// routine will emit diagnostics if there is an error.
8437FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008438Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8439 QualType TargetType,
8440 bool Complain,
8441 DeclAccessPair &FoundResult,
8442 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008443 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008444
8445 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8446 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008447 int NumMatches = Resolver.getNumMatches();
8448 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008449 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008450 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8451 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8452 else
8453 Resolver.ComplainNoMatchesFound();
8454 }
8455 else if (NumMatches > 1 && Complain)
8456 Resolver.ComplainMultipleMatchesFound();
8457 else if (NumMatches == 1) {
8458 Fn = Resolver.getMatchingFunctionDecl();
8459 assert(Fn);
8460 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8461 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008462 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008463 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008464 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008465
8466 if (pHadMultipleCandidates)
8467 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008468 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008469}
8470
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008471/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008472/// resolve that overloaded function expression down to a single function.
8473///
8474/// This routine can only resolve template-ids that refer to a single function
8475/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008476/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008477/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008478FunctionDecl *
8479Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8480 bool Complain,
8481 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008482 // C++ [over.over]p1:
8483 // [...] [Note: any redundant set of parentheses surrounding the
8484 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008485 // C++ [over.over]p1:
8486 // [...] The overloaded function name can be preceded by the &
8487 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008488
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008489 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008490 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008491 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008492
8493 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008494 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008495
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008496 // Look through all of the overloaded functions, searching for one
8497 // whose type matches exactly.
8498 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008499 for (UnresolvedSetIterator I = ovl->decls_begin(),
8500 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008501 // C++0x [temp.arg.explicit]p3:
8502 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008503 // where deduction is not done, if a template argument list is
8504 // specified and it, along with any default template arguments,
8505 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008506 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008507 FunctionTemplateDecl *FunctionTemplate
8508 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008509
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008510 // C++ [over.over]p2:
8511 // If the name is a function template, template argument deduction is
8512 // done (14.8.2.2), and if the argument deduction succeeds, the
8513 // resulting template argument list is used to generate a single
8514 // function template specialization, which is added to the set of
8515 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008516 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008517 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008518 if (TemplateDeductionResult Result
8519 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8520 Specialization, Info)) {
8521 // FIXME: make a note of the failed deduction for diagnostics.
8522 (void)Result;
8523 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008524 }
8525
John McCall0009fcc2011-04-26 20:42:42 +00008526 assert(Specialization && "no specialization and no error?");
8527
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008528 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008529 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008530 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008531 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8532 << ovl->getName();
8533 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008534 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008535 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008536 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008537
John McCall0009fcc2011-04-26 20:42:42 +00008538 Matched = Specialization;
8539 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008541
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008542 return Matched;
8543}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008544
Douglas Gregor1beec452011-03-12 01:48:56 +00008545
8546
8547
John McCall50a2c2c2011-10-11 23:14:30 +00008548// Resolve and fix an overloaded expression that can be resolved
8549// because it identifies a single function template specialization.
8550//
Douglas Gregor1beec452011-03-12 01:48:56 +00008551// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008552//
8553// Return true if it was logically possible to so resolve the
8554// expression, regardless of whether or not it succeeded. Always
8555// returns true if 'complain' is set.
8556bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8557 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8558 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008559 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008560 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008561 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008562
John McCall50a2c2c2011-10-11 23:14:30 +00008563 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008564
John McCall0009fcc2011-04-26 20:42:42 +00008565 DeclAccessPair found;
8566 ExprResult SingleFunctionExpression;
8567 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8568 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008569 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8570 SrcExpr = ExprError();
8571 return true;
8572 }
John McCall0009fcc2011-04-26 20:42:42 +00008573
8574 // It is only correct to resolve to an instance method if we're
8575 // resolving a form that's permitted to be a pointer to member.
8576 // Otherwise we'll end up making a bound member expression, which
8577 // is illegal in all the contexts we resolve like this.
8578 if (!ovl.HasFormOfMemberPointer &&
8579 isa<CXXMethodDecl>(fn) &&
8580 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008581 if (!complain) return false;
8582
8583 Diag(ovl.Expression->getExprLoc(),
8584 diag::err_bound_member_function)
8585 << 0 << ovl.Expression->getSourceRange();
8586
8587 // TODO: I believe we only end up here if there's a mix of
8588 // static and non-static candidates (otherwise the expression
8589 // would have 'bound member' type, not 'overload' type).
8590 // Ideally we would note which candidate was chosen and why
8591 // the static candidates were rejected.
8592 SrcExpr = ExprError();
8593 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008594 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008595
John McCall0009fcc2011-04-26 20:42:42 +00008596 // Fix the expresion to refer to 'fn'.
8597 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008598 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008599
8600 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008601 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008602 SingleFunctionExpression =
8603 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008604 if (SingleFunctionExpression.isInvalid()) {
8605 SrcExpr = ExprError();
8606 return true;
8607 }
8608 }
John McCall0009fcc2011-04-26 20:42:42 +00008609 }
8610
8611 if (!SingleFunctionExpression.isUsable()) {
8612 if (complain) {
8613 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8614 << ovl.Expression->getName()
8615 << DestTypeForComplaining
8616 << OpRangeForComplaining
8617 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008618 NoteAllOverloadCandidates(SrcExpr.get());
8619
8620 SrcExpr = ExprError();
8621 return true;
8622 }
8623
8624 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008625 }
8626
John McCall50a2c2c2011-10-11 23:14:30 +00008627 SrcExpr = SingleFunctionExpression;
8628 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008629}
8630
Douglas Gregorcabea402009-09-22 15:41:20 +00008631/// \brief Add a single candidate to the overload set.
8632static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008633 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008634 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008635 Expr **Args, unsigned NumArgs,
8636 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008637 bool PartialOverloading,
8638 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008639 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008640 if (isa<UsingShadowDecl>(Callee))
8641 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8642
Douglas Gregorcabea402009-09-22 15:41:20 +00008643 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008644 if (ExplicitTemplateArgs) {
8645 assert(!KnownValid && "Explicit template arguments?");
8646 return;
8647 }
John McCalla0296f72010-03-19 07:35:19 +00008648 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008649 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008650 return;
John McCalld14a8642009-11-21 08:51:07 +00008651 }
8652
8653 if (FunctionTemplateDecl *FuncTemplate
8654 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008655 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8656 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008657 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008658 return;
8659 }
8660
Richard Smith95ce4f62011-06-26 22:19:54 +00008661 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008662}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008663
Douglas Gregorcabea402009-09-22 15:41:20 +00008664/// \brief Add the overload candidates named by callee and/or found by argument
8665/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008666void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008667 Expr **Args, unsigned NumArgs,
8668 OverloadCandidateSet &CandidateSet,
8669 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008670
8671#ifndef NDEBUG
8672 // Verify that ArgumentDependentLookup is consistent with the rules
8673 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008674 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008675 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8676 // and let Y be the lookup set produced by argument dependent
8677 // lookup (defined as follows). If X contains
8678 //
8679 // -- a declaration of a class member, or
8680 //
8681 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008682 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008683 //
8684 // -- a declaration that is neither a function or a function
8685 // template
8686 //
8687 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008688
John McCall57500772009-12-16 12:17:52 +00008689 if (ULE->requiresADL()) {
8690 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8691 E = ULE->decls_end(); I != E; ++I) {
8692 assert(!(*I)->getDeclContext()->isRecord());
8693 assert(isa<UsingShadowDecl>(*I) ||
8694 !(*I)->getDeclContext()->isFunctionOrMethod());
8695 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008696 }
8697 }
8698#endif
8699
John McCall57500772009-12-16 12:17:52 +00008700 // It would be nice to avoid this copy.
8701 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008702 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008703 if (ULE->hasExplicitTemplateArgs()) {
8704 ULE->copyTemplateArgumentsInto(TABuffer);
8705 ExplicitTemplateArgs = &TABuffer;
8706 }
8707
8708 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8709 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008710 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008711 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008712 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008713
John McCall57500772009-12-16 12:17:52 +00008714 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008715 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8716 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008717 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008718 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008719 PartialOverloading,
8720 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008721}
John McCalld681c392009-12-16 08:11:27 +00008722
Richard Smith998a5912011-06-05 22:42:48 +00008723/// Attempt to recover from an ill-formed use of a non-dependent name in a
8724/// template, where the non-dependent name was declared after the template
8725/// was defined. This is common in code written for a compilers which do not
8726/// correctly implement two-stage name lookup.
8727///
8728/// Returns true if a viable candidate was found and a diagnostic was issued.
8729static bool
8730DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8731 const CXXScopeSpec &SS, LookupResult &R,
8732 TemplateArgumentListInfo *ExplicitTemplateArgs,
8733 Expr **Args, unsigned NumArgs) {
8734 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8735 return false;
8736
8737 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8738 SemaRef.LookupQualifiedName(R, DC);
8739
8740 if (!R.empty()) {
8741 R.suppressDiagnostics();
8742
8743 if (isa<CXXRecordDecl>(DC)) {
8744 // Don't diagnose names we find in classes; we get much better
8745 // diagnostics for these from DiagnoseEmptyLookup.
8746 R.clear();
8747 return false;
8748 }
8749
8750 OverloadCandidateSet Candidates(FnLoc);
8751 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8752 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8753 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008754 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008755
8756 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008757 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008758 // No viable functions. Don't bother the user with notes for functions
8759 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008760 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008761 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008762 }
Richard Smith998a5912011-06-05 22:42:48 +00008763
8764 // Find the namespaces where ADL would have looked, and suggest
8765 // declaring the function there instead.
8766 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8767 Sema::AssociatedClassSet AssociatedClasses;
8768 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8769 AssociatedNamespaces,
8770 AssociatedClasses);
8771 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008772 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008773 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008774 for (Sema::AssociatedNamespaceSet::iterator
8775 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008776 end = AssociatedNamespaces.end(); it != end; ++it) {
8777 if (!Std->Encloses(*it))
8778 SuggestedNamespaces.insert(*it);
8779 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008780 } else {
8781 // Lacking the 'std::' namespace, use all of the associated namespaces.
8782 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008783 }
8784
8785 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8786 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008787 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008788 SemaRef.Diag(Best->Function->getLocation(),
8789 diag::note_not_found_by_two_phase_lookup)
8790 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008791 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008792 SemaRef.Diag(Best->Function->getLocation(),
8793 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008794 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008795 } else {
8796 // FIXME: It would be useful to list the associated namespaces here,
8797 // but the diagnostics infrastructure doesn't provide a way to produce
8798 // a localized representation of a list of items.
8799 SemaRef.Diag(Best->Function->getLocation(),
8800 diag::note_not_found_by_two_phase_lookup)
8801 << R.getLookupName() << 2;
8802 }
8803
8804 // Try to recover by calling this function.
8805 return true;
8806 }
8807
8808 R.clear();
8809 }
8810
8811 return false;
8812}
8813
8814/// Attempt to recover from ill-formed use of a non-dependent operator in a
8815/// template, where the non-dependent operator was declared after the template
8816/// was defined.
8817///
8818/// Returns true if a viable candidate was found and a diagnostic was issued.
8819static bool
8820DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8821 SourceLocation OpLoc,
8822 Expr **Args, unsigned NumArgs) {
8823 DeclarationName OpName =
8824 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8825 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8826 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8827 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8828}
8829
John McCalld681c392009-12-16 08:11:27 +00008830/// Attempts to recover from a call where no functions were found.
8831///
8832/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008833static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008834BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008835 UnresolvedLookupExpr *ULE,
8836 SourceLocation LParenLoc,
8837 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008838 SourceLocation RParenLoc,
8839 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008840
8841 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008842 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008843
John McCall57500772009-12-16 12:17:52 +00008844 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008845 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008846 if (ULE->hasExplicitTemplateArgs()) {
8847 ULE->copyTemplateArgumentsInto(TABuffer);
8848 ExplicitTemplateArgs = &TABuffer;
8849 }
8850
John McCalld681c392009-12-16 08:11:27 +00008851 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8852 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008853 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8854 ExplicitTemplateArgs, Args, NumArgs) &&
8855 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008856 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008857 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008858 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008859
John McCall57500772009-12-16 12:17:52 +00008860 assert(!R.empty() && "lookup results empty despite recovery");
8861
8862 // Build an implicit member call if appropriate. Just drop the
8863 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008864 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008865 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008866 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8867 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008868 else if (ExplicitTemplateArgs)
8869 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8870 else
8871 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8872
8873 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008874 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008875
8876 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008877 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008878 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008879 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008880 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008881}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008882
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008883/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008884/// (which eventually refers to the declaration Func) and the call
8885/// arguments Args/NumArgs, attempt to resolve the function call down
8886/// to a specific function. If overload resolution succeeds, returns
8887/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008888/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008889/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008890ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008891Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008892 SourceLocation LParenLoc,
8893 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008894 SourceLocation RParenLoc,
8895 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008896#ifndef NDEBUG
8897 if (ULE->requiresADL()) {
8898 // To do ADL, we must have found an unqualified name.
8899 assert(!ULE->getQualifier() && "qualified name with ADL");
8900
8901 // We don't perform ADL for implicit declarations of builtins.
8902 // Verify that this was correctly set up.
8903 FunctionDecl *F;
8904 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8905 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8906 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008907 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008908
John McCall57500772009-12-16 12:17:52 +00008909 // We don't perform ADL in C.
8910 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008911 } else
8912 assert(!ULE->isStdAssociatedNamespace() &&
8913 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008914#endif
8915
John McCall4124c492011-10-17 18:40:02 +00008916 UnbridgedCastsSet UnbridgedCasts;
8917 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8918 return ExprError();
8919
John McCallbc077cf2010-02-08 23:07:23 +00008920 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008921
John McCall57500772009-12-16 12:17:52 +00008922 // Add the functions denoted by the callee to the set of candidate
8923 // functions, including those from argument-dependent lookup.
8924 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008925
8926 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008927 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8928 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008929 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008930 // In Microsoft mode, if we are inside a template class member function then
8931 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008932 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008933 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00008934 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00008935 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008936 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8937 Context.DependentTy, VK_RValue,
8938 RParenLoc);
8939 CE->setTypeDependent(true);
8940 return Owned(CE);
8941 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008942 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008943 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008944 }
John McCalld681c392009-12-16 08:11:27 +00008945
John McCall4124c492011-10-17 18:40:02 +00008946 UnbridgedCasts.restore();
8947
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008948 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008949 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008950 case OR_Success: {
8951 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008952 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008953 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008954 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008955 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008956 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8957 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008958 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008959
Richard Smith998a5912011-06-05 22:42:48 +00008960 case OR_No_Viable_Function: {
8961 // Try to recover by looking for viable functions which the user might
8962 // have meant to call.
8963 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8964 Args, NumArgs, RParenLoc,
8965 /*EmptyLookup=*/false);
8966 if (!Recovery.isInvalid())
8967 return Recovery;
8968
Chris Lattner45d9d602009-02-17 07:29:20 +00008969 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008970 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008971 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008972 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008973 break;
Richard Smith998a5912011-06-05 22:42:48 +00008974 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008975
8976 case OR_Ambiguous:
8977 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008978 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008979 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008980 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008981
8982 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008983 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008984 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8985 << Best->Function->isDeleted()
8986 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008987 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008988 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008989 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00008990
8991 // We emitted an error for the unvailable/deleted function call but keep
8992 // the call in the AST.
8993 FunctionDecl *FDecl = Best->Function;
8994 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8995 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8996 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008997 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008998 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008999 }
9000
Douglas Gregorb412e172010-07-25 18:17:45 +00009001 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009002 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009003}
9004
John McCall4c4c1df2010-01-26 03:27:55 +00009005static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009006 return Functions.size() > 1 ||
9007 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9008}
9009
Douglas Gregor084d8552009-03-13 23:49:33 +00009010/// \brief Create a unary operation that may resolve to an overloaded
9011/// operator.
9012///
9013/// \param OpLoc The location of the operator itself (e.g., '*').
9014///
9015/// \param OpcIn The UnaryOperator::Opcode that describes this
9016/// operator.
9017///
9018/// \param Functions The set of non-member functions that will be
9019/// considered by overload resolution. The caller needs to build this
9020/// set based on the context using, e.g.,
9021/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9022/// set should not contain any member functions; those will be added
9023/// by CreateOverloadedUnaryOp().
9024///
9025/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009026ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009027Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9028 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009029 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009030 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009031
9032 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9033 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9034 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009035 // TODO: provide better source location info.
9036 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009037
John McCall4124c492011-10-17 18:40:02 +00009038 if (checkPlaceholderForOverload(*this, Input))
9039 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009040
Douglas Gregor084d8552009-03-13 23:49:33 +00009041 Expr *Args[2] = { Input, 0 };
9042 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009043
Douglas Gregor084d8552009-03-13 23:49:33 +00009044 // For post-increment and post-decrement, add the implicit '0' as
9045 // the second argument, so that we know this is a post-increment or
9046 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009047 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009048 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009049 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9050 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009051 NumArgs = 2;
9052 }
9053
9054 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009055 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009056 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009057 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009058 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009059 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009060 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009061
John McCall58cc69d2010-01-27 01:50:18 +00009062 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009063 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009064 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009065 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009066 /*ADL*/ true, IsOverloaded(Fns),
9067 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009068 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009069 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009070 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009071 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009072 OpLoc));
9073 }
9074
9075 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009076 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009077
9078 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009079 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009080
9081 // Add operator candidates that are member functions.
9082 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9083
John McCall4c4c1df2010-01-26 03:27:55 +00009084 // Add candidates from ADL.
9085 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009086 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009087 /*ExplicitTemplateArgs*/ 0,
9088 CandidateSet);
9089
Douglas Gregor084d8552009-03-13 23:49:33 +00009090 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009091 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009092
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009093 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9094
Douglas Gregor084d8552009-03-13 23:49:33 +00009095 // Perform overload resolution.
9096 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009097 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009098 case OR_Success: {
9099 // We found a built-in operator or an overloaded operator.
9100 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009101
Douglas Gregor084d8552009-03-13 23:49:33 +00009102 if (FnDecl) {
9103 // We matched an overloaded operator. Build a call to that
9104 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009105
Chandler Carruth30141632011-02-25 19:41:05 +00009106 MarkDeclarationReferenced(OpLoc, FnDecl);
9107
Douglas Gregor084d8552009-03-13 23:49:33 +00009108 // Convert the arguments.
9109 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009110 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009111
John Wiegley01296292011-04-08 18:41:53 +00009112 ExprResult InputRes =
9113 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9114 Best->FoundDecl, Method);
9115 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009116 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009117 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009118 } else {
9119 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009120 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009121 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009122 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009123 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009124 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009125 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009126 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009127 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009128 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009129 }
9130
John McCall4fa0d5f2010-05-06 18:15:07 +00009131 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9132
John McCall7decc9e2010-11-18 06:31:45 +00009133 // Determine the result type.
9134 QualType ResultTy = FnDecl->getResultType();
9135 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9136 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009137
Douglas Gregor084d8552009-03-13 23:49:33 +00009138 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009139 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9140 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009141 if (FnExpr.isInvalid())
9142 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009143
Eli Friedman030eee42009-11-18 03:58:17 +00009144 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009145 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009146 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009147 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009148
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009149 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009150 FnDecl))
9151 return ExprError();
9152
John McCallb268a282010-08-23 23:25:46 +00009153 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009154 } else {
9155 // We matched a built-in operator. Convert the arguments, then
9156 // break out so that we will build the appropriate built-in
9157 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009158 ExprResult InputRes =
9159 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9160 Best->Conversions[0], AA_Passing);
9161 if (InputRes.isInvalid())
9162 return ExprError();
9163 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009164 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009165 }
John Wiegley01296292011-04-08 18:41:53 +00009166 }
9167
9168 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009169 // This is an erroneous use of an operator which can be overloaded by
9170 // a non-member function. Check for non-member operators which were
9171 // defined too late to be candidates.
9172 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9173 // FIXME: Recover by calling the found function.
9174 return ExprError();
9175
John Wiegley01296292011-04-08 18:41:53 +00009176 // No viable function; fall through to handling this as a
9177 // built-in operator, which will produce an error message for us.
9178 break;
9179
9180 case OR_Ambiguous:
9181 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9182 << UnaryOperator::getOpcodeStr(Opc)
9183 << Input->getType()
9184 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009185 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009186 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9187 return ExprError();
9188
9189 case OR_Deleted:
9190 Diag(OpLoc, diag::err_ovl_deleted_oper)
9191 << Best->Function->isDeleted()
9192 << UnaryOperator::getOpcodeStr(Opc)
9193 << getDeletedOrUnavailableSuffix(Best->Function)
9194 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009195 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9196 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009197 return ExprError();
9198 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009199
9200 // Either we found no viable overloaded operator or we matched a
9201 // built-in operator. In either case, fall through to trying to
9202 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009203 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009204}
9205
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009206/// \brief Create a binary operation that may resolve to an overloaded
9207/// operator.
9208///
9209/// \param OpLoc The location of the operator itself (e.g., '+').
9210///
9211/// \param OpcIn The BinaryOperator::Opcode that describes this
9212/// operator.
9213///
9214/// \param Functions The set of non-member functions that will be
9215/// considered by overload resolution. The caller needs to build this
9216/// set based on the context using, e.g.,
9217/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9218/// set should not contain any member functions; those will be added
9219/// by CreateOverloadedBinOp().
9220///
9221/// \param LHS Left-hand argument.
9222/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009223ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009224Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009225 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009226 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009227 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009228 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009229 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009230
9231 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9232 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9233 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9234
9235 // If either side is type-dependent, create an appropriate dependent
9236 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009237 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009238 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009239 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009240 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009241 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009242 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009243 Context.DependentTy,
9244 VK_RValue, OK_Ordinary,
9245 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009246
Douglas Gregor5287f092009-11-05 00:51:44 +00009247 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9248 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009249 VK_LValue,
9250 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009251 Context.DependentTy,
9252 Context.DependentTy,
9253 OpLoc));
9254 }
John McCall4c4c1df2010-01-26 03:27:55 +00009255
9256 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009257 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009258 // TODO: provide better source location info in DNLoc component.
9259 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009260 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009261 = UnresolvedLookupExpr::Create(Context, NamingClass,
9262 NestedNameSpecifierLoc(), OpNameInfo,
9263 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009264 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009265 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009266 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009267 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009268 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009269 OpLoc));
9270 }
9271
John McCall4124c492011-10-17 18:40:02 +00009272 // Always do placeholder-like conversions on the RHS.
9273 if (checkPlaceholderForOverload(*this, Args[1]))
9274 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009275
John McCall526ab472011-10-25 17:37:35 +00009276 // Do placeholder-like conversion on the LHS; note that we should
9277 // not get here with a PseudoObject LHS.
9278 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009279 if (checkPlaceholderForOverload(*this, Args[0]))
9280 return ExprError();
9281
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009282 // If this is the assignment operator, we only perform overload resolution
9283 // if the left-hand side is a class or enumeration type. This is actually
9284 // a hack. The standard requires that we do overload resolution between the
9285 // various built-in candidates, but as DR507 points out, this can lead to
9286 // problems. So we do it this way, which pretty much follows what GCC does.
9287 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009288 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009289 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009290
John McCalle26a8722010-12-04 08:14:53 +00009291 // If this is the .* operator, which is not overloadable, just
9292 // create a built-in binary operator.
9293 if (Opc == BO_PtrMemD)
9294 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9295
Douglas Gregor084d8552009-03-13 23:49:33 +00009296 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009297 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009298
9299 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009300 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009301
9302 // Add operator candidates that are member functions.
9303 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9304
John McCall4c4c1df2010-01-26 03:27:55 +00009305 // Add candidates from ADL.
9306 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9307 Args, 2,
9308 /*ExplicitTemplateArgs*/ 0,
9309 CandidateSet);
9310
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009311 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009312 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009313
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009314 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9315
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009316 // Perform overload resolution.
9317 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009318 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009319 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009320 // We found a built-in operator or an overloaded operator.
9321 FunctionDecl *FnDecl = Best->Function;
9322
9323 if (FnDecl) {
9324 // We matched an overloaded operator. Build a call to that
9325 // operator.
9326
Chandler Carruth30141632011-02-25 19:41:05 +00009327 MarkDeclarationReferenced(OpLoc, FnDecl);
9328
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009329 // Convert the arguments.
9330 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009331 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009332 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009333
Chandler Carruth8e543b32010-12-12 08:17:55 +00009334 ExprResult Arg1 =
9335 PerformCopyInitialization(
9336 InitializedEntity::InitializeParameter(Context,
9337 FnDecl->getParamDecl(0)),
9338 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009339 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009340 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009341
John Wiegley01296292011-04-08 18:41:53 +00009342 ExprResult Arg0 =
9343 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9344 Best->FoundDecl, Method);
9345 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009346 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009347 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009348 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009349 } else {
9350 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009351 ExprResult Arg0 = PerformCopyInitialization(
9352 InitializedEntity::InitializeParameter(Context,
9353 FnDecl->getParamDecl(0)),
9354 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009355 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009356 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009357
Chandler Carruth8e543b32010-12-12 08:17:55 +00009358 ExprResult Arg1 =
9359 PerformCopyInitialization(
9360 InitializedEntity::InitializeParameter(Context,
9361 FnDecl->getParamDecl(1)),
9362 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009363 if (Arg1.isInvalid())
9364 return ExprError();
9365 Args[0] = LHS = Arg0.takeAs<Expr>();
9366 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009367 }
9368
John McCall4fa0d5f2010-05-06 18:15:07 +00009369 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9370
John McCall7decc9e2010-11-18 06:31:45 +00009371 // Determine the result type.
9372 QualType ResultTy = FnDecl->getResultType();
9373 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9374 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009375
9376 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009377 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9378 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009379 if (FnExpr.isInvalid())
9380 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009381
John McCallb268a282010-08-23 23:25:46 +00009382 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009383 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009384 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009385
9386 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009387 FnDecl))
9388 return ExprError();
9389
John McCallb268a282010-08-23 23:25:46 +00009390 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009391 } else {
9392 // We matched a built-in operator. Convert the arguments, then
9393 // break out so that we will build the appropriate built-in
9394 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009395 ExprResult ArgsRes0 =
9396 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9397 Best->Conversions[0], AA_Passing);
9398 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009399 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009400 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009401
John Wiegley01296292011-04-08 18:41:53 +00009402 ExprResult ArgsRes1 =
9403 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9404 Best->Conversions[1], AA_Passing);
9405 if (ArgsRes1.isInvalid())
9406 return ExprError();
9407 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009408 break;
9409 }
9410 }
9411
Douglas Gregor66950a32009-09-30 21:46:01 +00009412 case OR_No_Viable_Function: {
9413 // C++ [over.match.oper]p9:
9414 // If the operator is the operator , [...] and there are no
9415 // viable functions, then the operator is assumed to be the
9416 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009417 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009418 break;
9419
Chandler Carruth8e543b32010-12-12 08:17:55 +00009420 // For class as left operand for assignment or compound assigment
9421 // operator do not fall through to handling in built-in, but report that
9422 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009423 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009424 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009425 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009426 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9427 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009428 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009429 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009430 // This is an erroneous use of an operator which can be overloaded by
9431 // a non-member function. Check for non-member operators which were
9432 // defined too late to be candidates.
9433 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9434 // FIXME: Recover by calling the found function.
9435 return ExprError();
9436
Douglas Gregor66950a32009-09-30 21:46:01 +00009437 // No viable function; try to create a built-in operation, which will
9438 // produce an error. Then, show the non-viable candidates.
9439 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009440 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009441 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009442 "C++ binary operator overloading is missing candidates!");
9443 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009444 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9445 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009446 return move(Result);
9447 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009448
9449 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009450 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009451 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009452 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009453 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009454 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9455 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009456 return ExprError();
9457
9458 case OR_Deleted:
9459 Diag(OpLoc, diag::err_ovl_deleted_oper)
9460 << Best->Function->isDeleted()
9461 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009462 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009463 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009464 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9465 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009466 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009467 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009468
Douglas Gregor66950a32009-09-30 21:46:01 +00009469 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009470 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009471}
9472
John McCalldadc5752010-08-24 06:29:42 +00009473ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009474Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9475 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009476 Expr *Base, Expr *Idx) {
9477 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009478 DeclarationName OpName =
9479 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9480
9481 // If either side is type-dependent, create an appropriate dependent
9482 // expression.
9483 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9484
John McCall58cc69d2010-01-27 01:50:18 +00009485 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009486 // CHECKME: no 'operator' keyword?
9487 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9488 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009489 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009490 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009491 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009492 /*ADL*/ true, /*Overloaded*/ false,
9493 UnresolvedSetIterator(),
9494 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009495 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009496
Sebastian Redladba46e2009-10-29 20:17:01 +00009497 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9498 Args, 2,
9499 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009500 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009501 RLoc));
9502 }
9503
John McCall4124c492011-10-17 18:40:02 +00009504 // Handle placeholders on both operands.
9505 if (checkPlaceholderForOverload(*this, Args[0]))
9506 return ExprError();
9507 if (checkPlaceholderForOverload(*this, Args[1]))
9508 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009509
Sebastian Redladba46e2009-10-29 20:17:01 +00009510 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009511 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009512
9513 // Subscript can only be overloaded as a member function.
9514
9515 // Add operator candidates that are member functions.
9516 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9517
9518 // Add builtin operator candidates.
9519 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9520
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009521 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9522
Sebastian Redladba46e2009-10-29 20:17:01 +00009523 // Perform overload resolution.
9524 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009525 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009526 case OR_Success: {
9527 // We found a built-in operator or an overloaded operator.
9528 FunctionDecl *FnDecl = Best->Function;
9529
9530 if (FnDecl) {
9531 // We matched an overloaded operator. Build a call to that
9532 // operator.
9533
Chandler Carruth30141632011-02-25 19:41:05 +00009534 MarkDeclarationReferenced(LLoc, FnDecl);
9535
John McCalla0296f72010-03-19 07:35:19 +00009536 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009537 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009538
Sebastian Redladba46e2009-10-29 20:17:01 +00009539 // Convert the arguments.
9540 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009541 ExprResult Arg0 =
9542 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9543 Best->FoundDecl, Method);
9544 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009545 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009546 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009547
Anders Carlssona68e51e2010-01-29 18:37:50 +00009548 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009549 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009550 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009551 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009552 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009553 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009554 Owned(Args[1]));
9555 if (InputInit.isInvalid())
9556 return ExprError();
9557
9558 Args[1] = InputInit.takeAs<Expr>();
9559
Sebastian Redladba46e2009-10-29 20:17:01 +00009560 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009561 QualType ResultTy = FnDecl->getResultType();
9562 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9563 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009564
9565 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009566 DeclarationNameLoc LocInfo;
9567 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9568 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009569 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9570 HadMultipleCandidates,
9571 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009572 if (FnExpr.isInvalid())
9573 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009574
John McCallb268a282010-08-23 23:25:46 +00009575 CXXOperatorCallExpr *TheCall =
9576 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009577 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009578 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009579
John McCallb268a282010-08-23 23:25:46 +00009580 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009581 FnDecl))
9582 return ExprError();
9583
John McCallb268a282010-08-23 23:25:46 +00009584 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009585 } else {
9586 // We matched a built-in operator. Convert the arguments, then
9587 // break out so that we will build the appropriate built-in
9588 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009589 ExprResult ArgsRes0 =
9590 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9591 Best->Conversions[0], AA_Passing);
9592 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009593 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009594 Args[0] = ArgsRes0.take();
9595
9596 ExprResult ArgsRes1 =
9597 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9598 Best->Conversions[1], AA_Passing);
9599 if (ArgsRes1.isInvalid())
9600 return ExprError();
9601 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009602
9603 break;
9604 }
9605 }
9606
9607 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009608 if (CandidateSet.empty())
9609 Diag(LLoc, diag::err_ovl_no_oper)
9610 << Args[0]->getType() << /*subscript*/ 0
9611 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9612 else
9613 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9614 << Args[0]->getType()
9615 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009616 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9617 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009618 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009619 }
9620
9621 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009622 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009623 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009624 << Args[0]->getType() << Args[1]->getType()
9625 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009626 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9627 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009628 return ExprError();
9629
9630 case OR_Deleted:
9631 Diag(LLoc, diag::err_ovl_deleted_oper)
9632 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009633 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009634 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009635 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9636 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009637 return ExprError();
9638 }
9639
9640 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009641 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009642}
9643
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009644/// BuildCallToMemberFunction - Build a call to a member
9645/// function. MemExpr is the expression that refers to the member
9646/// function (and includes the object parameter), Args/NumArgs are the
9647/// arguments to the function call (not including the object
9648/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009649/// expression refers to a non-static member function or an overloaded
9650/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009651ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009652Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9653 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009654 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009655 assert(MemExprE->getType() == Context.BoundMemberTy ||
9656 MemExprE->getType() == Context.OverloadTy);
9657
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009658 // Dig out the member expression. This holds both the object
9659 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009660 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009661
John McCall0009fcc2011-04-26 20:42:42 +00009662 // Determine whether this is a call to a pointer-to-member function.
9663 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9664 assert(op->getType() == Context.BoundMemberTy);
9665 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9666
9667 QualType fnType =
9668 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9669
9670 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9671 QualType resultType = proto->getCallResultType(Context);
9672 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9673
9674 // Check that the object type isn't more qualified than the
9675 // member function we're calling.
9676 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9677
9678 QualType objectType = op->getLHS()->getType();
9679 if (op->getOpcode() == BO_PtrMemI)
9680 objectType = objectType->castAs<PointerType>()->getPointeeType();
9681 Qualifiers objectQuals = objectType.getQualifiers();
9682
9683 Qualifiers difference = objectQuals - funcQuals;
9684 difference.removeObjCGCAttr();
9685 difference.removeAddressSpace();
9686 if (difference) {
9687 std::string qualsString = difference.getAsString();
9688 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9689 << fnType.getUnqualifiedType()
9690 << qualsString
9691 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9692 }
9693
9694 CXXMemberCallExpr *call
9695 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9696 resultType, valueKind, RParenLoc);
9697
9698 if (CheckCallReturnType(proto->getResultType(),
9699 op->getRHS()->getSourceRange().getBegin(),
9700 call, 0))
9701 return ExprError();
9702
9703 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9704 return ExprError();
9705
9706 return MaybeBindToTemporary(call);
9707 }
9708
John McCall4124c492011-10-17 18:40:02 +00009709 UnbridgedCastsSet UnbridgedCasts;
9710 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9711 return ExprError();
9712
John McCall10eae182009-11-30 22:42:35 +00009713 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009714 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009715 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009716 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009717 if (isa<MemberExpr>(NakedMemExpr)) {
9718 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009719 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009720 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009721 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009722 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009723 } else {
9724 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009725 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009726
John McCall6e9f8f62009-12-03 04:06:58 +00009727 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009728 Expr::Classification ObjectClassification
9729 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9730 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009731
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009732 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009733 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009734
John McCall2d74de92009-12-01 22:10:20 +00009735 // FIXME: avoid copy.
9736 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9737 if (UnresExpr->hasExplicitTemplateArgs()) {
9738 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9739 TemplateArgs = &TemplateArgsBuffer;
9740 }
9741
John McCall10eae182009-11-30 22:42:35 +00009742 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9743 E = UnresExpr->decls_end(); I != E; ++I) {
9744
John McCall6e9f8f62009-12-03 04:06:58 +00009745 NamedDecl *Func = *I;
9746 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9747 if (isa<UsingShadowDecl>(Func))
9748 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9749
Douglas Gregor02824322011-01-26 19:30:28 +00009750
Francois Pichet64225792011-01-18 05:04:39 +00009751 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009752 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009753 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9754 CandidateSet);
9755 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009756 // If explicit template arguments were provided, we can't call a
9757 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009758 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009759 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009760
John McCalla0296f72010-03-19 07:35:19 +00009761 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009762 ObjectClassification,
9763 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009764 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009765 } else {
John McCall10eae182009-11-30 22:42:35 +00009766 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009767 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009768 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009769 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009770 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009771 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009772 }
Mike Stump11289f42009-09-09 15:08:12 +00009773
John McCall10eae182009-11-30 22:42:35 +00009774 DeclarationName DeclName = UnresExpr->getMemberName();
9775
John McCall4124c492011-10-17 18:40:02 +00009776 UnbridgedCasts.restore();
9777
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009778 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009779 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009780 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009781 case OR_Success:
9782 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009783 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009784 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009785 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009786 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009787 break;
9788
9789 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009790 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009791 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009792 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009793 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009794 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009795 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009796
9797 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009798 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009799 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009800 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009801 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009802 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009803
9804 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009805 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009806 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009807 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009808 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009809 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009810 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009811 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009812 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009813 }
9814
John McCall16df1e52010-03-30 21:47:33 +00009815 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009816
John McCall2d74de92009-12-01 22:10:20 +00009817 // If overload resolution picked a static member, build a
9818 // non-member call based on that function.
9819 if (Method->isStatic()) {
9820 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9821 Args, NumArgs, RParenLoc);
9822 }
9823
John McCall10eae182009-11-30 22:42:35 +00009824 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009825 }
9826
John McCall7decc9e2010-11-18 06:31:45 +00009827 QualType ResultType = Method->getResultType();
9828 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9829 ResultType = ResultType.getNonLValueExprType(Context);
9830
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009831 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009832 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009833 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009834 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009835
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009836 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009837 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009838 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009839 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009840
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009841 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009842 // We only need to do this if there was actually an overload; otherwise
9843 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009844 if (!Method->isStatic()) {
9845 ExprResult ObjectArg =
9846 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9847 FoundDecl, Method);
9848 if (ObjectArg.isInvalid())
9849 return ExprError();
9850 MemExpr->setBase(ObjectArg.take());
9851 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009852
9853 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009854 const FunctionProtoType *Proto =
9855 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009856 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009857 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009858 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009859
John McCallb268a282010-08-23 23:25:46 +00009860 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009861 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009862
Anders Carlsson47061ee2011-05-06 14:25:31 +00009863 if ((isa<CXXConstructorDecl>(CurContext) ||
9864 isa<CXXDestructorDecl>(CurContext)) &&
9865 TheCall->getMethodDecl()->isPure()) {
9866 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9867
Chandler Carruth59259262011-06-27 08:31:58 +00009868 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009869 Diag(MemExpr->getLocStart(),
9870 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9871 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9872 << MD->getParent()->getDeclName();
9873
9874 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009875 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009876 }
John McCallb268a282010-08-23 23:25:46 +00009877 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009878}
9879
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009880/// BuildCallToObjectOfClassType - Build a call to an object of class
9881/// type (C++ [over.call.object]), which can end up invoking an
9882/// overloaded function call operator (@c operator()) or performing a
9883/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009884ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009885Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009886 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009887 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009888 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009889 if (checkPlaceholderForOverload(*this, Obj))
9890 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009891 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009892
9893 UnbridgedCastsSet UnbridgedCasts;
9894 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9895 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009896
John Wiegley01296292011-04-08 18:41:53 +00009897 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9898 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009899
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009900 // C++ [over.call.object]p1:
9901 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009902 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009903 // candidate functions includes at least the function call
9904 // operators of T. The function call operators of T are obtained by
9905 // ordinary lookup of the name operator() in the context of
9906 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009907 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009908 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009909
John Wiegley01296292011-04-08 18:41:53 +00009910 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009911 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009912 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009913 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009914
John McCall27b18f82009-11-17 02:14:36 +00009915 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9916 LookupQualifiedName(R, Record->getDecl());
9917 R.suppressDiagnostics();
9918
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009919 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009920 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009921 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9922 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009923 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009924 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009925
Douglas Gregorab7897a2008-11-19 22:57:39 +00009926 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009927 // In addition, for each (non-explicit in C++0x) conversion function
9928 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009929 //
9930 // operator conversion-type-id () cv-qualifier;
9931 //
9932 // where cv-qualifier is the same cv-qualification as, or a
9933 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009934 // denotes the type "pointer to function of (P1,...,Pn) returning
9935 // R", or the type "reference to pointer to function of
9936 // (P1,...,Pn) returning R", or the type "reference to function
9937 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009938 // is also considered as a candidate function. Similarly,
9939 // surrogate call functions are added to the set of candidate
9940 // functions for each conversion function declared in an
9941 // accessible base class provided the function is not hidden
9942 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009943 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009944 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009945 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009946 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009947 NamedDecl *D = *I;
9948 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9949 if (isa<UsingShadowDecl>(D))
9950 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009951
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009952 // Skip over templated conversion functions; they aren't
9953 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009954 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009955 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009956
John McCall6e9f8f62009-12-03 04:06:58 +00009957 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009958 if (!Conv->isExplicit()) {
9959 // Strip the reference type (if any) and then the pointer type (if
9960 // any) to get down to what might be a function type.
9961 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9962 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9963 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009964
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009965 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9966 {
9967 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9968 Object.get(), Args, NumArgs, CandidateSet);
9969 }
9970 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009971 }
Mike Stump11289f42009-09-09 15:08:12 +00009972
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009973 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9974
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009975 // Perform overload resolution.
9976 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009977 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009978 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009979 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009980 // Overload resolution succeeded; we'll build the appropriate call
9981 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009982 break;
9983
9984 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009985 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009986 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9987 << Object.get()->getType() << /*call*/ 1
9988 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009989 else
John Wiegley01296292011-04-08 18:41:53 +00009990 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009991 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009992 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009993 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009994 break;
9995
9996 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009997 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009998 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009999 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010000 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010001 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010002
10003 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +000010004 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010005 diag::err_ovl_deleted_object_call)
10006 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010007 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010008 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010009 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010010 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010011 break;
Mike Stump11289f42009-09-09 15:08:12 +000010012 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010013
Douglas Gregorb412e172010-07-25 18:17:45 +000010014 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010015 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010016
John McCall4124c492011-10-17 18:40:02 +000010017 UnbridgedCasts.restore();
10018
Douglas Gregorab7897a2008-11-19 22:57:39 +000010019 if (Best->Function == 0) {
10020 // Since there is no function declaration, this is one of the
10021 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010022 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010023 = cast<CXXConversionDecl>(
10024 Best->Conversions[0].UserDefined.ConversionFunction);
10025
John Wiegley01296292011-04-08 18:41:53 +000010026 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010027 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010028
Douglas Gregorab7897a2008-11-19 22:57:39 +000010029 // We selected one of the surrogate functions that converts the
10030 // object parameter to a function pointer. Perform the conversion
10031 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010032
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010033 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010034 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010035 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10036 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010037 if (Call.isInvalid())
10038 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010039 // Record usage of conversion in an implicit cast.
10040 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10041 CK_UserDefinedConversion,
10042 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010043
Douglas Gregor668443e2011-01-20 00:18:04 +000010044 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010045 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010046 }
10047
Chandler Carruth30141632011-02-25 19:41:05 +000010048 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010049 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010050 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010051
Douglas Gregorab7897a2008-11-19 22:57:39 +000010052 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10053 // that calls this method, using Object for the implicit object
10054 // parameter and passing along the remaining arguments.
10055 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010056 const FunctionProtoType *Proto =
10057 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010058
10059 unsigned NumArgsInProto = Proto->getNumArgs();
10060 unsigned NumArgsToCheck = NumArgs;
10061
10062 // Build the full argument list for the method call (the
10063 // implicit object parameter is placed at the beginning of the
10064 // list).
10065 Expr **MethodArgs;
10066 if (NumArgs < NumArgsInProto) {
10067 NumArgsToCheck = NumArgsInProto;
10068 MethodArgs = new Expr*[NumArgsInProto + 1];
10069 } else {
10070 MethodArgs = new Expr*[NumArgs + 1];
10071 }
John Wiegley01296292011-04-08 18:41:53 +000010072 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010073 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10074 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010075
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010076 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10077 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010078 if (NewFn.isInvalid())
10079 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010080
10081 // Once we've built TheCall, all of the expressions are properly
10082 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010083 QualType ResultTy = Method->getResultType();
10084 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10085 ResultTy = ResultTy.getNonLValueExprType(Context);
10086
John McCallb268a282010-08-23 23:25:46 +000010087 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010088 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010089 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010090 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010091 delete [] MethodArgs;
10092
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010093 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010094 Method))
10095 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010096
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010097 // We may have default arguments. If so, we need to allocate more
10098 // slots in the call for them.
10099 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010100 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010101 else if (NumArgs > NumArgsInProto)
10102 NumArgsToCheck = NumArgsInProto;
10103
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010104 bool IsError = false;
10105
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010106 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010107 ExprResult ObjRes =
10108 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10109 Best->FoundDecl, Method);
10110 if (ObjRes.isInvalid())
10111 IsError = true;
10112 else
10113 Object = move(ObjRes);
10114 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010115
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010116 // Check the argument types.
10117 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010118 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010119 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010120 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010121
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010122 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010123
John McCalldadc5752010-08-24 06:29:42 +000010124 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010125 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010126 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010127 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010128 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010129
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010130 IsError |= InputInit.isInvalid();
10131 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010132 } else {
John McCalldadc5752010-08-24 06:29:42 +000010133 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010134 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10135 if (DefArg.isInvalid()) {
10136 IsError = true;
10137 break;
10138 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010139
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010140 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010141 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010142
10143 TheCall->setArg(i + 1, Arg);
10144 }
10145
10146 // If this is a variadic call, handle args passed through "...".
10147 if (Proto->isVariadic()) {
10148 // Promote the arguments (C99 6.5.2.2p7).
10149 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010150 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10151 IsError |= Arg.isInvalid();
10152 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010153 }
10154 }
10155
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010156 if (IsError) return true;
10157
John McCallb268a282010-08-23 23:25:46 +000010158 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010159 return true;
10160
John McCalle172be52010-08-24 06:09:16 +000010161 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010162}
10163
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010164/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010165/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010166/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010167ExprResult
John McCallb268a282010-08-23 23:25:46 +000010168Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010169 assert(Base->getType()->isRecordType() &&
10170 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010171
John McCall4124c492011-10-17 18:40:02 +000010172 if (checkPlaceholderForOverload(*this, Base))
10173 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010174
John McCallbc077cf2010-02-08 23:07:23 +000010175 SourceLocation Loc = Base->getExprLoc();
10176
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010177 // C++ [over.ref]p1:
10178 //
10179 // [...] An expression x->m is interpreted as (x.operator->())->m
10180 // for a class object x of type T if T::operator->() exists and if
10181 // the operator is selected as the best match function by the
10182 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010183 DeclarationName OpName =
10184 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010185 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010186 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010187
John McCallbc077cf2010-02-08 23:07:23 +000010188 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010189 PDiag(diag::err_typecheck_incomplete_tag)
10190 << Base->getSourceRange()))
10191 return ExprError();
10192
John McCall27b18f82009-11-17 02:14:36 +000010193 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10194 LookupQualifiedName(R, BaseRecord->getDecl());
10195 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010196
10197 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010198 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010199 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10200 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010201 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010202
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010203 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10204
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010205 // Perform overload resolution.
10206 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010207 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010208 case OR_Success:
10209 // Overload resolution succeeded; we'll build the call below.
10210 break;
10211
10212 case OR_No_Viable_Function:
10213 if (CandidateSet.empty())
10214 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010215 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010216 else
10217 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010218 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010219 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010220 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010221
10222 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010223 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10224 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010225 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010226 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010227
10228 case OR_Deleted:
10229 Diag(OpLoc, diag::err_ovl_deleted_oper)
10230 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010231 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010232 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010233 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010234 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010235 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010236 }
10237
Chandler Carruth30141632011-02-25 19:41:05 +000010238 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010239 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010240 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010241
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010242 // Convert the object parameter.
10243 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010244 ExprResult BaseResult =
10245 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10246 Best->FoundDecl, Method);
10247 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010248 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010249 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010250
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010251 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010252 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10253 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010254 if (FnExpr.isInvalid())
10255 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010256
John McCall7decc9e2010-11-18 06:31:45 +000010257 QualType ResultTy = Method->getResultType();
10258 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10259 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010260 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010261 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010262 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010263
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010264 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010265 Method))
10266 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010267
10268 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010269}
10270
Douglas Gregorcd695e52008-11-10 20:40:00 +000010271/// FixOverloadedFunctionReference - E is an expression that refers to
10272/// a C++ overloaded function (possibly with some parentheses and
10273/// perhaps a '&' around it). We have resolved the overloaded function
10274/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010275/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010276Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010277 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010278 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010279 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10280 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010281 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010282 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010283
Douglas Gregor51c538b2009-11-20 19:42:02 +000010284 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010285 }
10286
Douglas Gregor51c538b2009-11-20 19:42:02 +000010287 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010288 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10289 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010290 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010291 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010292 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010293 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010294 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010295 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010296
10297 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010298 ICE->getCastKind(),
10299 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010300 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010301 }
10302
Douglas Gregor51c538b2009-11-20 19:42:02 +000010303 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010304 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010305 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010306 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10307 if (Method->isStatic()) {
10308 // Do nothing: static member functions aren't any different
10309 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010310 } else {
John McCalle66edc12009-11-24 19:00:30 +000010311 // Fix the sub expression, which really has to be an
10312 // UnresolvedLookupExpr holding an overloaded member function
10313 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010314 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10315 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010316 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010317 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010318
John McCalld14a8642009-11-21 08:51:07 +000010319 assert(isa<DeclRefExpr>(SubExpr)
10320 && "fixed to something other than a decl ref");
10321 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10322 && "fixed to a member ref with no nested name qualifier");
10323
10324 // We have taken the address of a pointer to member
10325 // function. Perform the computation here so that we get the
10326 // appropriate pointer to member type.
10327 QualType ClassType
10328 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10329 QualType MemPtrType
10330 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10331
John McCall7decc9e2010-11-18 06:31:45 +000010332 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10333 VK_RValue, OK_Ordinary,
10334 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010335 }
10336 }
John McCall16df1e52010-03-30 21:47:33 +000010337 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10338 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010339 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010340 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010341
John McCalle3027922010-08-25 11:45:40 +000010342 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010343 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010344 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010345 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010346 }
John McCalld14a8642009-11-21 08:51:07 +000010347
10348 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010349 // FIXME: avoid copy.
10350 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010351 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010352 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10353 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010354 }
10355
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010356 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10357 ULE->getQualifierLoc(),
10358 Fn,
10359 ULE->getNameLoc(),
10360 Fn->getType(),
10361 VK_LValue,
10362 Found.getDecl(),
10363 TemplateArgs);
10364 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10365 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010366 }
10367
John McCall10eae182009-11-30 22:42:35 +000010368 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010369 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010370 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10371 if (MemExpr->hasExplicitTemplateArgs()) {
10372 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10373 TemplateArgs = &TemplateArgsBuffer;
10374 }
John McCall6b51f282009-11-23 01:53:49 +000010375
John McCall2d74de92009-12-01 22:10:20 +000010376 Expr *Base;
10377
John McCall7decc9e2010-11-18 06:31:45 +000010378 // If we're filling in a static method where we used to have an
10379 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010380 if (MemExpr->isImplicitAccess()) {
10381 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010382 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10383 MemExpr->getQualifierLoc(),
10384 Fn,
10385 MemExpr->getMemberLoc(),
10386 Fn->getType(),
10387 VK_LValue,
10388 Found.getDecl(),
10389 TemplateArgs);
10390 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10391 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010392 } else {
10393 SourceLocation Loc = MemExpr->getMemberLoc();
10394 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010395 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000010396 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000010397 Base = new (Context) CXXThisExpr(Loc,
10398 MemExpr->getBaseType(),
10399 /*isImplicit=*/true);
10400 }
John McCall2d74de92009-12-01 22:10:20 +000010401 } else
John McCallc3007a22010-10-26 07:05:15 +000010402 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010403
John McCall4adb38c2011-04-27 00:36:17 +000010404 ExprValueKind valueKind;
10405 QualType type;
10406 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10407 valueKind = VK_LValue;
10408 type = Fn->getType();
10409 } else {
10410 valueKind = VK_RValue;
10411 type = Context.BoundMemberTy;
10412 }
10413
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010414 MemberExpr *ME = MemberExpr::Create(Context, Base,
10415 MemExpr->isArrow(),
10416 MemExpr->getQualifierLoc(),
10417 Fn,
10418 Found,
10419 MemExpr->getMemberNameInfo(),
10420 TemplateArgs,
10421 type, valueKind, OK_Ordinary);
10422 ME->setHadMultipleCandidates(true);
10423 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010425
John McCallc3007a22010-10-26 07:05:15 +000010426 llvm_unreachable("Invalid reference to overloaded function");
10427 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010428}
10429
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010430ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010431 DeclAccessPair Found,
10432 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010433 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010434}
10435
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010436} // end namespace clang