blob: 8281597e29e08868b0e10f87c7fe40fa939133f5 [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 Kramer02b08432012-01-14 20:16:52 +0000544 for (iterator i = begin(), e = end(); i != e; ++i)
545 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
546 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000547 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000548 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000549 Functions.clear();
550}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000551
John McCall4124c492011-10-17 18:40:02 +0000552namespace {
553 class UnbridgedCastsSet {
554 struct Entry {
555 Expr **Addr;
556 Expr *Saved;
557 };
558 SmallVector<Entry, 2> Entries;
559
560 public:
561 void save(Sema &S, Expr *&E) {
562 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
563 Entry entry = { &E, E };
564 Entries.push_back(entry);
565 E = S.stripARCUnbridgedCast(E);
566 }
567
568 void restore() {
569 for (SmallVectorImpl<Entry>::iterator
570 i = Entries.begin(), e = Entries.end(); i != e; ++i)
571 *i->Addr = i->Saved;
572 }
573 };
574}
575
576/// checkPlaceholderForOverload - Do any interesting placeholder-like
577/// preprocessing on the given expression.
578///
579/// \param unbridgedCasts a collection to which to add unbridged casts;
580/// without this, they will be immediately diagnosed as errors
581///
582/// Return true on unrecoverable error.
583static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
584 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000585 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
586 // We can't handle overloaded expressions here because overload
587 // resolution might reasonably tweak them.
588 if (placeholder->getKind() == BuiltinType::Overload) return false;
589
590 // If the context potentially accepts unbridged ARC casts, strip
591 // the unbridged cast and add it to the collection for later restoration.
592 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
593 unbridgedCasts) {
594 unbridgedCasts->save(S, E);
595 return false;
596 }
597
598 // Go ahead and check everything else.
599 ExprResult result = S.CheckPlaceholderExpr(E);
600 if (result.isInvalid())
601 return true;
602
603 E = result.take();
604 return false;
605 }
606
607 // Nothing to do.
608 return false;
609}
610
611/// checkArgPlaceholdersForOverload - Check a set of call operands for
612/// placeholders.
613static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
614 unsigned numArgs,
615 UnbridgedCastsSet &unbridged) {
616 for (unsigned i = 0; i != numArgs; ++i)
617 if (checkPlaceholderForOverload(S, args[i], &unbridged))
618 return true;
619
620 return false;
621}
622
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000623// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000624// overload of the declarations in Old. This routine returns false if
625// New and Old cannot be overloaded, e.g., if New has the same
626// signature as some function in Old (C++ 1.3.10) or if the Old
627// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000628// it does return false, MatchedDecl will point to the decl that New
629// cannot be overloaded with. This decl may be a UsingShadowDecl on
630// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000631//
632// Example: Given the following input:
633//
634// void f(int, float); // #1
635// void f(int, int); // #2
636// int f(int, int); // #3
637//
638// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000639// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000640//
John McCall3d988d92009-12-02 08:47:38 +0000641// When we process #2, Old contains only the FunctionDecl for #1. By
642// comparing the parameter types, we see that #1 and #2 are overloaded
643// (since they have different signatures), so this routine returns
644// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000645//
John McCall3d988d92009-12-02 08:47:38 +0000646// When we process #3, Old is an overload set containing #1 and #2. We
647// compare the signatures of #3 to #1 (they're overloaded, so we do
648// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
649// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000650// signature), IsOverload returns false and MatchedDecl will be set to
651// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000652//
653// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
654// into a class by a using declaration. The rules for whether to hide
655// shadow declarations ignore some properties which otherwise figure
656// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000657Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000658Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
659 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000660 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000661 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000662 NamedDecl *OldD = *I;
663
664 bool OldIsUsingDecl = false;
665 if (isa<UsingShadowDecl>(OldD)) {
666 OldIsUsingDecl = true;
667
668 // We can always introduce two using declarations into the same
669 // context, even if they have identical signatures.
670 if (NewIsUsingDecl) continue;
671
672 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
673 }
674
675 // If either declaration was introduced by a using declaration,
676 // we'll need to use slightly different rules for matching.
677 // Essentially, these rules are the normal rules, except that
678 // function templates hide function templates with different
679 // return types or template parameter lists.
680 bool UseMemberUsingDeclRules =
681 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
682
John McCall3d988d92009-12-02 08:47:38 +0000683 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000684 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
685 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
686 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
687 continue;
688 }
689
John McCalldaa3d6b2009-12-09 03:35:25 +0000690 Match = *I;
691 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692 }
John McCall3d988d92009-12-02 08:47:38 +0000693 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000694 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
695 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
696 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
697 continue;
698 }
699
John McCalldaa3d6b2009-12-09 03:35:25 +0000700 Match = *I;
701 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000702 }
John McCalla8987a2942010-11-10 03:01:53 +0000703 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000704 // We can overload with these, which can show up when doing
705 // redeclaration checks for UsingDecls.
706 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000707 } else if (isa<TagDecl>(OldD)) {
708 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000709 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
710 // Optimistically assume that an unresolved using decl will
711 // overload; if it doesn't, we'll have to diagnose during
712 // template instantiation.
713 } else {
John McCall1f82f242009-11-18 22:49:29 +0000714 // (C++ 13p1):
715 // Only function declarations can be overloaded; object and type
716 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000717 Match = *I;
718 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000719 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000720 }
John McCall1f82f242009-11-18 22:49:29 +0000721
John McCalldaa3d6b2009-12-09 03:35:25 +0000722 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000723}
724
John McCalle9cccd82010-06-16 08:42:20 +0000725bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
726 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000727 // If both of the functions are extern "C", then they are not
728 // overloads.
729 if (Old->isExternC() && New->isExternC())
730 return false;
731
John McCall1f82f242009-11-18 22:49:29 +0000732 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
733 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
734
735 // C++ [temp.fct]p2:
736 // A function template can be overloaded with other function templates
737 // and with normal (non-template) functions.
738 if ((OldTemplate == 0) != (NewTemplate == 0))
739 return true;
740
741 // Is the function New an overload of the function Old?
742 QualType OldQType = Context.getCanonicalType(Old->getType());
743 QualType NewQType = Context.getCanonicalType(New->getType());
744
745 // Compare the signatures (C++ 1.3.10) of the two functions to
746 // determine whether they are overloads. If we find any mismatch
747 // in the signature, they are overloads.
748
749 // If either of these functions is a K&R-style function (no
750 // prototype), then we consider them to have matching signatures.
751 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
752 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
753 return false;
754
John McCall424cec92011-01-19 06:33:43 +0000755 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
756 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000757
758 // The signature of a function includes the types of its
759 // parameters (C++ 1.3.10), which includes the presence or absence
760 // of the ellipsis; see C++ DR 357).
761 if (OldQType != NewQType &&
762 (OldType->getNumArgs() != NewType->getNumArgs() ||
763 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000764 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000765 return true;
766
767 // C++ [temp.over.link]p4:
768 // The signature of a function template consists of its function
769 // signature, its return type and its template parameter list. The names
770 // of the template parameters are significant only for establishing the
771 // relationship between the template parameters and the rest of the
772 // signature.
773 //
774 // We check the return type and template parameter lists for function
775 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000776 //
777 // However, we don't consider either of these when deciding whether
778 // a member introduced by a shadow declaration is hidden.
779 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000780 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
781 OldTemplate->getTemplateParameters(),
782 false, TPL_TemplateMatch) ||
783 OldType->getResultType() != NewType->getResultType()))
784 return true;
785
786 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000787 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000788 //
789 // As part of this, also check whether one of the member functions
790 // is static, in which case they are not overloads (C++
791 // 13.1p2). While not part of the definition of the signature,
792 // this check is important to determine whether these functions
793 // can be overloaded.
794 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
795 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
796 if (OldMethod && NewMethod &&
797 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000798 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000799 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
800 if (!UseUsingDeclRules &&
801 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
802 (OldMethod->getRefQualifier() == RQ_None ||
803 NewMethod->getRefQualifier() == RQ_None)) {
804 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000805 // - Member function declarations with the same name and the same
806 // parameter-type-list as well as member function template
807 // declarations with the same name, the same parameter-type-list, and
808 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000809 // them, but not all, have a ref-qualifier (8.3.5).
810 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
811 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
812 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
John McCall1f82f242009-11-18 22:49:29 +0000815 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
John McCall1f82f242009-11-18 22:49:29 +0000818 // The signatures match; this is not an overload.
819 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000820}
821
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000822/// \brief Checks availability of the function depending on the current
823/// function context. Inside an unavailable function, unavailability is ignored.
824///
825/// \returns true if \arg FD is unavailable and current context is inside
826/// an available function, false otherwise.
827bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
828 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
829}
830
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000831/// \brief Tries a user-defined conversion from From to ToType.
832///
833/// Produces an implicit conversion sequence for when a standard conversion
834/// is not an option. See TryImplicitConversion for more information.
835static ImplicitConversionSequence
836TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
837 bool SuppressUserConversions,
838 bool AllowExplicit,
839 bool InOverloadResolution,
840 bool CStyle,
841 bool AllowObjCWritebackConversion) {
842 ImplicitConversionSequence ICS;
843
844 if (SuppressUserConversions) {
845 // We're not in the case above, so there is no conversion that
846 // we can perform.
847 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
848 return ICS;
849 }
850
851 // Attempt user-defined conversion.
852 OverloadCandidateSet Conversions(From->getExprLoc());
853 OverloadingResult UserDefResult
854 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
855 AllowExplicit);
856
857 if (UserDefResult == OR_Success) {
858 ICS.setUserDefined();
859 // C++ [over.ics.user]p4:
860 // A conversion of an expression of class type to the same class
861 // type is given Exact Match rank, and a conversion of an
862 // expression of class type to a base class of that type is
863 // given Conversion rank, in spite of the fact that a copy
864 // constructor (i.e., a user-defined conversion function) is
865 // called for those cases.
866 if (CXXConstructorDecl *Constructor
867 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
868 QualType FromCanon
869 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
870 QualType ToCanon
871 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
872 if (Constructor->isCopyConstructor() &&
873 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
874 // Turn this into a "standard" conversion sequence, so that it
875 // gets ranked with standard conversion sequences.
876 ICS.setStandard();
877 ICS.Standard.setAsIdentityConversion();
878 ICS.Standard.setFromType(From->getType());
879 ICS.Standard.setAllToTypes(ToType);
880 ICS.Standard.CopyConstructor = Constructor;
881 if (ToCanon != FromCanon)
882 ICS.Standard.Second = ICK_Derived_To_Base;
883 }
884 }
885
886 // C++ [over.best.ics]p4:
887 // However, when considering the argument of a user-defined
888 // conversion function that is a candidate by 13.3.1.3 when
889 // invoked for the copying of the temporary in the second step
890 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
891 // 13.3.1.6 in all cases, only standard conversion sequences and
892 // ellipsis conversion sequences are allowed.
893 if (SuppressUserConversions && ICS.isUserDefined()) {
894 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
895 }
896 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
897 ICS.setAmbiguous();
898 ICS.Ambiguous.setFromType(From->getType());
899 ICS.Ambiguous.setToType(ToType);
900 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
901 Cand != Conversions.end(); ++Cand)
902 if (Cand->Viable)
903 ICS.Ambiguous.addConversion(Cand->Function);
904 } else {
905 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
906 }
907
908 return ICS;
909}
910
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000911/// TryImplicitConversion - Attempt to perform an implicit conversion
912/// from the given expression (Expr) to the given type (ToType). This
913/// function returns an implicit conversion sequence that can be used
914/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000915///
916/// void f(float f);
917/// void g(int i) { f(i); }
918///
919/// this routine would produce an implicit conversion sequence to
920/// describe the initialization of f from i, which will be a standard
921/// conversion sequence containing an lvalue-to-rvalue conversion (C++
922/// 4.1) followed by a floating-integral conversion (C++ 4.9).
923//
924/// Note that this routine only determines how the conversion can be
925/// performed; it does not actually perform the conversion. As such,
926/// it will not produce any diagnostics if no conversion is available,
927/// but will instead return an implicit conversion sequence of kind
928/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000929///
930/// If @p SuppressUserConversions, then user-defined conversions are
931/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000932/// If @p AllowExplicit, then explicit user-defined conversions are
933/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000934///
935/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
936/// writeback conversion, which allows __autoreleasing id* parameters to
937/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000938static ImplicitConversionSequence
939TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
940 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000941 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000942 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000943 bool CStyle,
944 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000945 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000946 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000947 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000948 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000949 return ICS;
950 }
951
John McCall5c32be02010-08-24 20:38:10 +0000952 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000953 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000954 return ICS;
955 }
956
Douglas Gregor836a7e82010-08-11 02:15:33 +0000957 // C++ [over.ics.user]p4:
958 // A conversion of an expression of class type to the same class
959 // type is given Exact Match rank, and a conversion of an
960 // expression of class type to a base class of that type is
961 // given Conversion rank, in spite of the fact that a copy/move
962 // constructor (i.e., a user-defined conversion function) is
963 // called for those cases.
964 QualType FromType = From->getType();
965 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000966 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
967 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000968 ICS.setStandard();
969 ICS.Standard.setAsIdentityConversion();
970 ICS.Standard.setFromType(FromType);
971 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000972
Douglas Gregor5ab11652010-04-17 22:01:05 +0000973 // We don't actually check at this point whether there is a valid
974 // copy/move constructor, since overloading just assumes that it
975 // exists. When we actually perform initialization, we'll find the
976 // appropriate constructor to copy the returned object, if needed.
977 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000978
Douglas Gregor5ab11652010-04-17 22:01:05 +0000979 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000980 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000981 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000982
Douglas Gregor836a7e82010-08-11 02:15:33 +0000983 return ICS;
984 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000986 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
987 AllowExplicit, InOverloadResolution, CStyle,
988 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000989}
990
John McCall31168b02011-06-15 23:02:42 +0000991ImplicitConversionSequence
992Sema::TryImplicitConversion(Expr *From, QualType ToType,
993 bool SuppressUserConversions,
994 bool AllowExplicit,
995 bool InOverloadResolution,
996 bool CStyle,
997 bool AllowObjCWritebackConversion) {
998 return clang::TryImplicitConversion(*this, From, ToType,
999 SuppressUserConversions, AllowExplicit,
1000 InOverloadResolution, CStyle,
1001 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +00001002}
1003
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001004/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001005/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001006/// converted expression. Flavor is the kind of conversion we're
1007/// performing, used in the error message. If @p AllowExplicit,
1008/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001009ExprResult
1010Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001011 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001012 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001013 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001014}
1015
John Wiegley01296292011-04-08 18:41:53 +00001016ExprResult
1017Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001018 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001019 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001020 if (checkPlaceholderForOverload(*this, From))
1021 return ExprError();
1022
John McCall31168b02011-06-15 23:02:42 +00001023 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1024 bool AllowObjCWritebackConversion
1025 = getLangOptions().ObjCAutoRefCount &&
1026 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001027
John McCall5c32be02010-08-24 20:38:10 +00001028 ICS = clang::TryImplicitConversion(*this, From, ToType,
1029 /*SuppressUserConversions=*/false,
1030 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001031 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001032 /*CStyle=*/false,
1033 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001034 return PerformImplicitConversion(From, ToType, ICS, Action);
1035}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001036
1037/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001038/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001039bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1040 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001041 if (Context.hasSameUnqualifiedType(FromType, ToType))
1042 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001043
John McCall991eb4b2010-12-21 00:44:39 +00001044 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1045 // where F adds one of the following at most once:
1046 // - a pointer
1047 // - a member pointer
1048 // - a block pointer
1049 CanQualType CanTo = Context.getCanonicalType(ToType);
1050 CanQualType CanFrom = Context.getCanonicalType(FromType);
1051 Type::TypeClass TyClass = CanTo->getTypeClass();
1052 if (TyClass != CanFrom->getTypeClass()) return false;
1053 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1054 if (TyClass == Type::Pointer) {
1055 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1056 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1057 } else if (TyClass == Type::BlockPointer) {
1058 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1059 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1060 } else if (TyClass == Type::MemberPointer) {
1061 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1062 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1063 } else {
1064 return false;
1065 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001066
John McCall991eb4b2010-12-21 00:44:39 +00001067 TyClass = CanTo->getTypeClass();
1068 if (TyClass != CanFrom->getTypeClass()) return false;
1069 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1070 return false;
1071 }
1072
1073 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1074 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1075 if (!EInfo.getNoReturn()) return false;
1076
1077 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1078 assert(QualType(FromFn, 0).isCanonical());
1079 if (QualType(FromFn, 0) != CanTo) return false;
1080
1081 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001082 return true;
1083}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
Douglas Gregor46188682010-05-18 22:42:18 +00001085/// \brief Determine whether the conversion from FromType to ToType is a valid
1086/// vector conversion.
1087///
1088/// \param ICK Will be set to the vector conversion kind, if this is a vector
1089/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1091 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001092 // We need at least one of these types to be a vector type to have a vector
1093 // conversion.
1094 if (!ToType->isVectorType() && !FromType->isVectorType())
1095 return false;
1096
1097 // Identical types require no conversions.
1098 if (Context.hasSameUnqualifiedType(FromType, ToType))
1099 return false;
1100
1101 // There are no conversions between extended vector types, only identity.
1102 if (ToType->isExtVectorType()) {
1103 // There are no conversions between extended vector types other than the
1104 // identity conversion.
1105 if (FromType->isExtVectorType())
1106 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
Douglas Gregor46188682010-05-18 22:42:18 +00001108 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001109 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001110 ICK = ICK_Vector_Splat;
1111 return true;
1112 }
1113 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001114
1115 // We can perform the conversion between vector types in the following cases:
1116 // 1)vector types are equivalent AltiVec and GCC vector types
1117 // 2)lax vector conversions are permitted and the vector types are of the
1118 // same size
1119 if (ToType->isVectorType() && FromType->isVectorType()) {
1120 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001121 (Context.getLangOptions().LaxVectorConversions &&
1122 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001123 ICK = ICK_Vector_Conversion;
1124 return true;
1125 }
Douglas Gregor46188682010-05-18 22:42:18 +00001126 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001127
Douglas Gregor46188682010-05-18 22:42:18 +00001128 return false;
1129}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001130
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001131/// IsStandardConversion - Determines whether there is a standard
1132/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1133/// expression From to the type ToType. Standard conversion sequences
1134/// only consider non-class types; for conversions that involve class
1135/// types, use TryImplicitConversion. If a conversion exists, SCS will
1136/// contain the standard conversion sequence required to perform this
1137/// conversion and this routine will return true. Otherwise, this
1138/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001139static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1140 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001141 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001142 bool CStyle,
1143 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001144 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001145
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001146 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001147 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001148 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001149 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001150 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001151 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001153 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001154 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001155 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001156 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001157 return false;
1158
Mike Stump11289f42009-09-09 15:08:12 +00001159 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001160 }
1161
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 // The first conversion can be an lvalue-to-rvalue conversion,
1163 // array-to-pointer conversion, or function-to-pointer conversion
1164 // (C++ 4p1).
1165
John McCall5c32be02010-08-24 20:38:10 +00001166 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001167 DeclAccessPair AccessPair;
1168 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001169 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001170 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001171 // We were able to resolve the address of the overloaded function,
1172 // so we can convert to the type of that function.
1173 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001174
1175 // we can sometimes resolve &foo<int> regardless of ToType, so check
1176 // if the type matches (identity) or we are converting to bool
1177 if (!S.Context.hasSameUnqualifiedType(
1178 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1179 QualType resultTy;
1180 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001181 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001182 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1183 // otherwise, only a boolean conversion is standard
1184 if (!ToType->isBooleanType())
1185 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001187
Chandler Carruthffce2452011-03-29 08:08:18 +00001188 // Check if the "from" expression is taking the address of an overloaded
1189 // function and recompute the FromType accordingly. Take advantage of the
1190 // fact that non-static member functions *must* have such an address-of
1191 // expression.
1192 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1193 if (Method && !Method->isStatic()) {
1194 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1195 "Non-unary operator on non-static member address");
1196 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1197 == UO_AddrOf &&
1198 "Non-address-of operator on non-static member address");
1199 const Type *ClassType
1200 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1201 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001202 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1203 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1204 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001205 "Non-address-of operator for overloaded function expression");
1206 FromType = S.Context.getPointerType(FromType);
1207 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001208
Douglas Gregor980fb162010-04-29 18:24:40 +00001209 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001210 assert(S.Context.hasSameType(
1211 FromType,
1212 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001213 } else {
1214 return false;
1215 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001216 }
John McCall154a2fd2011-08-30 00:57:29 +00001217 // Lvalue-to-rvalue conversion (C++11 4.1):
1218 // A glvalue (3.10) of a non-function, non-array type T can
1219 // be converted to a prvalue.
1220 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001221 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001222 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001223 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001224 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001225
1226 // If T is a non-class type, the type of the rvalue is the
1227 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001228 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1229 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001230 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001231 } else if (FromType->isArrayType()) {
1232 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001233 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001234
1235 // An lvalue or rvalue of type "array of N T" or "array of unknown
1236 // bound of T" can be converted to an rvalue of type "pointer to
1237 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001238 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001239
John McCall5c32be02010-08-24 20:38:10 +00001240 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001241 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001242 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001243
1244 // For the purpose of ranking in overload resolution
1245 // (13.3.3.1.1), this conversion is considered an
1246 // array-to-pointer conversion followed by a qualification
1247 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001248 SCS.Second = ICK_Identity;
1249 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001250 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001251 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001252 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001253 }
John McCall086a4642010-11-24 05:12:34 +00001254 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001255 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001256 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001257
1258 // An lvalue of function type T can be converted to an rvalue of
1259 // type "pointer to T." The result is a pointer to the
1260 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001261 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001262 } else {
1263 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001264 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001265 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001266 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001267
1268 // The second conversion can be an integral promotion, floating
1269 // point promotion, integral conversion, floating point conversion,
1270 // floating-integral conversion, pointer conversion,
1271 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001272 // For overloading in C, this can also be a "compatible-type"
1273 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001274 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001275 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001276 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001277 // The unqualified versions of the types are the same: there's no
1278 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001279 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001280 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001281 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001282 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001283 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001284 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001285 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001286 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001287 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001288 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001289 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001290 SCS.Second = ICK_Complex_Promotion;
1291 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001292 } else if (ToType->isBooleanType() &&
1293 (FromType->isArithmeticType() ||
1294 FromType->isAnyPointerType() ||
1295 FromType->isBlockPointerType() ||
1296 FromType->isMemberPointerType() ||
1297 FromType->isNullPtrType())) {
1298 // Boolean conversions (C++ 4.12).
1299 SCS.Second = ICK_Boolean_Conversion;
1300 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001301 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001302 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001303 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001304 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001305 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001306 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001307 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001308 SCS.Second = ICK_Complex_Conversion;
1309 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001310 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1311 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001312 // Complex-real conversions (C99 6.3.1.7)
1313 SCS.Second = ICK_Complex_Real;
1314 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001315 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001316 // Floating point conversions (C++ 4.8).
1317 SCS.Second = ICK_Floating_Conversion;
1318 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001319 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001320 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001321 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001322 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001323 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001324 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001325 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001326 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001327 SCS.Second = ICK_Block_Pointer_Conversion;
1328 } else if (AllowObjCWritebackConversion &&
1329 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1330 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001331 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1332 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001333 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001334 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001335 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001336 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001337 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001338 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001339 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001340 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001341 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001342 SCS.Second = SecondICK;
1343 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001344 } else if (!S.getLangOptions().CPlusPlus &&
1345 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001346 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001347 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001348 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001349 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001350 // Treat a conversion that strips "noreturn" as an identity conversion.
1351 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001352 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1353 InOverloadResolution,
1354 SCS, CStyle)) {
1355 SCS.Second = ICK_TransparentUnionConversion;
1356 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001357 } else {
1358 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001359 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001360 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001361 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001362
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001363 QualType CanonFrom;
1364 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001365 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001366 bool ObjCLifetimeConversion;
1367 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1368 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001369 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001370 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001371 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001372 CanonFrom = S.Context.getCanonicalType(FromType);
1373 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001374 } else {
1375 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001376 SCS.Third = ICK_Identity;
1377
Mike Stump11289f42009-09-09 15:08:12 +00001378 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001379 // [...] Any difference in top-level cv-qualification is
1380 // subsumed by the initialization itself and does not constitute
1381 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001382 CanonFrom = S.Context.getCanonicalType(FromType);
1383 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001384 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001385 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001386 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001387 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1388 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001389 FromType = ToType;
1390 CanonFrom = CanonTo;
1391 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001392 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001393 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001394
1395 // If we have not converted the argument type to the parameter type,
1396 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001397 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001398 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001399
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001400 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001401}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001402
1403static bool
1404IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1405 QualType &ToType,
1406 bool InOverloadResolution,
1407 StandardConversionSequence &SCS,
1408 bool CStyle) {
1409
1410 const RecordType *UT = ToType->getAsUnionType();
1411 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1412 return false;
1413 // The field to initialize within the transparent union.
1414 RecordDecl *UD = UT->getDecl();
1415 // It's compatible if the expression matches any of the fields.
1416 for (RecordDecl::field_iterator it = UD->field_begin(),
1417 itend = UD->field_end();
1418 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001419 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1420 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001421 ToType = it->getType();
1422 return true;
1423 }
1424 }
1425 return false;
1426}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001427
1428/// IsIntegralPromotion - Determines whether the conversion from the
1429/// expression From (whose potentially-adjusted type is FromType) to
1430/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1431/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001432bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001433 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001434 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001435 if (!To) {
1436 return false;
1437 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001438
1439 // An rvalue of type char, signed char, unsigned char, short int, or
1440 // unsigned short int can be converted to an rvalue of type int if
1441 // int can represent all the values of the source type; otherwise,
1442 // the source rvalue can be converted to an rvalue of type unsigned
1443 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001444 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1445 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001446 if (// We can promote any signed, promotable integer type to an int
1447 (FromType->isSignedIntegerType() ||
1448 // We can promote any unsigned integer type whose size is
1449 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001450 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001451 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001452 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001453 }
1454
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001455 return To->getKind() == BuiltinType::UInt;
1456 }
1457
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001458 // C++0x [conv.prom]p3:
1459 // A prvalue of an unscoped enumeration type whose underlying type is not
1460 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1461 // following types that can represent all the values of the enumeration
1462 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1463 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001464 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001465 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001466 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467 // with lowest integer conversion rank (4.13) greater than the rank of long
1468 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001469 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001470 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1471 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1472 // provided for a scoped enumeration.
1473 if (FromEnumType->getDecl()->isScoped())
1474 return false;
1475
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001476 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001477 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001478 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001479 return Context.hasSameUnqualifiedType(ToType,
1480 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001481 }
John McCall56774992009-12-09 09:09:27 +00001482
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001483 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1485 // to an rvalue a prvalue of the first of the following types that can
1486 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001487 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001488 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001489 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001490 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001491 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001492 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001493 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001494 // Determine whether the type we're converting from is signed or
1495 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001496 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001497 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001498
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001499 // The types we'll try to promote to, in the appropriate
1500 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001501 QualType PromoteTypes[6] = {
1502 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001503 Context.LongTy, Context.UnsignedLongTy ,
1504 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001506 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001507 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1508 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001509 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001510 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1511 // We found the type that we can promote to. If this is the
1512 // type we wanted, we have a promotion. Otherwise, no
1513 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001514 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001515 }
1516 }
1517 }
1518
1519 // An rvalue for an integral bit-field (9.6) can be converted to an
1520 // rvalue of type int if int can represent all the values of the
1521 // bit-field; otherwise, it can be converted to unsigned int if
1522 // unsigned int can represent all the values of the bit-field. If
1523 // the bit-field is larger yet, no integral promotion applies to
1524 // it. If the bit-field has an enumerated type, it is treated as any
1525 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001526 // FIXME: We should delay checking of bit-fields until we actually perform the
1527 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001528 using llvm::APSInt;
1529 if (From)
1530 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001531 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001532 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001533 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1534 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1535 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001536
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001537 // Are we promoting to an int from a bitfield that fits in an int?
1538 if (BitWidth < ToSize ||
1539 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1540 return To->getKind() == BuiltinType::Int;
1541 }
Mike Stump11289f42009-09-09 15:08:12 +00001542
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001543 // Are we promoting to an unsigned int from an unsigned bitfield
1544 // that fits into an unsigned int?
1545 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1546 return To->getKind() == BuiltinType::UInt;
1547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001549 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001550 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551 }
Mike Stump11289f42009-09-09 15:08:12 +00001552
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553 // An rvalue of type bool can be converted to an rvalue of type int,
1554 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001555 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001557 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001558
1559 return false;
1560}
1561
1562/// IsFloatingPointPromotion - Determines whether the conversion from
1563/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1564/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001565bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001566 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1567 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001568 /// An rvalue of type float can be converted to an rvalue of type
1569 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001570 if (FromBuiltin->getKind() == BuiltinType::Float &&
1571 ToBuiltin->getKind() == BuiltinType::Double)
1572 return true;
1573
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001574 // C99 6.3.1.5p1:
1575 // When a float is promoted to double or long double, or a
1576 // double is promoted to long double [...].
1577 if (!getLangOptions().CPlusPlus &&
1578 (FromBuiltin->getKind() == BuiltinType::Float ||
1579 FromBuiltin->getKind() == BuiltinType::Double) &&
1580 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1581 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001582
1583 // Half can be promoted to float.
1584 if (FromBuiltin->getKind() == BuiltinType::Half &&
1585 ToBuiltin->getKind() == BuiltinType::Float)
1586 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001587 }
1588
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589 return false;
1590}
1591
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001592/// \brief Determine if a conversion is a complex promotion.
1593///
1594/// A complex promotion is defined as a complex -> complex conversion
1595/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001596/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001597bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001598 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001599 if (!FromComplex)
1600 return false;
1601
John McCall9dd450b2009-09-21 23:43:11 +00001602 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001603 if (!ToComplex)
1604 return false;
1605
1606 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001607 ToComplex->getElementType()) ||
1608 IsIntegralPromotion(0, FromComplex->getElementType(),
1609 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001610}
1611
Douglas Gregor237f96c2008-11-26 23:31:11 +00001612/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1613/// the pointer type FromPtr to a pointer to type ToPointee, with the
1614/// same type qualifiers as FromPtr has on its pointee type. ToType,
1615/// if non-empty, will be a pointer to ToType that may or may not have
1616/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001617///
Mike Stump11289f42009-09-09 15:08:12 +00001618static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001619BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001620 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001621 ASTContext &Context,
1622 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001623 assert((FromPtr->getTypeClass() == Type::Pointer ||
1624 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1625 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001626
John McCall31168b02011-06-15 23:02:42 +00001627 /// Conversions to 'id' subsume cv-qualifier conversions.
1628 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001629 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001630
1631 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001632 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001633 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001634 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001635
John McCall31168b02011-06-15 23:02:42 +00001636 if (StripObjCLifetime)
1637 Quals.removeObjCLifetime();
1638
Mike Stump11289f42009-09-09 15:08:12 +00001639 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001640 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001641 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001642 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001643 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001644
1645 // Build a pointer to ToPointee. It has the right qualifiers
1646 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001647 if (isa<ObjCObjectPointerType>(ToType))
1648 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001649 return Context.getPointerType(ToPointee);
1650 }
1651
1652 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001653 QualType QualifiedCanonToPointee
1654 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001655
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001656 if (isa<ObjCObjectPointerType>(ToType))
1657 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1658 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001659}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660
Mike Stump11289f42009-09-09 15:08:12 +00001661static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001662 bool InOverloadResolution,
1663 ASTContext &Context) {
1664 // Handle value-dependent integral null pointer constants correctly.
1665 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1666 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001667 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001668 return !InOverloadResolution;
1669
Douglas Gregor56751b52009-09-25 04:25:58 +00001670 return Expr->isNullPointerConstant(Context,
1671 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1672 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001673}
Mike Stump11289f42009-09-09 15:08:12 +00001674
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675/// IsPointerConversion - Determines whether the conversion of the
1676/// expression From, which has the (possibly adjusted) type FromType,
1677/// can be converted to the type ToType via a pointer conversion (C++
1678/// 4.10). If so, returns true and places the converted type (that
1679/// might differ from ToType in its cv-qualifiers at some level) into
1680/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001681///
Douglas Gregora29dc052008-11-27 01:19:21 +00001682/// This routine also supports conversions to and from block pointers
1683/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1684/// pointers to interfaces. FIXME: Once we've determined the
1685/// appropriate overloading rules for Objective-C, we may want to
1686/// split the Objective-C checks into a different routine; however,
1687/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001688/// conversions, so for now they live here. IncompatibleObjC will be
1689/// set if the conversion is an allowed Objective-C conversion that
1690/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001691bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001692 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001693 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001694 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001695 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001696 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1697 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001698 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001699
Mike Stump11289f42009-09-09 15:08:12 +00001700 // Conversion from a null pointer constant to any Objective-C pointer type.
1701 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001702 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001703 ConvertedType = ToType;
1704 return true;
1705 }
1706
Douglas Gregor231d1c62008-11-27 00:15:41 +00001707 // Blocks: Block pointers can be converted to void*.
1708 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001709 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001710 ConvertedType = ToType;
1711 return true;
1712 }
1713 // Blocks: A null pointer constant can be converted to a block
1714 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001715 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001716 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001717 ConvertedType = ToType;
1718 return true;
1719 }
1720
Sebastian Redl576fd422009-05-10 18:38:11 +00001721 // If the left-hand-side is nullptr_t, the right side can be a null
1722 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001723 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001724 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001725 ConvertedType = ToType;
1726 return true;
1727 }
1728
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001729 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001730 if (!ToTypePtr)
1731 return false;
1732
1733 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001734 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001735 ConvertedType = ToType;
1736 return true;
1737 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001738
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001740 // , including objective-c pointers.
1741 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001742 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1743 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001744 ConvertedType = BuildSimilarlyQualifiedPointerType(
1745 FromType->getAs<ObjCObjectPointerType>(),
1746 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001747 ToType, Context);
1748 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001749 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001750 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001751 if (!FromTypePtr)
1752 return false;
1753
1754 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001755
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001756 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001757 // pointer conversion, so don't do all of the work below.
1758 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1759 return false;
1760
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001761 // An rvalue of type "pointer to cv T," where T is an object type,
1762 // can be converted to an rvalue of type "pointer to cv void" (C++
1763 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001764 if (FromPointeeType->isIncompleteOrObjectType() &&
1765 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001766 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001767 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001768 ToType, Context,
1769 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001770 return true;
1771 }
1772
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001773 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001774 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001775 ToPointeeType->isVoidType()) {
1776 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1777 ToPointeeType,
1778 ToType, Context);
1779 return true;
1780 }
1781
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001782 // When we're overloading in C, we allow a special kind of pointer
1783 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001784 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001785 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001786 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001787 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001788 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001789 return true;
1790 }
1791
Douglas Gregor5c407d92008-10-23 00:40:37 +00001792 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001793 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001794 // An rvalue of type "pointer to cv D," where D is a class type,
1795 // can be converted to an rvalue of type "pointer to cv B," where
1796 // B is a base class (clause 10) of D. If B is an inaccessible
1797 // (clause 11) or ambiguous (10.2) base class of D, a program that
1798 // necessitates this conversion is ill-formed. The result of the
1799 // conversion is a pointer to the base class sub-object of the
1800 // derived class object. The null pointer value is converted to
1801 // the null pointer value of the destination type.
1802 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001803 // Note that we do not check for ambiguity or inaccessibility
1804 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001805 if (getLangOptions().CPlusPlus &&
1806 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001807 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001808 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001809 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001810 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001811 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001812 ToType, Context);
1813 return true;
1814 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001815
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001816 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1817 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1818 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1819 ToPointeeType,
1820 ToType, Context);
1821 return true;
1822 }
1823
Douglas Gregora119f102008-12-19 19:13:09 +00001824 return false;
1825}
Douglas Gregoraec25842011-04-26 23:16:46 +00001826
1827/// \brief Adopt the given qualifiers for the given type.
1828static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1829 Qualifiers TQs = T.getQualifiers();
1830
1831 // Check whether qualifiers already match.
1832 if (TQs == Qs)
1833 return T;
1834
1835 if (Qs.compatiblyIncludes(TQs))
1836 return Context.getQualifiedType(T, Qs);
1837
1838 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1839}
Douglas Gregora119f102008-12-19 19:13:09 +00001840
1841/// isObjCPointerConversion - Determines whether this is an
1842/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1843/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001844bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001845 QualType& ConvertedType,
1846 bool &IncompatibleObjC) {
1847 if (!getLangOptions().ObjC1)
1848 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001849
Douglas Gregoraec25842011-04-26 23:16:46 +00001850 // The set of qualifiers on the type we're converting from.
1851 Qualifiers FromQualifiers = FromType.getQualifiers();
1852
Steve Naroff7cae42b2009-07-10 23:34:53 +00001853 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001854 const ObjCObjectPointerType* ToObjCPtr =
1855 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001856 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001857 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001858
Steve Naroff7cae42b2009-07-10 23:34:53 +00001859 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001860 // If the pointee types are the same (ignoring qualifications),
1861 // then this is not a pointer conversion.
1862 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1863 FromObjCPtr->getPointeeType()))
1864 return false;
1865
Douglas Gregoraec25842011-04-26 23:16:46 +00001866 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001867 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001868 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001869 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001870 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001871 return true;
1872 }
1873 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001874 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001875 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001876 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001877 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001878 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001879 return true;
1880 }
1881 // Objective C++: We're able to convert from a pointer to an
1882 // interface to a pointer to a different interface.
1883 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001884 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1885 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1886 if (getLangOptions().CPlusPlus && LHS && RHS &&
1887 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1888 FromObjCPtr->getPointeeType()))
1889 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001890 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001891 ToObjCPtr->getPointeeType(),
1892 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001893 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001894 return true;
1895 }
1896
1897 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1898 // Okay: this is some kind of implicit downcast of Objective-C
1899 // interfaces, which is permitted. However, we're going to
1900 // complain about it.
1901 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001902 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001903 ToObjCPtr->getPointeeType(),
1904 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001905 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001906 return true;
1907 }
Mike Stump11289f42009-09-09 15:08:12 +00001908 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001909 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001910 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001911 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001912 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001914 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001915 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001916 // to a block pointer type.
1917 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001918 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001919 return true;
1920 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001921 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001924 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001925 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001926 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001927 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001928 return true;
1929 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001930 else
Douglas Gregora119f102008-12-19 19:13:09 +00001931 return false;
1932
Douglas Gregor033f56d2008-12-23 00:53:59 +00001933 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001934 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001935 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001936 else if (const BlockPointerType *FromBlockPtr =
1937 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001938 FromPointeeType = FromBlockPtr->getPointeeType();
1939 else
Douglas Gregora119f102008-12-19 19:13:09 +00001940 return false;
1941
Douglas Gregora119f102008-12-19 19:13:09 +00001942 // If we have pointers to pointers, recursively check whether this
1943 // is an Objective-C conversion.
1944 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1945 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1946 IncompatibleObjC)) {
1947 // We always complain about this conversion.
1948 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001949 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001950 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001951 return true;
1952 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001953 // Allow conversion of pointee being objective-c pointer to another one;
1954 // as in I* to id.
1955 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1956 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1957 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1958 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001959
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001960 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001961 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001962 return true;
1963 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001964
Douglas Gregor033f56d2008-12-23 00:53:59 +00001965 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001966 // differences in the argument and result types are in Objective-C
1967 // pointer conversions. If so, we permit the conversion (but
1968 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001969 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001970 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001971 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001972 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001973 if (FromFunctionType && ToFunctionType) {
1974 // If the function types are exactly the same, this isn't an
1975 // Objective-C pointer conversion.
1976 if (Context.getCanonicalType(FromPointeeType)
1977 == Context.getCanonicalType(ToPointeeType))
1978 return false;
1979
1980 // Perform the quick checks that will tell us whether these
1981 // function types are obviously different.
1982 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1983 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1984 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1985 return false;
1986
1987 bool HasObjCConversion = false;
1988 if (Context.getCanonicalType(FromFunctionType->getResultType())
1989 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1990 // Okay, the types match exactly. Nothing to do.
1991 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1992 ToFunctionType->getResultType(),
1993 ConvertedType, IncompatibleObjC)) {
1994 // Okay, we have an Objective-C pointer conversion.
1995 HasObjCConversion = true;
1996 } else {
1997 // Function types are too different. Abort.
1998 return false;
1999 }
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregora119f102008-12-19 19:13:09 +00002001 // Check argument types.
2002 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2003 ArgIdx != NumArgs; ++ArgIdx) {
2004 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2005 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2006 if (Context.getCanonicalType(FromArgType)
2007 == Context.getCanonicalType(ToArgType)) {
2008 // Okay, the types match exactly. Nothing to do.
2009 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2010 ConvertedType, IncompatibleObjC)) {
2011 // Okay, we have an Objective-C pointer conversion.
2012 HasObjCConversion = true;
2013 } else {
2014 // Argument types are too different. Abort.
2015 return false;
2016 }
2017 }
2018
2019 if (HasObjCConversion) {
2020 // We had an Objective-C conversion. Allow this pointer
2021 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002022 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002023 IncompatibleObjC = true;
2024 return true;
2025 }
2026 }
2027
Sebastian Redl72b597d2009-01-25 19:43:20 +00002028 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002029}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030
John McCall31168b02011-06-15 23:02:42 +00002031/// \brief Determine whether this is an Objective-C writeback conversion,
2032/// used for parameter passing when performing automatic reference counting.
2033///
2034/// \param FromType The type we're converting form.
2035///
2036/// \param ToType The type we're converting to.
2037///
2038/// \param ConvertedType The type that will be produced after applying
2039/// this conversion.
2040bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2041 QualType &ConvertedType) {
2042 if (!getLangOptions().ObjCAutoRefCount ||
2043 Context.hasSameUnqualifiedType(FromType, ToType))
2044 return false;
2045
2046 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2047 QualType ToPointee;
2048 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2049 ToPointee = ToPointer->getPointeeType();
2050 else
2051 return false;
2052
2053 Qualifiers ToQuals = ToPointee.getQualifiers();
2054 if (!ToPointee->isObjCLifetimeType() ||
2055 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2056 !ToQuals.withoutObjCGLifetime().empty())
2057 return false;
2058
2059 // Argument must be a pointer to __strong to __weak.
2060 QualType FromPointee;
2061 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2062 FromPointee = FromPointer->getPointeeType();
2063 else
2064 return false;
2065
2066 Qualifiers FromQuals = FromPointee.getQualifiers();
2067 if (!FromPointee->isObjCLifetimeType() ||
2068 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2069 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2070 return false;
2071
2072 // Make sure that we have compatible qualifiers.
2073 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2074 if (!ToQuals.compatiblyIncludes(FromQuals))
2075 return false;
2076
2077 // Remove qualifiers from the pointee type we're converting from; they
2078 // aren't used in the compatibility check belong, and we'll be adding back
2079 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2080 FromPointee = FromPointee.getUnqualifiedType();
2081
2082 // The unqualified form of the pointee types must be compatible.
2083 ToPointee = ToPointee.getUnqualifiedType();
2084 bool IncompatibleObjC;
2085 if (Context.typesAreCompatible(FromPointee, ToPointee))
2086 FromPointee = ToPointee;
2087 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2088 IncompatibleObjC))
2089 return false;
2090
2091 /// \brief Construct the type we're converting to, which is a pointer to
2092 /// __autoreleasing pointee.
2093 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2094 ConvertedType = Context.getPointerType(FromPointee);
2095 return true;
2096}
2097
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002098bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2099 QualType& ConvertedType) {
2100 QualType ToPointeeType;
2101 if (const BlockPointerType *ToBlockPtr =
2102 ToType->getAs<BlockPointerType>())
2103 ToPointeeType = ToBlockPtr->getPointeeType();
2104 else
2105 return false;
2106
2107 QualType FromPointeeType;
2108 if (const BlockPointerType *FromBlockPtr =
2109 FromType->getAs<BlockPointerType>())
2110 FromPointeeType = FromBlockPtr->getPointeeType();
2111 else
2112 return false;
2113 // We have pointer to blocks, check whether the only
2114 // differences in the argument and result types are in Objective-C
2115 // pointer conversions. If so, we permit the conversion.
2116
2117 const FunctionProtoType *FromFunctionType
2118 = FromPointeeType->getAs<FunctionProtoType>();
2119 const FunctionProtoType *ToFunctionType
2120 = ToPointeeType->getAs<FunctionProtoType>();
2121
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002122 if (!FromFunctionType || !ToFunctionType)
2123 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002124
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002125 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002126 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002127
2128 // Perform the quick checks that will tell us whether these
2129 // function types are obviously different.
2130 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2131 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2132 return false;
2133
2134 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2135 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2136 if (FromEInfo != ToEInfo)
2137 return false;
2138
2139 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002140 if (Context.hasSameType(FromFunctionType->getResultType(),
2141 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002142 // Okay, the types match exactly. Nothing to do.
2143 } else {
2144 QualType RHS = FromFunctionType->getResultType();
2145 QualType LHS = ToFunctionType->getResultType();
2146 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2147 !RHS.hasQualifiers() && LHS.hasQualifiers())
2148 LHS = LHS.getUnqualifiedType();
2149
2150 if (Context.hasSameType(RHS,LHS)) {
2151 // OK exact match.
2152 } else if (isObjCPointerConversion(RHS, LHS,
2153 ConvertedType, IncompatibleObjC)) {
2154 if (IncompatibleObjC)
2155 return false;
2156 // Okay, we have an Objective-C pointer conversion.
2157 }
2158 else
2159 return false;
2160 }
2161
2162 // Check argument types.
2163 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2164 ArgIdx != NumArgs; ++ArgIdx) {
2165 IncompatibleObjC = false;
2166 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2167 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2168 if (Context.hasSameType(FromArgType, ToArgType)) {
2169 // Okay, the types match exactly. Nothing to do.
2170 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2171 ConvertedType, IncompatibleObjC)) {
2172 if (IncompatibleObjC)
2173 return false;
2174 // Okay, we have an Objective-C pointer conversion.
2175 } else
2176 // Argument types are too different. Abort.
2177 return false;
2178 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002179 if (LangOpts.ObjCAutoRefCount &&
2180 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2181 ToFunctionType))
2182 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002183
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002184 ConvertedType = ToType;
2185 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002186}
2187
Richard Trieucaff2472011-11-23 22:32:32 +00002188enum {
2189 ft_default,
2190 ft_different_class,
2191 ft_parameter_arity,
2192 ft_parameter_mismatch,
2193 ft_return_type,
2194 ft_qualifer_mismatch
2195};
2196
2197/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2198/// function types. Catches different number of parameter, mismatch in
2199/// parameter types, and different return types.
2200void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2201 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002202 // If either type is not valid, include no extra info.
2203 if (FromType.isNull() || ToType.isNull()) {
2204 PDiag << ft_default;
2205 return;
2206 }
2207
Richard Trieucaff2472011-11-23 22:32:32 +00002208 // Get the function type from the pointers.
2209 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2210 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2211 *ToMember = ToType->getAs<MemberPointerType>();
2212 if (FromMember->getClass() != ToMember->getClass()) {
2213 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2214 << QualType(FromMember->getClass(), 0);
2215 return;
2216 }
2217 FromType = FromMember->getPointeeType();
2218 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002219 }
2220
Richard Trieu96ed5b62011-12-13 23:19:45 +00002221 if (FromType->isPointerType())
2222 FromType = FromType->getPointeeType();
2223 if (ToType->isPointerType())
2224 ToType = ToType->getPointeeType();
2225
2226 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002227 FromType = FromType.getNonReferenceType();
2228 ToType = ToType.getNonReferenceType();
2229
Richard Trieucaff2472011-11-23 22:32:32 +00002230 // Don't print extra info for non-specialized template functions.
2231 if (FromType->isInstantiationDependentType() &&
2232 !FromType->getAs<TemplateSpecializationType>()) {
2233 PDiag << ft_default;
2234 return;
2235 }
2236
Richard Trieu96ed5b62011-12-13 23:19:45 +00002237 // No extra info for same types.
2238 if (Context.hasSameType(FromType, ToType)) {
2239 PDiag << ft_default;
2240 return;
2241 }
2242
Richard Trieucaff2472011-11-23 22:32:32 +00002243 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2244 *ToFunction = ToType->getAs<FunctionProtoType>();
2245
2246 // Both types need to be function types.
2247 if (!FromFunction || !ToFunction) {
2248 PDiag << ft_default;
2249 return;
2250 }
2251
2252 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2253 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2254 << FromFunction->getNumArgs();
2255 return;
2256 }
2257
2258 // Handle different parameter types.
2259 unsigned ArgPos;
2260 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2261 PDiag << ft_parameter_mismatch << ArgPos + 1
2262 << ToFunction->getArgType(ArgPos)
2263 << FromFunction->getArgType(ArgPos);
2264 return;
2265 }
2266
2267 // Handle different return type.
2268 if (!Context.hasSameType(FromFunction->getResultType(),
2269 ToFunction->getResultType())) {
2270 PDiag << ft_return_type << ToFunction->getResultType()
2271 << FromFunction->getResultType();
2272 return;
2273 }
2274
2275 unsigned FromQuals = FromFunction->getTypeQuals(),
2276 ToQuals = ToFunction->getTypeQuals();
2277 if (FromQuals != ToQuals) {
2278 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2279 return;
2280 }
2281
2282 // Unable to find a difference, so add no extra info.
2283 PDiag << ft_default;
2284}
2285
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002286/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002287/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002288/// they have same number of arguments. This routine assumes that Objective-C
2289/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002290/// If the parameters are different, ArgPos will have the the parameter index
2291/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002292bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002293 const FunctionProtoType *NewType,
2294 unsigned *ArgPos) {
2295 if (!getLangOptions().ObjC1) {
2296 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2297 N = NewType->arg_type_begin(),
2298 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2299 if (!Context.hasSameType(*O, *N)) {
2300 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2301 return false;
2302 }
2303 }
2304 return true;
2305 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002306
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002307 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2308 N = NewType->arg_type_begin(),
2309 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2310 QualType ToType = (*O);
2311 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002312 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002313 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2314 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002315 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2316 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2317 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2318 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002319 continue;
2320 }
John McCall8b07ec22010-05-15 11:32:37 +00002321 else if (const ObjCObjectPointerType *PTTo =
2322 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002323 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002324 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002325 if (Context.hasSameUnqualifiedType(
2326 PTTo->getObjectType()->getBaseType(),
2327 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002328 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002329 }
Richard Trieucaff2472011-11-23 22:32:32 +00002330 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002331 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002332 }
2333 }
2334 return true;
2335}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002336
Douglas Gregor39c16d42008-10-24 04:54:22 +00002337/// CheckPointerConversion - Check the pointer conversion from the
2338/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002339/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002340/// conversions for which IsPointerConversion has already returned
2341/// true. It returns true and produces a diagnostic if there was an
2342/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002343bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002344 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002345 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002346 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002347 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002348 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002349
John McCall8cb679e2010-11-15 09:13:47 +00002350 Kind = CK_BitCast;
2351
Chandler Carruthffab8732011-04-09 07:32:05 +00002352 if (!IsCStyleOrFunctionalCast &&
2353 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2354 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2355 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002356 PDiag(diag::warn_impcast_bool_to_null_pointer)
2357 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002358
John McCall9320b872011-09-09 05:25:32 +00002359 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2360 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002361 QualType FromPointeeType = FromPtrType->getPointeeType(),
2362 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002363
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002364 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2365 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002366 // We must have a derived-to-base conversion. Check an
2367 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002368 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2369 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002370 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002371 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002372 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002373
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002374 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002375 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002376 }
2377 }
John McCall9320b872011-09-09 05:25:32 +00002378 } else if (const ObjCObjectPointerType *ToPtrType =
2379 ToType->getAs<ObjCObjectPointerType>()) {
2380 if (const ObjCObjectPointerType *FromPtrType =
2381 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002382 // Objective-C++ conversions are always okay.
2383 // FIXME: We should have a different class of conversions for the
2384 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002385 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002386 return false;
John McCall9320b872011-09-09 05:25:32 +00002387 } else if (FromType->isBlockPointerType()) {
2388 Kind = CK_BlockPointerToObjCPointerCast;
2389 } else {
2390 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002391 }
John McCall9320b872011-09-09 05:25:32 +00002392 } else if (ToType->isBlockPointerType()) {
2393 if (!FromType->isBlockPointerType())
2394 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002395 }
John McCall8cb679e2010-11-15 09:13:47 +00002396
2397 // We shouldn't fall into this case unless it's valid for other
2398 // reasons.
2399 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2400 Kind = CK_NullToPointer;
2401
Douglas Gregor39c16d42008-10-24 04:54:22 +00002402 return false;
2403}
2404
Sebastian Redl72b597d2009-01-25 19:43:20 +00002405/// IsMemberPointerConversion - Determines whether the conversion of the
2406/// expression From, which has the (possibly adjusted) type FromType, can be
2407/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2408/// If so, returns true and places the converted type (that might differ from
2409/// ToType in its cv-qualifiers at some level) into ConvertedType.
2410bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002411 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002412 bool InOverloadResolution,
2413 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002414 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002415 if (!ToTypePtr)
2416 return false;
2417
2418 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002419 if (From->isNullPointerConstant(Context,
2420 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2421 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002422 ConvertedType = ToType;
2423 return true;
2424 }
2425
2426 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002427 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002428 if (!FromTypePtr)
2429 return false;
2430
2431 // A pointer to member of B can be converted to a pointer to member of D,
2432 // where D is derived from B (C++ 4.11p2).
2433 QualType FromClass(FromTypePtr->getClass(), 0);
2434 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002435
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002436 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2437 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2438 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002439 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2440 ToClass.getTypePtr());
2441 return true;
2442 }
2443
2444 return false;
2445}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002446
Sebastian Redl72b597d2009-01-25 19:43:20 +00002447/// CheckMemberPointerConversion - Check the member pointer conversion from the
2448/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002449/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002450/// for which IsMemberPointerConversion has already returned true. It returns
2451/// true and produces a diagnostic if there was an error, or returns false
2452/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002453bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002454 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002455 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002456 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002457 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002458 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002459 if (!FromPtrType) {
2460 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002461 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002462 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002463 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002464 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002465 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002466 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002467
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002468 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002469 assert(ToPtrType && "No member pointer cast has a target type "
2470 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002471
Sebastian Redled8f2002009-01-28 18:33:18 +00002472 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2473 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002474
Sebastian Redled8f2002009-01-28 18:33:18 +00002475 // FIXME: What about dependent types?
2476 assert(FromClass->isRecordType() && "Pointer into non-class.");
2477 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002478
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002479 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002480 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002481 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2482 assert(DerivationOkay &&
2483 "Should not have been called if derivation isn't OK.");
2484 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002485
Sebastian Redled8f2002009-01-28 18:33:18 +00002486 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2487 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002488 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2489 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2490 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2491 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002492 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002493
Douglas Gregor89ee6822009-02-28 01:32:25 +00002494 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002495 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2496 << FromClass << ToClass << QualType(VBase, 0)
2497 << From->getSourceRange();
2498 return true;
2499 }
2500
John McCall5b0829a2010-02-10 09:31:12 +00002501 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002502 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2503 Paths.front(),
2504 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002505
Anders Carlssond7923c62009-08-22 23:33:40 +00002506 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002507 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002508 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002509 return false;
2510}
2511
Douglas Gregor9a657932008-10-21 23:43:52 +00002512/// IsQualificationConversion - Determines whether the conversion from
2513/// an rvalue of type FromType to ToType is a qualification conversion
2514/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002515///
2516/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2517/// when the qualification conversion involves a change in the Objective-C
2518/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002519bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002520Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002521 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002522 FromType = Context.getCanonicalType(FromType);
2523 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002524 ObjCLifetimeConversion = false;
2525
Douglas Gregor9a657932008-10-21 23:43:52 +00002526 // If FromType and ToType are the same type, this is not a
2527 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002528 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002529 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002530
Douglas Gregor9a657932008-10-21 23:43:52 +00002531 // (C++ 4.4p4):
2532 // A conversion can add cv-qualifiers at levels other than the first
2533 // in multi-level pointers, subject to the following rules: [...]
2534 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002535 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002536 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002537 // Within each iteration of the loop, we check the qualifiers to
2538 // determine if this still looks like a qualification
2539 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002540 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002541 // until there are no more pointers or pointers-to-members left to
2542 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002543 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002544
Douglas Gregor90609aa2011-04-25 18:40:17 +00002545 Qualifiers FromQuals = FromType.getQualifiers();
2546 Qualifiers ToQuals = ToType.getQualifiers();
2547
John McCall31168b02011-06-15 23:02:42 +00002548 // Objective-C ARC:
2549 // Check Objective-C lifetime conversions.
2550 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2551 UnwrappedAnyPointer) {
2552 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2553 ObjCLifetimeConversion = true;
2554 FromQuals.removeObjCLifetime();
2555 ToQuals.removeObjCLifetime();
2556 } else {
2557 // Qualification conversions cannot cast between different
2558 // Objective-C lifetime qualifiers.
2559 return false;
2560 }
2561 }
2562
Douglas Gregorf30053d2011-05-08 06:09:53 +00002563 // Allow addition/removal of GC attributes but not changing GC attributes.
2564 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2565 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2566 FromQuals.removeObjCGCAttr();
2567 ToQuals.removeObjCGCAttr();
2568 }
2569
Douglas Gregor9a657932008-10-21 23:43:52 +00002570 // -- for every j > 0, if const is in cv 1,j then const is in cv
2571 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002572 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002573 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002574
Douglas Gregor9a657932008-10-21 23:43:52 +00002575 // -- if the cv 1,j and cv 2,j are different, then const is in
2576 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002577 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002578 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002579 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002580
Douglas Gregor9a657932008-10-21 23:43:52 +00002581 // Keep track of whether all prior cv-qualifiers in the "to" type
2582 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002583 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002584 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002585 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002586
2587 // We are left with FromType and ToType being the pointee types
2588 // after unwrapping the original FromType and ToType the same number
2589 // of types. If we unwrapped any pointers, and if FromType and
2590 // ToType have the same unqualified type (since we checked
2591 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002592 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002593}
2594
Douglas Gregor576e98c2009-01-30 23:27:23 +00002595/// Determines whether there is a user-defined conversion sequence
2596/// (C++ [over.ics.user]) that converts expression From to the type
2597/// ToType. If such a conversion exists, User will contain the
2598/// user-defined conversion sequence that performs such a conversion
2599/// and this routine will return true. Otherwise, this routine returns
2600/// false and User is unspecified.
2601///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002602/// \param AllowExplicit true if the conversion should consider C++0x
2603/// "explicit" conversion functions as well as non-explicit conversion
2604/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002605static OverloadingResult
2606IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2607 UserDefinedConversionSequence& User,
2608 OverloadCandidateSet& CandidateSet,
2609 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002610 // Whether we will only visit constructors.
2611 bool ConstructorsOnly = false;
2612
2613 // If the type we are conversion to is a class type, enumerate its
2614 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002615 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002616 // C++ [over.match.ctor]p1:
2617 // When objects of class type are direct-initialized (8.5), or
2618 // copy-initialized from an expression of the same or a
2619 // derived class type (8.5), overload resolution selects the
2620 // constructor. [...] For copy-initialization, the candidate
2621 // functions are all the converting constructors (12.3.1) of
2622 // that class. The argument list is the expression-list within
2623 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002624 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002625 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002626 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002627 ConstructorsOnly = true;
2628
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002629 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2630 // RequireCompleteType may have returned true due to some invalid decl
2631 // during template instantiation, but ToType may be complete enough now
2632 // to try to recover.
2633 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002634 // We're not going to find any constructors.
2635 } else if (CXXRecordDecl *ToRecordDecl
2636 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002637
2638 Expr **Args = &From;
2639 unsigned NumArgs = 1;
2640 bool ListInitializing = false;
2641 // If we're list-initializing, we pass the individual elements as
2642 // arguments, not the entire list.
2643 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2644 Args = InitList->getInits();
2645 NumArgs = InitList->getNumInits();
2646 ListInitializing = true;
2647 }
2648
Douglas Gregor89ee6822009-02-28 01:32:25 +00002649 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002650 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002651 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002652 NamedDecl *D = *Con;
2653 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2654
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002655 // Find the constructor (which may be a template).
2656 CXXConstructorDecl *Constructor = 0;
2657 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002658 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002659 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002660 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002661 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2662 else
John McCalla0296f72010-03-19 07:35:19 +00002663 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002665 bool Usable = !Constructor->isInvalidDecl();
2666 if (ListInitializing)
2667 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2668 else
2669 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2670 if (Usable) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002671 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002672 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2673 /*ExplicitArgs*/ 0,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002674 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002675 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002676 !ConstructorsOnly &&
2677 !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002678 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002679 // Allow one user-defined conversion when user specifies a
2680 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002681 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002682 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002683 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002684 !ConstructorsOnly && !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002685 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002686 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002687 }
2688 }
2689
Douglas Gregor5ab11652010-04-17 22:01:05 +00002690 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002691 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002692 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2693 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002694 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002695 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002696 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002697 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002698 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2699 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002700 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002701 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002702 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002703 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002704 DeclAccessPair FoundDecl = I.getPair();
2705 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002706 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2707 if (isa<UsingShadowDecl>(D))
2708 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2709
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002710 CXXConversionDecl *Conv;
2711 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002712 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2713 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002714 else
John McCallda4458e2010-03-31 01:36:47 +00002715 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002716
2717 if (AllowExplicit || !Conv->isExplicit()) {
2718 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002719 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2720 ActingContext, From, ToType,
2721 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002722 else
John McCall5c32be02010-08-24 20:38:10 +00002723 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2724 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002725 }
2726 }
2727 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002728 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002729
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002730 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2731
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002732 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002733 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002734 case OR_Success:
2735 // Record the standard conversion we used and the conversion function.
2736 if (CXXConstructorDecl *Constructor
2737 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002738 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2739
John McCall5c32be02010-08-24 20:38:10 +00002740 // C++ [over.ics.user]p1:
2741 // If the user-defined conversion is specified by a
2742 // constructor (12.3.1), the initial standard conversion
2743 // sequence converts the source type to the type required by
2744 // the argument of the constructor.
2745 //
2746 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002747 if (isa<InitListExpr>(From)) {
2748 // Initializer lists don't have conversions as such.
2749 User.Before.setAsIdentityConversion();
2750 } else {
2751 if (Best->Conversions[0].isEllipsis())
2752 User.EllipsisConversion = true;
2753 else {
2754 User.Before = Best->Conversions[0].Standard;
2755 User.EllipsisConversion = false;
2756 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002757 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002758 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002759 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002760 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002761 User.After.setAsIdentityConversion();
2762 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2763 User.After.setAllToTypes(ToType);
2764 return OR_Success;
2765 } else if (CXXConversionDecl *Conversion
2766 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002767 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2768
John McCall5c32be02010-08-24 20:38:10 +00002769 // C++ [over.ics.user]p1:
2770 //
2771 // [...] If the user-defined conversion is specified by a
2772 // conversion function (12.3.2), the initial standard
2773 // conversion sequence converts the source type to the
2774 // implicit object parameter of the conversion function.
2775 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002776 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002777 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002778 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002779 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002780
John McCall5c32be02010-08-24 20:38:10 +00002781 // C++ [over.ics.user]p2:
2782 // The second standard conversion sequence converts the
2783 // result of the user-defined conversion to the target type
2784 // for the sequence. Since an implicit conversion sequence
2785 // is an initialization, the special rules for
2786 // initialization by user-defined conversion apply when
2787 // selecting the best user-defined conversion for a
2788 // user-defined conversion sequence (see 13.3.3 and
2789 // 13.3.3.1).
2790 User.After = Best->FinalConversion;
2791 return OR_Success;
2792 } else {
2793 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002794 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002795 }
2796
John McCall5c32be02010-08-24 20:38:10 +00002797 case OR_No_Viable_Function:
2798 return OR_No_Viable_Function;
2799 case OR_Deleted:
2800 // No conversion here! We're done.
2801 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002802
John McCall5c32be02010-08-24 20:38:10 +00002803 case OR_Ambiguous:
2804 return OR_Ambiguous;
2805 }
2806
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002807 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002808}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002809
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002810bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002811Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002812 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002813 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002815 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002816 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002817 if (OvResult == OR_Ambiguous)
2818 Diag(From->getSourceRange().getBegin(),
2819 diag::err_typecheck_ambiguous_condition)
2820 << From->getType() << ToType << From->getSourceRange();
2821 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2822 Diag(From->getSourceRange().getBegin(),
2823 diag::err_typecheck_nonviable_condition)
2824 << From->getType() << ToType << From->getSourceRange();
2825 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002826 return false;
John McCall5c32be02010-08-24 20:38:10 +00002827 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002828 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002829}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002830
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002831/// CompareImplicitConversionSequences - Compare two implicit
2832/// conversion sequences to determine whether one is better than the
2833/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002834static ImplicitConversionSequence::CompareKind
2835CompareImplicitConversionSequences(Sema &S,
2836 const ImplicitConversionSequence& ICS1,
2837 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002838{
2839 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2840 // conversion sequences (as defined in 13.3.3.1)
2841 // -- a standard conversion sequence (13.3.3.1.1) is a better
2842 // conversion sequence than a user-defined conversion sequence or
2843 // an ellipsis conversion sequence, and
2844 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2845 // conversion sequence than an ellipsis conversion sequence
2846 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002847 //
John McCall0d1da222010-01-12 00:44:57 +00002848 // C++0x [over.best.ics]p10:
2849 // For the purpose of ranking implicit conversion sequences as
2850 // described in 13.3.3.2, the ambiguous conversion sequence is
2851 // treated as a user-defined sequence that is indistinguishable
2852 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002853 if (ICS1.getKindRank() < ICS2.getKindRank())
2854 return ImplicitConversionSequence::Better;
2855 else if (ICS2.getKindRank() < ICS1.getKindRank())
2856 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002857
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002858 // The following checks require both conversion sequences to be of
2859 // the same kind.
2860 if (ICS1.getKind() != ICS2.getKind())
2861 return ImplicitConversionSequence::Indistinguishable;
2862
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002863 ImplicitConversionSequence::CompareKind Result =
2864 ImplicitConversionSequence::Indistinguishable;
2865
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002866 // Two implicit conversion sequences of the same form are
2867 // indistinguishable conversion sequences unless one of the
2868 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002869 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002870 Result = CompareStandardConversionSequences(S,
2871 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002872 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002873 // User-defined conversion sequence U1 is a better conversion
2874 // sequence than another user-defined conversion sequence U2 if
2875 // they contain the same user-defined conversion function or
2876 // constructor and if the second standard conversion sequence of
2877 // U1 is better than the second standard conversion sequence of
2878 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002879 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002880 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002881 Result = CompareStandardConversionSequences(S,
2882 ICS1.UserDefined.After,
2883 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002884 }
2885
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002886 // List-initialization sequence L1 is a better conversion sequence than
2887 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2888 // for some X and L2 does not.
2889 if (Result == ImplicitConversionSequence::Indistinguishable &&
2890 ICS1.isListInitializationSequence() &&
2891 ICS2.isListInitializationSequence()) {
2892 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2893 }
2894
2895 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002896}
2897
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002898static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2899 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2900 Qualifiers Quals;
2901 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002904
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002905 return Context.hasSameUnqualifiedType(T1, T2);
2906}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002907
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002908// Per 13.3.3.2p3, compare the given standard conversion sequences to
2909// determine if one is a proper subset of the other.
2910static ImplicitConversionSequence::CompareKind
2911compareStandardConversionSubsets(ASTContext &Context,
2912 const StandardConversionSequence& SCS1,
2913 const StandardConversionSequence& SCS2) {
2914 ImplicitConversionSequence::CompareKind Result
2915 = ImplicitConversionSequence::Indistinguishable;
2916
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002917 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002918 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002919 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2920 return ImplicitConversionSequence::Better;
2921 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2922 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002923
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002924 if (SCS1.Second != SCS2.Second) {
2925 if (SCS1.Second == ICK_Identity)
2926 Result = ImplicitConversionSequence::Better;
2927 else if (SCS2.Second == ICK_Identity)
2928 Result = ImplicitConversionSequence::Worse;
2929 else
2930 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002931 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002932 return ImplicitConversionSequence::Indistinguishable;
2933
2934 if (SCS1.Third == SCS2.Third) {
2935 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2936 : ImplicitConversionSequence::Indistinguishable;
2937 }
2938
2939 if (SCS1.Third == ICK_Identity)
2940 return Result == ImplicitConversionSequence::Worse
2941 ? ImplicitConversionSequence::Indistinguishable
2942 : ImplicitConversionSequence::Better;
2943
2944 if (SCS2.Third == ICK_Identity)
2945 return Result == ImplicitConversionSequence::Better
2946 ? ImplicitConversionSequence::Indistinguishable
2947 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002948
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002949 return ImplicitConversionSequence::Indistinguishable;
2950}
2951
Douglas Gregore696ebb2011-01-26 14:52:12 +00002952/// \brief Determine whether one of the given reference bindings is better
2953/// than the other based on what kind of bindings they are.
2954static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2955 const StandardConversionSequence &SCS2) {
2956 // C++0x [over.ics.rank]p3b4:
2957 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2958 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002959 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002960 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002961 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002962 // reference*.
2963 //
2964 // FIXME: Rvalue references. We're going rogue with the above edits,
2965 // because the semantics in the current C++0x working paper (N3225 at the
2966 // time of this writing) break the standard definition of std::forward
2967 // and std::reference_wrapper when dealing with references to functions.
2968 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002969 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2970 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2971 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002972
Douglas Gregore696ebb2011-01-26 14:52:12 +00002973 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2974 SCS2.IsLvalueReference) ||
2975 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2976 !SCS2.IsLvalueReference);
2977}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002978
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002979/// CompareStandardConversionSequences - Compare two standard
2980/// conversion sequences to determine whether one is better than the
2981/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002982static ImplicitConversionSequence::CompareKind
2983CompareStandardConversionSequences(Sema &S,
2984 const StandardConversionSequence& SCS1,
2985 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002986{
2987 // Standard conversion sequence S1 is a better conversion sequence
2988 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2989
2990 // -- S1 is a proper subsequence of S2 (comparing the conversion
2991 // sequences in the canonical form defined by 13.3.3.1.1,
2992 // excluding any Lvalue Transformation; the identity conversion
2993 // sequence is considered to be a subsequence of any
2994 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002995 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002996 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002997 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002998
2999 // -- the rank of S1 is better than the rank of S2 (by the rules
3000 // defined below), or, if not that,
3001 ImplicitConversionRank Rank1 = SCS1.getRank();
3002 ImplicitConversionRank Rank2 = SCS2.getRank();
3003 if (Rank1 < Rank2)
3004 return ImplicitConversionSequence::Better;
3005 else if (Rank2 < Rank1)
3006 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003007
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003008 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3009 // are indistinguishable unless one of the following rules
3010 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003011
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003012 // A conversion that is not a conversion of a pointer, or
3013 // pointer to member, to bool is better than another conversion
3014 // that is such a conversion.
3015 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3016 return SCS2.isPointerConversionToBool()
3017 ? ImplicitConversionSequence::Better
3018 : ImplicitConversionSequence::Worse;
3019
Douglas Gregor5c407d92008-10-23 00:40:37 +00003020 // C++ [over.ics.rank]p4b2:
3021 //
3022 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003023 // conversion of B* to A* is better than conversion of B* to
3024 // void*, and conversion of A* to void* is better than conversion
3025 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003026 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003027 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003028 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003029 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003030 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3031 // Exactly one of the conversion sequences is a conversion to
3032 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003033 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3034 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003035 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3036 // Neither conversion sequence converts to a void pointer; compare
3037 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003038 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003039 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003040 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003041 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3042 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003043 // Both conversion sequences are conversions to void
3044 // pointers. Compare the source types to determine if there's an
3045 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003046 QualType FromType1 = SCS1.getFromType();
3047 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003048
3049 // Adjust the types we're converting from via the array-to-pointer
3050 // conversion, if we need to.
3051 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003052 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003053 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003054 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003055
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003056 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3057 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003058
John McCall5c32be02010-08-24 20:38:10 +00003059 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003060 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003061 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003062 return ImplicitConversionSequence::Worse;
3063
3064 // Objective-C++: If one interface is more specific than the
3065 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003066 const ObjCObjectPointerType* FromObjCPtr1
3067 = FromType1->getAs<ObjCObjectPointerType>();
3068 const ObjCObjectPointerType* FromObjCPtr2
3069 = FromType2->getAs<ObjCObjectPointerType>();
3070 if (FromObjCPtr1 && FromObjCPtr2) {
3071 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3072 FromObjCPtr2);
3073 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3074 FromObjCPtr1);
3075 if (AssignLeft != AssignRight) {
3076 return AssignLeft? ImplicitConversionSequence::Better
3077 : ImplicitConversionSequence::Worse;
3078 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003079 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003080 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003081
3082 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3083 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003084 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003085 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003086 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003087
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003088 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003089 // Check for a better reference binding based on the kind of bindings.
3090 if (isBetterReferenceBindingKind(SCS1, SCS2))
3091 return ImplicitConversionSequence::Better;
3092 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3093 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094
Sebastian Redlb28b4072009-03-22 23:49:27 +00003095 // C++ [over.ics.rank]p3b4:
3096 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3097 // which the references refer are the same type except for
3098 // top-level cv-qualifiers, and the type to which the reference
3099 // initialized by S2 refers is more cv-qualified than the type
3100 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003101 QualType T1 = SCS1.getToType(2);
3102 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003103 T1 = S.Context.getCanonicalType(T1);
3104 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003105 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003106 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3107 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003108 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003109 // Objective-C++ ARC: If the references refer to objects with different
3110 // lifetimes, prefer bindings that don't change lifetime.
3111 if (SCS1.ObjCLifetimeConversionBinding !=
3112 SCS2.ObjCLifetimeConversionBinding) {
3113 return SCS1.ObjCLifetimeConversionBinding
3114 ? ImplicitConversionSequence::Worse
3115 : ImplicitConversionSequence::Better;
3116 }
3117
Chandler Carruth8e543b32010-12-12 08:17:55 +00003118 // If the type is an array type, promote the element qualifiers to the
3119 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003120 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003121 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003122 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003123 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003124 if (T2.isMoreQualifiedThan(T1))
3125 return ImplicitConversionSequence::Better;
3126 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003127 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003128 }
3129 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003130
Francois Pichet08d2fa02011-09-18 21:37:37 +00003131 // In Microsoft mode, prefer an integral conversion to a
3132 // floating-to-integral conversion if the integral conversion
3133 // is between types of the same size.
3134 // For example:
3135 // void f(float);
3136 // void f(int);
3137 // int main {
3138 // long a;
3139 // f(a);
3140 // }
3141 // Here, MSVC will call f(int) instead of generating a compile error
3142 // as clang will do in standard mode.
3143 if (S.getLangOptions().MicrosoftMode &&
3144 SCS1.Second == ICK_Integral_Conversion &&
3145 SCS2.Second == ICK_Floating_Integral &&
3146 S.Context.getTypeSize(SCS1.getFromType()) ==
3147 S.Context.getTypeSize(SCS1.getToType(2)))
3148 return ImplicitConversionSequence::Better;
3149
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003150 return ImplicitConversionSequence::Indistinguishable;
3151}
3152
3153/// CompareQualificationConversions - Compares two standard conversion
3154/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003155/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3156ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003157CompareQualificationConversions(Sema &S,
3158 const StandardConversionSequence& SCS1,
3159 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003160 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003161 // -- S1 and S2 differ only in their qualification conversion and
3162 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3163 // cv-qualification signature of type T1 is a proper subset of
3164 // the cv-qualification signature of type T2, and S1 is not the
3165 // deprecated string literal array-to-pointer conversion (4.2).
3166 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3167 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3168 return ImplicitConversionSequence::Indistinguishable;
3169
3170 // FIXME: the example in the standard doesn't use a qualification
3171 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003172 QualType T1 = SCS1.getToType(2);
3173 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003174 T1 = S.Context.getCanonicalType(T1);
3175 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003176 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003177 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3178 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003179
3180 // If the types are the same, we won't learn anything by unwrapped
3181 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003182 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003183 return ImplicitConversionSequence::Indistinguishable;
3184
Chandler Carruth607f38e2009-12-29 07:16:59 +00003185 // If the type is an array type, promote the element qualifiers to the type
3186 // for comparison.
3187 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003188 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003189 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003190 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003191
Mike Stump11289f42009-09-09 15:08:12 +00003192 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003193 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003194
3195 // Objective-C++ ARC:
3196 // Prefer qualification conversions not involving a change in lifetime
3197 // to qualification conversions that do not change lifetime.
3198 if (SCS1.QualificationIncludesObjCLifetime !=
3199 SCS2.QualificationIncludesObjCLifetime) {
3200 Result = SCS1.QualificationIncludesObjCLifetime
3201 ? ImplicitConversionSequence::Worse
3202 : ImplicitConversionSequence::Better;
3203 }
3204
John McCall5c32be02010-08-24 20:38:10 +00003205 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003206 // Within each iteration of the loop, we check the qualifiers to
3207 // determine if this still looks like a qualification
3208 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003209 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003210 // until there are no more pointers or pointers-to-members left
3211 // to unwrap. This essentially mimics what
3212 // IsQualificationConversion does, but here we're checking for a
3213 // strict subset of qualifiers.
3214 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3215 // The qualifiers are the same, so this doesn't tell us anything
3216 // about how the sequences rank.
3217 ;
3218 else if (T2.isMoreQualifiedThan(T1)) {
3219 // T1 has fewer qualifiers, so it could be the better sequence.
3220 if (Result == ImplicitConversionSequence::Worse)
3221 // Neither has qualifiers that are a subset of the other's
3222 // qualifiers.
3223 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003224
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003225 Result = ImplicitConversionSequence::Better;
3226 } else if (T1.isMoreQualifiedThan(T2)) {
3227 // T2 has fewer qualifiers, so it could be the better sequence.
3228 if (Result == ImplicitConversionSequence::Better)
3229 // Neither has qualifiers that are a subset of the other's
3230 // qualifiers.
3231 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003232
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003233 Result = ImplicitConversionSequence::Worse;
3234 } else {
3235 // Qualifiers are disjoint.
3236 return ImplicitConversionSequence::Indistinguishable;
3237 }
3238
3239 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003240 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003241 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003242 }
3243
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003244 // Check that the winning standard conversion sequence isn't using
3245 // the deprecated string literal array to pointer conversion.
3246 switch (Result) {
3247 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003248 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003249 Result = ImplicitConversionSequence::Indistinguishable;
3250 break;
3251
3252 case ImplicitConversionSequence::Indistinguishable:
3253 break;
3254
3255 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003256 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003257 Result = ImplicitConversionSequence::Indistinguishable;
3258 break;
3259 }
3260
3261 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003262}
3263
Douglas Gregor5c407d92008-10-23 00:40:37 +00003264/// CompareDerivedToBaseConversions - Compares two standard conversion
3265/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003266/// various kinds of derived-to-base conversions (C++
3267/// [over.ics.rank]p4b3). As part of these checks, we also look at
3268/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003269ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003270CompareDerivedToBaseConversions(Sema &S,
3271 const StandardConversionSequence& SCS1,
3272 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003273 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003274 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003275 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003276 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003277
3278 // Adjust the types we're converting from via the array-to-pointer
3279 // conversion, if we need to.
3280 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003281 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003282 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003283 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003284
3285 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003286 FromType1 = S.Context.getCanonicalType(FromType1);
3287 ToType1 = S.Context.getCanonicalType(ToType1);
3288 FromType2 = S.Context.getCanonicalType(FromType2);
3289 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003290
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003291 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003292 //
3293 // If class B is derived directly or indirectly from class A and
3294 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003295 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003296 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003297 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003298 SCS2.Second == ICK_Pointer_Conversion &&
3299 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3300 FromType1->isPointerType() && FromType2->isPointerType() &&
3301 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003302 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003303 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003304 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003305 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003306 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003307 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003308 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003309 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003310
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003311 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003312 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003313 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003314 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003315 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003316 return ImplicitConversionSequence::Worse;
3317 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003318
3319 // -- conversion of B* to A* is better than conversion of C* to A*,
3320 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003321 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003322 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003323 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003324 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003325 }
3326 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3327 SCS2.Second == ICK_Pointer_Conversion) {
3328 const ObjCObjectPointerType *FromPtr1
3329 = FromType1->getAs<ObjCObjectPointerType>();
3330 const ObjCObjectPointerType *FromPtr2
3331 = FromType2->getAs<ObjCObjectPointerType>();
3332 const ObjCObjectPointerType *ToPtr1
3333 = ToType1->getAs<ObjCObjectPointerType>();
3334 const ObjCObjectPointerType *ToPtr2
3335 = ToType2->getAs<ObjCObjectPointerType>();
3336
3337 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3338 // Apply the same conversion ranking rules for Objective-C pointer types
3339 // that we do for C++ pointers to class types. However, we employ the
3340 // Objective-C pseudo-subtyping relationship used for assignment of
3341 // Objective-C pointer types.
3342 bool FromAssignLeft
3343 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3344 bool FromAssignRight
3345 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3346 bool ToAssignLeft
3347 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3348 bool ToAssignRight
3349 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3350
3351 // A conversion to an a non-id object pointer type or qualified 'id'
3352 // type is better than a conversion to 'id'.
3353 if (ToPtr1->isObjCIdType() &&
3354 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3355 return ImplicitConversionSequence::Worse;
3356 if (ToPtr2->isObjCIdType() &&
3357 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3358 return ImplicitConversionSequence::Better;
3359
3360 // A conversion to a non-id object pointer type is better than a
3361 // conversion to a qualified 'id' type
3362 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3363 return ImplicitConversionSequence::Worse;
3364 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3365 return ImplicitConversionSequence::Better;
3366
3367 // A conversion to an a non-Class object pointer type or qualified 'Class'
3368 // type is better than a conversion to 'Class'.
3369 if (ToPtr1->isObjCClassType() &&
3370 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3371 return ImplicitConversionSequence::Worse;
3372 if (ToPtr2->isObjCClassType() &&
3373 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3374 return ImplicitConversionSequence::Better;
3375
3376 // A conversion to a non-Class object pointer type is better than a
3377 // conversion to a qualified 'Class' type.
3378 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3379 return ImplicitConversionSequence::Worse;
3380 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3381 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003382
Douglas Gregor058d3de2011-01-31 18:51:41 +00003383 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3384 if (S.Context.hasSameType(FromType1, FromType2) &&
3385 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3386 (ToAssignLeft != ToAssignRight))
3387 return ToAssignLeft? ImplicitConversionSequence::Worse
3388 : ImplicitConversionSequence::Better;
3389
3390 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3391 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3392 (FromAssignLeft != FromAssignRight))
3393 return FromAssignLeft? ImplicitConversionSequence::Better
3394 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003395 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003396 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003397
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003398 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003399 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3400 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3401 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003403 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003404 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003405 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003407 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003409 ToType2->getAs<MemberPointerType>();
3410 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3411 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3412 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3413 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3414 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3415 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3416 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3417 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003418 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003419 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003420 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003421 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003422 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003423 return ImplicitConversionSequence::Better;
3424 }
3425 // conversion of B::* to C::* is better than conversion of A::* to C::*
3426 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003427 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003428 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003429 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003430 return ImplicitConversionSequence::Worse;
3431 }
3432 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433
Douglas Gregor5ab11652010-04-17 22:01:05 +00003434 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003435 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003436 // -- binding of an expression of type C to a reference of type
3437 // B& is better than binding an expression of type C to a
3438 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003439 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3440 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3441 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003442 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003443 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003444 return ImplicitConversionSequence::Worse;
3445 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003446
Douglas Gregor2fe98832008-11-03 19:09:14 +00003447 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003448 // -- binding of an expression of type B to a reference of type
3449 // A& is better than binding an expression of type C to a
3450 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003451 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3452 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3453 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003454 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003455 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003456 return ImplicitConversionSequence::Worse;
3457 }
3458 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003459
Douglas Gregor5c407d92008-10-23 00:40:37 +00003460 return ImplicitConversionSequence::Indistinguishable;
3461}
3462
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003463/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3464/// determine whether they are reference-related,
3465/// reference-compatible, reference-compatible with added
3466/// qualification, or incompatible, for use in C++ initialization by
3467/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3468/// type, and the first type (T1) is the pointee type of the reference
3469/// type being initialized.
3470Sema::ReferenceCompareResult
3471Sema::CompareReferenceRelationship(SourceLocation Loc,
3472 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003473 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003474 bool &ObjCConversion,
3475 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003476 assert(!OrigT1->isReferenceType() &&
3477 "T1 must be the pointee type of the reference type");
3478 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3479
3480 QualType T1 = Context.getCanonicalType(OrigT1);
3481 QualType T2 = Context.getCanonicalType(OrigT2);
3482 Qualifiers T1Quals, T2Quals;
3483 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3484 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3485
3486 // C++ [dcl.init.ref]p4:
3487 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3488 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3489 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003490 DerivedToBase = false;
3491 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003492 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003493 if (UnqualT1 == UnqualT2) {
3494 // Nothing to do.
3495 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003496 IsDerivedFrom(UnqualT2, UnqualT1))
3497 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003498 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3499 UnqualT2->isObjCObjectOrInterfaceType() &&
3500 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3501 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003502 else
3503 return Ref_Incompatible;
3504
3505 // At this point, we know that T1 and T2 are reference-related (at
3506 // least).
3507
3508 // If the type is an array type, promote the element qualifiers to the type
3509 // for comparison.
3510 if (isa<ArrayType>(T1) && T1Quals)
3511 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3512 if (isa<ArrayType>(T2) && T2Quals)
3513 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3514
3515 // C++ [dcl.init.ref]p4:
3516 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3517 // reference-related to T2 and cv1 is the same cv-qualification
3518 // as, or greater cv-qualification than, cv2. For purposes of
3519 // overload resolution, cases for which cv1 is greater
3520 // cv-qualification than cv2 are identified as
3521 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003522 //
3523 // Note that we also require equivalence of Objective-C GC and address-space
3524 // qualifiers when performing these computations, so that e.g., an int in
3525 // address space 1 is not reference-compatible with an int in address
3526 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003527 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3528 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3529 T1Quals.removeObjCLifetime();
3530 T2Quals.removeObjCLifetime();
3531 ObjCLifetimeConversion = true;
3532 }
3533
Douglas Gregord517d552011-04-28 17:56:11 +00003534 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003535 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003536 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003537 return Ref_Compatible_With_Added_Qualification;
3538 else
3539 return Ref_Related;
3540}
3541
Douglas Gregor836a7e82010-08-11 02:15:33 +00003542/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003543/// with DeclType. Return true if something definite is found.
3544static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003545FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3546 QualType DeclType, SourceLocation DeclLoc,
3547 Expr *Init, QualType T2, bool AllowRvalues,
3548 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003549 assert(T2->isRecordType() && "Can only find conversions of record types.");
3550 CXXRecordDecl *T2RecordDecl
3551 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3552
3553 OverloadCandidateSet CandidateSet(DeclLoc);
3554 const UnresolvedSetImpl *Conversions
3555 = T2RecordDecl->getVisibleConversionFunctions();
3556 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3557 E = Conversions->end(); I != E; ++I) {
3558 NamedDecl *D = *I;
3559 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3560 if (isa<UsingShadowDecl>(D))
3561 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3562
3563 FunctionTemplateDecl *ConvTemplate
3564 = dyn_cast<FunctionTemplateDecl>(D);
3565 CXXConversionDecl *Conv;
3566 if (ConvTemplate)
3567 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3568 else
3569 Conv = cast<CXXConversionDecl>(D);
3570
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003572 // explicit conversions, skip it.
3573 if (!AllowExplicit && Conv->isExplicit())
3574 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575
Douglas Gregor836a7e82010-08-11 02:15:33 +00003576 if (AllowRvalues) {
3577 bool DerivedToBase = false;
3578 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003579 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003580
3581 // If we are initializing an rvalue reference, don't permit conversion
3582 // functions that return lvalues.
3583 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3584 const ReferenceType *RefType
3585 = Conv->getConversionType()->getAs<LValueReferenceType>();
3586 if (RefType && !RefType->getPointeeType()->isFunctionType())
3587 continue;
3588 }
3589
Douglas Gregor836a7e82010-08-11 02:15:33 +00003590 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003591 S.CompareReferenceRelationship(
3592 DeclLoc,
3593 Conv->getConversionType().getNonReferenceType()
3594 .getUnqualifiedType(),
3595 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003596 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003597 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003598 continue;
3599 } else {
3600 // If the conversion function doesn't return a reference type,
3601 // it can't be considered for this conversion. An rvalue reference
3602 // is only acceptable if its referencee is a function type.
3603
3604 const ReferenceType *RefType =
3605 Conv->getConversionType()->getAs<ReferenceType>();
3606 if (!RefType ||
3607 (!RefType->isLValueReferenceType() &&
3608 !RefType->getPointeeType()->isFunctionType()))
3609 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003611
Douglas Gregor836a7e82010-08-11 02:15:33 +00003612 if (ConvTemplate)
3613 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003614 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003615 else
3616 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003617 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003618 }
3619
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003620 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3621
Sebastian Redld92badf2010-06-30 18:13:39 +00003622 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003623 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003624 case OR_Success:
3625 // C++ [over.ics.ref]p1:
3626 //
3627 // [...] If the parameter binds directly to the result of
3628 // applying a conversion function to the argument
3629 // expression, the implicit conversion sequence is a
3630 // user-defined conversion sequence (13.3.3.1.2), with the
3631 // second standard conversion sequence either an identity
3632 // conversion or, if the conversion function returns an
3633 // entity of a type that is a derived class of the parameter
3634 // type, a derived-to-base Conversion.
3635 if (!Best->FinalConversion.DirectBinding)
3636 return false;
3637
Chandler Carruth30141632011-02-25 19:41:05 +00003638 if (Best->Function)
3639 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003640 ICS.setUserDefined();
3641 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3642 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003643 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003644 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003645 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003646 ICS.UserDefined.EllipsisConversion = false;
3647 assert(ICS.UserDefined.After.ReferenceBinding &&
3648 ICS.UserDefined.After.DirectBinding &&
3649 "Expected a direct reference binding!");
3650 return true;
3651
3652 case OR_Ambiguous:
3653 ICS.setAmbiguous();
3654 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3655 Cand != CandidateSet.end(); ++Cand)
3656 if (Cand->Viable)
3657 ICS.Ambiguous.addConversion(Cand->Function);
3658 return true;
3659
3660 case OR_No_Viable_Function:
3661 case OR_Deleted:
3662 // There was no suitable conversion, or we found a deleted
3663 // conversion; continue with other checks.
3664 return false;
3665 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003666
Eric Christopheraba9fb22010-06-30 18:36:32 +00003667 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003668}
3669
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003670/// \brief Compute an implicit conversion sequence for reference
3671/// initialization.
3672static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003673TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003674 SourceLocation DeclLoc,
3675 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003676 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003677 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3678
3679 // Most paths end in a failed conversion.
3680 ImplicitConversionSequence ICS;
3681 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3682
3683 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3684 QualType T2 = Init->getType();
3685
3686 // If the initializer is the address of an overloaded function, try
3687 // to resolve the overloaded function. If all goes well, T2 is the
3688 // type of the resulting function.
3689 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3690 DeclAccessPair Found;
3691 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3692 false, Found))
3693 T2 = Fn->getType();
3694 }
3695
3696 // Compute some basic properties of the types and the initializer.
3697 bool isRValRef = DeclType->isRValueReferenceType();
3698 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003699 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003700 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003701 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003702 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003703 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003704 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003705
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003706
Sebastian Redld92badf2010-06-30 18:13:39 +00003707 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003708 // A reference to type "cv1 T1" is initialized by an expression
3709 // of type "cv2 T2" as follows:
3710
Sebastian Redld92badf2010-06-30 18:13:39 +00003711 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003712 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003713 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3714 // reference-compatible with "cv2 T2," or
3715 //
3716 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3717 if (InitCategory.isLValue() &&
3718 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003719 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003720 // When a parameter of reference type binds directly (8.5.3)
3721 // to an argument expression, the implicit conversion sequence
3722 // is the identity conversion, unless the argument expression
3723 // has a type that is a derived class of the parameter type,
3724 // in which case the implicit conversion sequence is a
3725 // derived-to-base Conversion (13.3.3.1).
3726 ICS.setStandard();
3727 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003728 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3729 : ObjCConversion? ICK_Compatible_Conversion
3730 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003731 ICS.Standard.Third = ICK_Identity;
3732 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3733 ICS.Standard.setToType(0, T2);
3734 ICS.Standard.setToType(1, T1);
3735 ICS.Standard.setToType(2, T1);
3736 ICS.Standard.ReferenceBinding = true;
3737 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003738 ICS.Standard.IsLvalueReference = !isRValRef;
3739 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3740 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003741 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003742 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003743 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003744
Sebastian Redld92badf2010-06-30 18:13:39 +00003745 // Nothing more to do: the inaccessibility/ambiguity check for
3746 // derived-to-base conversions is suppressed when we're
3747 // computing the implicit conversion sequence (C++
3748 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003749 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003750 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003751
Sebastian Redld92badf2010-06-30 18:13:39 +00003752 // -- has a class type (i.e., T2 is a class type), where T1 is
3753 // not reference-related to T2, and can be implicitly
3754 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3755 // is reference-compatible with "cv3 T3" 92) (this
3756 // conversion is selected by enumerating the applicable
3757 // conversion functions (13.3.1.6) and choosing the best
3758 // one through overload resolution (13.3)),
3759 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003761 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003762 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3763 Init, T2, /*AllowRvalues=*/false,
3764 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003765 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003766 }
3767 }
3768
Sebastian Redld92badf2010-06-30 18:13:39 +00003769 // -- Otherwise, the reference shall be an lvalue reference to a
3770 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003771 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003773 // We actually handle one oddity of C++ [over.ics.ref] at this
3774 // point, which is that, due to p2 (which short-circuits reference
3775 // binding by only attempting a simple conversion for non-direct
3776 // bindings) and p3's strange wording, we allow a const volatile
3777 // reference to bind to an rvalue. Hence the check for the presence
3778 // of "const" rather than checking for "const" being the only
3779 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003780 // This is also the point where rvalue references and lvalue inits no longer
3781 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003782 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003783 return ICS;
3784
Douglas Gregorf143cd52011-01-24 16:14:37 +00003785 // -- If the initializer expression
3786 //
3787 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003788 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003789 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3790 (InitCategory.isXValue() ||
3791 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3792 (InitCategory.isLValue() && T2->isFunctionType()))) {
3793 ICS.setStandard();
3794 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003796 : ObjCConversion? ICK_Compatible_Conversion
3797 : ICK_Identity;
3798 ICS.Standard.Third = ICK_Identity;
3799 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3800 ICS.Standard.setToType(0, T2);
3801 ICS.Standard.setToType(1, T1);
3802 ICS.Standard.setToType(2, T1);
3803 ICS.Standard.ReferenceBinding = true;
3804 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3805 // binding unless we're binding to a class prvalue.
3806 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3807 // allow the use of rvalue references in C++98/03 for the benefit of
3808 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003809 ICS.Standard.DirectBinding =
3810 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003811 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003812 ICS.Standard.IsLvalueReference = !isRValRef;
3813 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003815 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003816 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003817 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003818 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Douglas Gregorf143cd52011-01-24 16:14:37 +00003821 // -- has a class type (i.e., T2 is a class type), where T1 is not
3822 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823 // an xvalue, class prvalue, or function lvalue of type
3824 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003825 // "cv3 T3",
3826 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003827 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003828 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003829 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003830 // class subobject).
3831 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003832 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003833 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3834 Init, T2, /*AllowRvalues=*/true,
3835 AllowExplicit)) {
3836 // In the second case, if the reference is an rvalue reference
3837 // and the second standard conversion sequence of the
3838 // user-defined conversion sequence includes an lvalue-to-rvalue
3839 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003840 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003841 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3842 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3843
Douglas Gregor95273c32011-01-21 16:36:05 +00003844 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003846
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003847 // -- Otherwise, a temporary of type "cv1 T1" is created and
3848 // initialized from the initializer expression using the
3849 // rules for a non-reference copy initialization (8.5). The
3850 // reference is then bound to the temporary. If T1 is
3851 // reference-related to T2, cv1 must be the same
3852 // cv-qualification as, or greater cv-qualification than,
3853 // cv2; otherwise, the program is ill-formed.
3854 if (RefRelationship == Sema::Ref_Related) {
3855 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3856 // we would be reference-compatible or reference-compatible with
3857 // added qualification. But that wasn't the case, so the reference
3858 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003859 //
3860 // Note that we only want to check address spaces and cvr-qualifiers here.
3861 // ObjC GC and lifetime qualifiers aren't important.
3862 Qualifiers T1Quals = T1.getQualifiers();
3863 Qualifiers T2Quals = T2.getQualifiers();
3864 T1Quals.removeObjCGCAttr();
3865 T1Quals.removeObjCLifetime();
3866 T2Quals.removeObjCGCAttr();
3867 T2Quals.removeObjCLifetime();
3868 if (!T1Quals.compatiblyIncludes(T2Quals))
3869 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003870 }
3871
3872 // If at least one of the types is a class type, the types are not
3873 // related, and we aren't allowed any user conversions, the
3874 // reference binding fails. This case is important for breaking
3875 // recursion, since TryImplicitConversion below will attempt to
3876 // create a temporary through the use of a copy constructor.
3877 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3878 (T1->isRecordType() || T2->isRecordType()))
3879 return ICS;
3880
Douglas Gregorcba72b12011-01-21 05:18:22 +00003881 // If T1 is reference-related to T2 and the reference is an rvalue
3882 // reference, the initializer expression shall not be an lvalue.
3883 if (RefRelationship >= Sema::Ref_Related &&
3884 isRValRef && Init->Classify(S.Context).isLValue())
3885 return ICS;
3886
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003887 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003888 // When a parameter of reference type is not bound directly to
3889 // an argument expression, the conversion sequence is the one
3890 // required to convert the argument expression to the
3891 // underlying type of the reference according to
3892 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3893 // to copy-initializing a temporary of the underlying type with
3894 // the argument expression. Any difference in top-level
3895 // cv-qualification is subsumed by the initialization itself
3896 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003897 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3898 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003899 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003900 /*CStyle=*/false,
3901 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003902
3903 // Of course, that's still a reference binding.
3904 if (ICS.isStandard()) {
3905 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003906 ICS.Standard.IsLvalueReference = !isRValRef;
3907 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3908 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003909 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003910 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003911 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003912 // Don't allow rvalue references to bind to lvalues.
3913 if (DeclType->isRValueReferenceType()) {
3914 if (const ReferenceType *RefType
3915 = ICS.UserDefined.ConversionFunction->getResultType()
3916 ->getAs<LValueReferenceType>()) {
3917 if (!RefType->getPointeeType()->isFunctionType()) {
3918 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3919 DeclType);
3920 return ICS;
3921 }
3922 }
3923 }
3924
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003925 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003926 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3927 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3928 ICS.UserDefined.After.BindsToRvalue = true;
3929 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3930 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003931 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003932
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003933 return ICS;
3934}
3935
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003936static ImplicitConversionSequence
3937TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3938 bool SuppressUserConversions,
3939 bool InOverloadResolution,
3940 bool AllowObjCWritebackConversion);
3941
3942/// TryListConversion - Try to copy-initialize a value of type ToType from the
3943/// initializer list From.
3944static ImplicitConversionSequence
3945TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3946 bool SuppressUserConversions,
3947 bool InOverloadResolution,
3948 bool AllowObjCWritebackConversion) {
3949 // C++11 [over.ics.list]p1:
3950 // When an argument is an initializer list, it is not an expression and
3951 // special rules apply for converting it to a parameter type.
3952
3953 ImplicitConversionSequence Result;
3954 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003955 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003956
3957 // C++11 [over.ics.list]p2:
3958 // If the parameter type is std::initializer_list<X> or "array of X" and
3959 // all the elements can be implicitly converted to X, the implicit
3960 // conversion sequence is the worst conversion necessary to convert an
3961 // element of the list to X.
3962 // FIXME: Recognize std::initializer_list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003963 // FIXME: Implement arrays.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003964 if (ToType->isArrayType())
3965 return Result;
3966
3967 // C++11 [over.ics.list]p3:
3968 // Otherwise, if the parameter is a non-aggregate class X and overload
3969 // resolution chooses a single best constructor [...] the implicit
3970 // conversion sequence is a user-defined conversion sequence. If multiple
3971 // constructors are viable but none is better than the others, the
3972 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003973 if (ToType->isRecordType() && !ToType->isAggregateType()) {
3974 // This function can deal with initializer lists.
3975 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
3976 /*AllowExplicit=*/false,
3977 InOverloadResolution, /*CStyle=*/false,
3978 AllowObjCWritebackConversion);
3979 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003980 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003981 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003982
3983 // C++11 [over.ics.list]p4:
3984 // Otherwise, if the parameter has an aggregate type which can be
3985 // initialized from the initializer list [...] the implicit conversion
3986 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003987 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003988 // Type is an aggregate, argument is an init list. At this point it comes
3989 // down to checking whether the initialization works.
3990 // FIXME: Find out whether this parameter is consumed or not.
3991 InitializedEntity Entity =
3992 InitializedEntity::InitializeParameter(S.Context, ToType,
3993 /*Consumed=*/false);
3994 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3995 Result.setUserDefined();
3996 Result.UserDefined.Before.setAsIdentityConversion();
3997 // Initializer lists don't have a type.
3998 Result.UserDefined.Before.setFromType(QualType());
3999 Result.UserDefined.Before.setAllToTypes(QualType());
4000
4001 Result.UserDefined.After.setAsIdentityConversion();
4002 Result.UserDefined.After.setFromType(ToType);
4003 Result.UserDefined.After.setAllToTypes(ToType);
4004 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004005 return Result;
4006 }
4007
4008 // C++11 [over.ics.list]p5:
4009 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004010 if (ToType->isReferenceType()) {
4011 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4012 // mention initializer lists in any way. So we go by what list-
4013 // initialization would do and try to extrapolate from that.
4014
4015 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4016
4017 // If the initializer list has a single element that is reference-related
4018 // to the parameter type, we initialize the reference from that.
4019 if (From->getNumInits() == 1) {
4020 Expr *Init = From->getInit(0);
4021
4022 QualType T2 = Init->getType();
4023
4024 // If the initializer is the address of an overloaded function, try
4025 // to resolve the overloaded function. If all goes well, T2 is the
4026 // type of the resulting function.
4027 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4028 DeclAccessPair Found;
4029 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4030 Init, ToType, false, Found))
4031 T2 = Fn->getType();
4032 }
4033
4034 // Compute some basic properties of the types and the initializer.
4035 bool dummy1 = false;
4036 bool dummy2 = false;
4037 bool dummy3 = false;
4038 Sema::ReferenceCompareResult RefRelationship
4039 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4040 dummy2, dummy3);
4041
4042 if (RefRelationship >= Sema::Ref_Related)
4043 return TryReferenceInit(S, Init, ToType,
4044 /*FIXME:*/From->getLocStart(),
4045 SuppressUserConversions,
4046 /*AllowExplicit=*/false);
4047 }
4048
4049 // Otherwise, we bind the reference to a temporary created from the
4050 // initializer list.
4051 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4052 InOverloadResolution,
4053 AllowObjCWritebackConversion);
4054 if (Result.isFailure())
4055 return Result;
4056 assert(!Result.isEllipsis() &&
4057 "Sub-initialization cannot result in ellipsis conversion.");
4058
4059 // Can we even bind to a temporary?
4060 if (ToType->isRValueReferenceType() ||
4061 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4062 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4063 Result.UserDefined.After;
4064 SCS.ReferenceBinding = true;
4065 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4066 SCS.BindsToRvalue = true;
4067 SCS.BindsToFunctionLvalue = false;
4068 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4069 SCS.ObjCLifetimeConversionBinding = false;
4070 } else
4071 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4072 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004073 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004074 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004075
4076 // C++11 [over.ics.list]p6:
4077 // Otherwise, if the parameter type is not a class:
4078 if (!ToType->isRecordType()) {
4079 // - if the initializer list has one element, the implicit conversion
4080 // sequence is the one required to convert the element to the
4081 // parameter type.
4082 // FIXME: Catch narrowing here?
4083 unsigned NumInits = From->getNumInits();
4084 if (NumInits == 1)
4085 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4086 SuppressUserConversions,
4087 InOverloadResolution,
4088 AllowObjCWritebackConversion);
4089 // - if the initializer list has no elements, the implicit conversion
4090 // sequence is the identity conversion.
4091 else if (NumInits == 0) {
4092 Result.setStandard();
4093 Result.Standard.setAsIdentityConversion();
4094 }
4095 return Result;
4096 }
4097
4098 // C++11 [over.ics.list]p7:
4099 // In all cases other than those enumerated above, no conversion is possible
4100 return Result;
4101}
4102
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004103/// TryCopyInitialization - Try to copy-initialize a value of type
4104/// ToType from the expression From. Return the implicit conversion
4105/// sequence required to pass this argument, which may be a bad
4106/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004107/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004108/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004109static ImplicitConversionSequence
4110TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004112 bool InOverloadResolution,
4113 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004114 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4115 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4116 InOverloadResolution,AllowObjCWritebackConversion);
4117
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004118 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004119 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004120 /*FIXME:*/From->getLocStart(),
4121 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004122 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004123
John McCall5c32be02010-08-24 20:38:10 +00004124 return TryImplicitConversion(S, From, ToType,
4125 SuppressUserConversions,
4126 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004127 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004128 /*CStyle=*/false,
4129 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004130}
4131
Anna Zaks1b068122011-07-28 19:46:48 +00004132static bool TryCopyInitialization(const CanQualType FromQTy,
4133 const CanQualType ToQTy,
4134 Sema &S,
4135 SourceLocation Loc,
4136 ExprValueKind FromVK) {
4137 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4138 ImplicitConversionSequence ICS =
4139 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4140
4141 return !ICS.isBad();
4142}
4143
Douglas Gregor436424c2008-11-18 23:14:02 +00004144/// TryObjectArgumentInitialization - Try to initialize the object
4145/// parameter of the given member function (@c Method) from the
4146/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004147static ImplicitConversionSequence
4148TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004149 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004150 CXXMethodDecl *Method,
4151 CXXRecordDecl *ActingContext) {
4152 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004153 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4154 // const volatile object.
4155 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4156 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004157 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004158
4159 // Set up the conversion sequence as a "bad" conversion, to allow us
4160 // to exit early.
4161 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004162
4163 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004164 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004165 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004166 FromType = PT->getPointeeType();
4167
Douglas Gregor02824322011-01-26 19:30:28 +00004168 // When we had a pointer, it's implicitly dereferenced, so we
4169 // better have an lvalue.
4170 assert(FromClassification.isLValue());
4171 }
4172
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004173 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004174
Douglas Gregor02824322011-01-26 19:30:28 +00004175 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004177 // parameter is
4178 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004179 // - "lvalue reference to cv X" for functions declared without a
4180 // ref-qualifier or with the & ref-qualifier
4181 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004182 // ref-qualifier
4183 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004185 // cv-qualification on the member function declaration.
4186 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004187 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004188 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004189 // (C++ [over.match.funcs]p5). We perform a simplified version of
4190 // reference binding here, that allows class rvalues to bind to
4191 // non-constant references.
4192
Douglas Gregor02824322011-01-26 19:30:28 +00004193 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004194 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004195 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004196 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004197 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004198 ICS.setBad(BadConversionSequence::bad_qualifiers,
4199 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004200 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004201 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004202
4203 // Check that we have either the same type or a derived type. It
4204 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004205 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004206 ImplicitConversionKind SecondKind;
4207 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4208 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004209 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004210 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004211 else {
John McCall65eb8792010-02-25 01:37:24 +00004212 ICS.setBad(BadConversionSequence::unrelated_class,
4213 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004214 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004215 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004216
Douglas Gregor02824322011-01-26 19:30:28 +00004217 // Check the ref-qualifier.
4218 switch (Method->getRefQualifier()) {
4219 case RQ_None:
4220 // Do nothing; we don't care about lvalueness or rvalueness.
4221 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222
Douglas Gregor02824322011-01-26 19:30:28 +00004223 case RQ_LValue:
4224 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4225 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004227 ImplicitParamType);
4228 return ICS;
4229 }
4230 break;
4231
4232 case RQ_RValue:
4233 if (!FromClassification.isRValue()) {
4234 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004236 ImplicitParamType);
4237 return ICS;
4238 }
4239 break;
4240 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004241
Douglas Gregor436424c2008-11-18 23:14:02 +00004242 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004243 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004244 ICS.Standard.setAsIdentityConversion();
4245 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004246 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004247 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004248 ICS.Standard.ReferenceBinding = true;
4249 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004250 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004251 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004252 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4253 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4254 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004255 return ICS;
4256}
4257
4258/// PerformObjectArgumentInitialization - Perform initialization of
4259/// the implicit object parameter for the given Method with the given
4260/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004261ExprResult
4262Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004263 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004264 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004265 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004266 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004267 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004268 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004269
Douglas Gregor02824322011-01-26 19:30:28 +00004270 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004271 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004272 FromRecordType = PT->getPointeeType();
4273 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004274 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004275 } else {
4276 FromRecordType = From->getType();
4277 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004278 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004279 }
4280
John McCall6e9f8f62009-12-03 04:06:58 +00004281 // Note that we always use the true parent context when performing
4282 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004283 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004284 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4285 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004286 if (ICS.isBad()) {
4287 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4288 Qualifiers FromQs = FromRecordType.getQualifiers();
4289 Qualifiers ToQs = DestType.getQualifiers();
4290 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4291 if (CVR) {
4292 Diag(From->getSourceRange().getBegin(),
4293 diag::err_member_function_call_bad_cvr)
4294 << Method->getDeclName() << FromRecordType << (CVR - 1)
4295 << From->getSourceRange();
4296 Diag(Method->getLocation(), diag::note_previous_decl)
4297 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004298 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004299 }
4300 }
4301
Douglas Gregor436424c2008-11-18 23:14:02 +00004302 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004303 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004304 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004305 }
Mike Stump11289f42009-09-09 15:08:12 +00004306
John Wiegley01296292011-04-08 18:41:53 +00004307 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4308 ExprResult FromRes =
4309 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4310 if (FromRes.isInvalid())
4311 return ExprError();
4312 From = FromRes.take();
4313 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004314
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004315 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004316 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004317 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004318 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004319}
4320
Douglas Gregor5fb53972009-01-14 15:45:31 +00004321/// TryContextuallyConvertToBool - Attempt to contextually convert the
4322/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004323static ImplicitConversionSequence
4324TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004325 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004326 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004327 // FIXME: Are these flags correct?
4328 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004329 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004330 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004331 /*CStyle=*/false,
4332 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004333}
4334
4335/// PerformContextuallyConvertToBool - Perform a contextual conversion
4336/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004337ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004338 if (checkPlaceholderForOverload(*this, From))
4339 return ExprError();
4340
John McCall5c32be02010-08-24 20:38:10 +00004341 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004342 if (!ICS.isBad())
4343 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Fariborz Jahanian76197412009-11-18 18:26:29 +00004345 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004346 return Diag(From->getSourceRange().getBegin(),
4347 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004348 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004349 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004350}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351
John McCallfec112d2011-09-09 06:11:02 +00004352/// dropPointerConversions - If the given standard conversion sequence
4353/// involves any pointer conversions, remove them. This may change
4354/// the result type of the conversion sequence.
4355static void dropPointerConversion(StandardConversionSequence &SCS) {
4356 if (SCS.Second == ICK_Pointer_Conversion) {
4357 SCS.Second = ICK_Identity;
4358 SCS.Third = ICK_Identity;
4359 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4360 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004361}
John McCall5c32be02010-08-24 20:38:10 +00004362
John McCallfec112d2011-09-09 06:11:02 +00004363/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4364/// convert the expression From to an Objective-C pointer type.
4365static ImplicitConversionSequence
4366TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4367 // Do an implicit conversion to 'id'.
4368 QualType Ty = S.Context.getObjCIdType();
4369 ImplicitConversionSequence ICS
4370 = TryImplicitConversion(S, From, Ty,
4371 // FIXME: Are these flags correct?
4372 /*SuppressUserConversions=*/false,
4373 /*AllowExplicit=*/true,
4374 /*InOverloadResolution=*/false,
4375 /*CStyle=*/false,
4376 /*AllowObjCWritebackConversion=*/false);
4377
4378 // Strip off any final conversions to 'id'.
4379 switch (ICS.getKind()) {
4380 case ImplicitConversionSequence::BadConversion:
4381 case ImplicitConversionSequence::AmbiguousConversion:
4382 case ImplicitConversionSequence::EllipsisConversion:
4383 break;
4384
4385 case ImplicitConversionSequence::UserDefinedConversion:
4386 dropPointerConversion(ICS.UserDefined.After);
4387 break;
4388
4389 case ImplicitConversionSequence::StandardConversion:
4390 dropPointerConversion(ICS.Standard);
4391 break;
4392 }
4393
4394 return ICS;
4395}
4396
4397/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4398/// conversion of the expression From to an Objective-C pointer type.
4399ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004400 if (checkPlaceholderForOverload(*this, From))
4401 return ExprError();
4402
John McCall8b07ec22010-05-15 11:32:37 +00004403 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004404 ImplicitConversionSequence ICS =
4405 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004406 if (!ICS.isBad())
4407 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004408 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004409}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004410
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004412/// enumeration type.
4413///
4414/// This routine will attempt to convert an expression of class type to an
4415/// integral or enumeration type, if that class type only has a single
4416/// conversion to an integral or enumeration type.
4417///
Douglas Gregor4799d032010-06-30 00:20:43 +00004418/// \param Loc The source location of the construct that requires the
4419/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004420///
Douglas Gregor4799d032010-06-30 00:20:43 +00004421/// \param FromE The expression we're converting from.
4422///
4423/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4424/// have integral or enumeration type.
4425///
4426/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4427/// incomplete class type.
4428///
4429/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4430/// explicit conversion function (because no implicit conversion functions
4431/// were available). This is a recovery mode.
4432///
4433/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4434/// showing which conversion was picked.
4435///
4436/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4437/// conversion function that could convert to integral or enumeration type.
4438///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004440/// usable conversion function.
4441///
4442/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4443/// function, which may be an extension in this case.
4444///
4445/// \returns The expression, converted to an integral or enumeration type if
4446/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004447ExprResult
John McCallb268a282010-08-23 23:25:46 +00004448Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004449 const PartialDiagnostic &NotIntDiag,
4450 const PartialDiagnostic &IncompleteDiag,
4451 const PartialDiagnostic &ExplicitConvDiag,
4452 const PartialDiagnostic &ExplicitConvNote,
4453 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004454 const PartialDiagnostic &AmbigNote,
4455 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004456 // We can't perform any more checking for type-dependent expressions.
4457 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004458 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004460 // If the expression already has integral or enumeration type, we're golden.
4461 QualType T = From->getType();
4462 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004463 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004464
4465 // FIXME: Check for missing '()' if T is a function type?
4466
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004467 // 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 +00004468 // expression of integral or enumeration type.
4469 const RecordType *RecordTy = T->getAs<RecordType>();
4470 if (!RecordTy || !getLangOptions().CPlusPlus) {
4471 Diag(Loc, NotIntDiag)
4472 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004473 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004476 // We must have a complete class type.
4477 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004478 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004480 // Look for a conversion to an integral or enumeration type.
4481 UnresolvedSet<4> ViableConversions;
4482 UnresolvedSet<4> ExplicitConversions;
4483 const UnresolvedSetImpl *Conversions
4484 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004486 bool HadMultipleCandidates = (Conversions->size() > 1);
4487
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004488 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004489 E = Conversions->end();
4490 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004491 ++I) {
4492 if (CXXConversionDecl *Conversion
4493 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4494 if (Conversion->getConversionType().getNonReferenceType()
4495 ->isIntegralOrEnumerationType()) {
4496 if (Conversion->isExplicit())
4497 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4498 else
4499 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4500 }
4501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004502
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004503 switch (ViableConversions.size()) {
4504 case 0:
4505 if (ExplicitConversions.size() == 1) {
4506 DeclAccessPair Found = ExplicitConversions[0];
4507 CXXConversionDecl *Conversion
4508 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004509
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004510 // The user probably meant to invoke the given explicit
4511 // conversion; use it.
4512 QualType ConvTy
4513 = Conversion->getConversionType().getNonReferenceType();
4514 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004515 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004517 Diag(Loc, ExplicitConvDiag)
4518 << T << ConvTy
4519 << FixItHint::CreateInsertion(From->getLocStart(),
4520 "static_cast<" + TypeStr + ">(")
4521 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4522 ")");
4523 Diag(Conversion->getLocation(), ExplicitConvNote)
4524 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004525
4526 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004527 // explicit conversion function.
4528 if (isSFINAEContext())
4529 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004531 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004532 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4533 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004534 if (Result.isInvalid())
4535 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004536 // Record usage of conversion in an implicit cast.
4537 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4538 CK_UserDefinedConversion,
4539 Result.get(), 0,
4540 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004541 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004543 // We'll complain below about a non-integral condition type.
4544 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004545
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004546 case 1: {
4547 // Apply this conversion.
4548 DeclAccessPair Found = ViableConversions[0];
4549 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550
Douglas Gregor4799d032010-06-30 00:20:43 +00004551 CXXConversionDecl *Conversion
4552 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4553 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004555 if (ConvDiag.getDiagID()) {
4556 if (isSFINAEContext())
4557 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558
Douglas Gregor4799d032010-06-30 00:20:43 +00004559 Diag(Loc, ConvDiag)
4560 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4561 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004562
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004563 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4564 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004565 if (Result.isInvalid())
4566 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004567 // Record usage of conversion in an implicit cast.
4568 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4569 CK_UserDefinedConversion,
4570 Result.get(), 0,
4571 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004572 break;
4573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004575 default:
4576 Diag(Loc, AmbigDiag)
4577 << T << From->getSourceRange();
4578 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4579 CXXConversionDecl *Conv
4580 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4581 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4582 Diag(Conv->getLocation(), AmbigNote)
4583 << ConvTy->isEnumeralType() << ConvTy;
4584 }
John McCallb268a282010-08-23 23:25:46 +00004585 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004586 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004587
Douglas Gregor5823da32010-06-29 23:25:20 +00004588 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004589 Diag(Loc, NotIntDiag)
4590 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004591
John McCallb268a282010-08-23 23:25:46 +00004592 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004593}
4594
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004595/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004596/// candidate functions, using the given function call arguments. If
4597/// @p SuppressUserConversions, then don't allow user-defined
4598/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004599///
4600/// \para PartialOverloading true if we are performing "partial" overloading
4601/// based on an incomplete set of function arguments. This feature is used by
4602/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004603void
4604Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004605 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004606 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004607 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004608 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004609 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004610 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004611 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004612 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004613 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004614 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004615
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004616 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004617 if (!isa<CXXConstructorDecl>(Method)) {
4618 // If we get here, it's because we're calling a member function
4619 // that is named without a member access expression (e.g.,
4620 // "this->f") that was either written explicitly or created
4621 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004622 // function, e.g., X::f(). We use an empty type for the implied
4623 // object argument (C++ [over.call.func]p3), and the acting context
4624 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004625 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004626 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004627 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004628 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004629 return;
4630 }
4631 // We treat a constructor like a non-member function, since its object
4632 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004633 }
4634
Douglas Gregorff7028a2009-11-13 23:59:09 +00004635 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004636 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004637
Douglas Gregor27381f32009-11-23 12:27:39 +00004638 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004639 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004640
Douglas Gregorffe14e32009-11-14 01:20:54 +00004641 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4642 // C++ [class.copy]p3:
4643 // A member function template is never instantiated to perform the copy
4644 // of a class object to an object of its class type.
4645 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004646 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004647 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004648 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4649 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004650 return;
4651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004652
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004653 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004654 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00004655 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004656 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004657 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004658 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004659 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004660 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004661
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004662 unsigned NumArgsInProto = Proto->getNumArgs();
4663
4664 // (C++ 13.3.2p2): A candidate function having fewer than m
4665 // parameters is viable only if it has an ellipsis in its parameter
4666 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004667 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004668 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004669 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004670 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004671 return;
4672 }
4673
4674 // (C++ 13.3.2p2): A candidate function having more than m parameters
4675 // is viable only if the (m+1)st parameter has a default argument
4676 // (8.3.6). For the purposes of overload resolution, the
4677 // parameter list is truncated on the right, so that there are
4678 // exactly m parameters.
4679 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004680 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004681 // Not enough arguments.
4682 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004683 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004684 return;
4685 }
4686
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004687 // (CUDA B.1): Check for invalid calls between targets.
4688 if (getLangOptions().CUDA)
4689 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4690 if (CheckCUDATarget(Caller, Function)) {
4691 Candidate.Viable = false;
4692 Candidate.FailureKind = ovl_fail_bad_target;
4693 return;
4694 }
4695
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004696 // Determine the implicit conversion sequences for each of the
4697 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004698 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4699 if (ArgIdx < NumArgsInProto) {
4700 // (C++ 13.3.2p3): for F to be a viable function, there shall
4701 // exist for each argument an implicit conversion sequence
4702 // (13.3.3.1) that converts that argument to the corresponding
4703 // parameter of F.
4704 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004705 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004706 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004707 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004708 /*InOverloadResolution=*/true,
4709 /*AllowObjCWritebackConversion=*/
4710 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004711 if (Candidate.Conversions[ArgIdx].isBad()) {
4712 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004713 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004714 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004715 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004716 } else {
4717 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4718 // argument for which there is no corresponding parameter is
4719 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004720 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004721 }
4722 }
4723}
4724
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004725/// \brief Add all of the function declarations in the given function set to
4726/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004727void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004728 Expr **Args, unsigned NumArgs,
4729 OverloadCandidateSet& CandidateSet,
4730 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004731 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004732 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4733 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004734 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004735 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004736 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004737 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004739 CandidateSet, SuppressUserConversions);
4740 else
John McCalla0296f72010-03-19 07:35:19 +00004741 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004742 SuppressUserConversions);
4743 } else {
John McCalla0296f72010-03-19 07:35:19 +00004744 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004745 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4746 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004747 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004748 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004749 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004751 Args[0]->Classify(Context),
4752 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004753 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004754 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004755 else
John McCalla0296f72010-03-19 07:35:19 +00004756 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004757 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004758 Args, NumArgs, CandidateSet,
4759 SuppressUserConversions);
4760 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004761 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004762}
4763
John McCallf0f1cf02009-11-17 07:50:12 +00004764/// AddMethodCandidate - Adds a named decl (which is some kind of
4765/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004766void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004767 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004768 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004769 Expr **Args, unsigned NumArgs,
4770 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004771 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004772 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004773 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004774
4775 if (isa<UsingShadowDecl>(Decl))
4776 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004777
John McCallf0f1cf02009-11-17 07:50:12 +00004778 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4779 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4780 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004781 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4782 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004783 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004784 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004785 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004786 } else {
John McCalla0296f72010-03-19 07:35:19 +00004787 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004788 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004789 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004790 }
4791}
4792
Douglas Gregor436424c2008-11-18 23:14:02 +00004793/// AddMethodCandidate - Adds the given C++ member function to the set
4794/// of candidate functions, using the given function call arguments
4795/// and the object argument (@c Object). For example, in a call
4796/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4797/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4798/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004799/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004800void
John McCalla0296f72010-03-19 07:35:19 +00004801Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004802 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004803 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004804 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004805 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004806 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004807 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004808 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004809 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004810 assert(!isa<CXXConstructorDecl>(Method) &&
4811 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004812
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004813 if (!CandidateSet.isNewCandidate(Method))
4814 return;
4815
Douglas Gregor27381f32009-11-23 12:27:39 +00004816 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004817 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004818
Douglas Gregor436424c2008-11-18 23:14:02 +00004819 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004820 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00004821 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004822 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004823 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004824 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004825 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004826
4827 unsigned NumArgsInProto = Proto->getNumArgs();
4828
4829 // (C++ 13.3.2p2): A candidate function having fewer than m
4830 // parameters is viable only if it has an ellipsis in its parameter
4831 // list (8.3.5).
4832 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4833 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004834 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004835 return;
4836 }
4837
4838 // (C++ 13.3.2p2): A candidate function having more than m parameters
4839 // is viable only if the (m+1)st parameter has a default argument
4840 // (8.3.6). For the purposes of overload resolution, the
4841 // parameter list is truncated on the right, so that there are
4842 // exactly m parameters.
4843 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4844 if (NumArgs < MinRequiredArgs) {
4845 // Not enough arguments.
4846 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004847 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004848 return;
4849 }
4850
4851 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00004852
John McCall6e9f8f62009-12-03 04:06:58 +00004853 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004854 // The implicit object argument is ignored.
4855 Candidate.IgnoreObjectArgument = true;
4856 else {
4857 // Determine the implicit conversion sequence for the object
4858 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004859 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004860 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4861 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004862 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004863 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004864 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004865 return;
4866 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004867 }
4868
4869 // Determine the implicit conversion sequences for each of the
4870 // arguments.
4871 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4872 if (ArgIdx < NumArgsInProto) {
4873 // (C++ 13.3.2p3): for F to be a viable function, there shall
4874 // exist for each argument an implicit conversion sequence
4875 // (13.3.3.1) that converts that argument to the corresponding
4876 // parameter of F.
4877 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004878 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004879 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004880 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004881 /*InOverloadResolution=*/true,
4882 /*AllowObjCWritebackConversion=*/
4883 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004884 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004885 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004886 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004887 break;
4888 }
4889 } else {
4890 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4891 // argument for which there is no corresponding parameter is
4892 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004893 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004894 }
4895 }
4896}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004897
Douglas Gregor97628d62009-08-21 00:16:32 +00004898/// \brief Add a C++ member function template as a candidate to the candidate
4899/// set, using template argument deduction to produce an appropriate member
4900/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004901void
Douglas Gregor97628d62009-08-21 00:16:32 +00004902Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004903 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004904 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004905 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004906 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004907 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004908 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004909 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004910 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004911 if (!CandidateSet.isNewCandidate(MethodTmpl))
4912 return;
4913
Douglas Gregor97628d62009-08-21 00:16:32 +00004914 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004915 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004916 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004917 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004918 // candidate functions in the usual way.113) A given name can refer to one
4919 // or more function templates and also to a set of overloaded non-template
4920 // functions. In such a case, the candidate functions generated from each
4921 // function template are combined with the set of non-template candidate
4922 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004923 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004924 FunctionDecl *Specialization = 0;
4925 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004926 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004927 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004928 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004929 Candidate.FoundDecl = FoundDecl;
4930 Candidate.Function = MethodTmpl->getTemplatedDecl();
4931 Candidate.Viable = false;
4932 Candidate.FailureKind = ovl_fail_bad_deduction;
4933 Candidate.IsSurrogate = false;
4934 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004935 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004936 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004937 Info);
4938 return;
4939 }
Mike Stump11289f42009-09-09 15:08:12 +00004940
Douglas Gregor97628d62009-08-21 00:16:32 +00004941 // Add the function template specialization produced by template argument
4942 // deduction as a candidate.
4943 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004944 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004945 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004946 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004947 ActingContext, ObjectType, ObjectClassification,
4948 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004949}
4950
Douglas Gregor05155d82009-08-21 23:19:43 +00004951/// \brief Add a C++ function template specialization as a candidate
4952/// in the candidate set, using template argument deduction to produce
4953/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004954void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004955Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004956 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004957 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004958 Expr **Args, unsigned NumArgs,
4959 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004960 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004961 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4962 return;
4963
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004964 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004965 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004966 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004967 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004968 // candidate functions in the usual way.113) A given name can refer to one
4969 // or more function templates and also to a set of overloaded non-template
4970 // functions. In such a case, the candidate functions generated from each
4971 // function template are combined with the set of non-template candidate
4972 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004973 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004974 FunctionDecl *Specialization = 0;
4975 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004976 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004977 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004978 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00004979 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004980 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4981 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004982 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004983 Candidate.IsSurrogate = false;
4984 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004985 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004986 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004987 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004988 return;
4989 }
Mike Stump11289f42009-09-09 15:08:12 +00004990
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004991 // Add the function template specialization produced by template argument
4992 // deduction as a candidate.
4993 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004994 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004995 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004996}
Mike Stump11289f42009-09-09 15:08:12 +00004997
Douglas Gregora1f013e2008-11-07 22:36:19 +00004998/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004999/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005000/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005001/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005002/// (which may or may not be the same type as the type that the
5003/// conversion function produces).
5004void
5005Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005006 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005007 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005008 Expr *From, QualType ToType,
5009 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005010 assert(!Conversion->getDescribedFunctionTemplate() &&
5011 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005012 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005013 if (!CandidateSet.isNewCandidate(Conversion))
5014 return;
5015
Douglas Gregor27381f32009-11-23 12:27:39 +00005016 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005017 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005018
Douglas Gregora1f013e2008-11-07 22:36:19 +00005019 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005020 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005021 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005022 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005023 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005024 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005025 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005026 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005027 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005028 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005029 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005030
Douglas Gregor6affc782010-08-19 15:37:02 +00005031 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005032 // For conversion functions, the function is considered to be a member of
5033 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005034 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005035 //
5036 // Determine the implicit conversion sequence for the implicit
5037 // object parameter.
5038 QualType ImplicitParamType = From->getType();
5039 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5040 ImplicitParamType = FromPtrType->getPointeeType();
5041 CXXRecordDecl *ConversionContext
5042 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005043
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005044 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045 = TryObjectArgumentInitialization(*this, From->getType(),
5046 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005047 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048
John McCall0d1da222010-01-12 00:44:57 +00005049 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005050 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005051 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005052 return;
5053 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005054
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005055 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005056 // derived to base as such conversions are given Conversion Rank. They only
5057 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5058 QualType FromCanon
5059 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5060 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5061 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5062 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005063 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005064 return;
5065 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005066
Douglas Gregora1f013e2008-11-07 22:36:19 +00005067 // To determine what the conversion from the result of calling the
5068 // conversion function to the type we're eventually trying to
5069 // convert to (ToType), we need to synthesize a call to the
5070 // conversion function and attempt copy initialization from it. This
5071 // makes sure that we get the right semantics with respect to
5072 // lvalues/rvalues and the type. Fortunately, we can allocate this
5073 // call on the stack and we don't need its arguments to be
5074 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005075 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005076 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005077 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5078 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005079 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005080 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005081
Richard Smith48d24642011-07-13 22:53:21 +00005082 QualType ConversionType = Conversion->getConversionType();
5083 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005084 Candidate.Viable = false;
5085 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5086 return;
5087 }
5088
Richard Smith48d24642011-07-13 22:53:21 +00005089 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005090
Mike Stump11289f42009-09-09 15:08:12 +00005091 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005092 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5093 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005094 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005095 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005096 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005097 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005098 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005099 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005100 /*InOverloadResolution=*/false,
5101 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005102
John McCall0d1da222010-01-12 00:44:57 +00005103 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005104 case ImplicitConversionSequence::StandardConversion:
5105 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005106
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005107 // C++ [over.ics.user]p3:
5108 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005109 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005110 // shall have exact match rank.
5111 if (Conversion->getPrimaryTemplate() &&
5112 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5113 Candidate.Viable = false;
5114 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5115 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005116
Douglas Gregorcba72b12011-01-21 05:18:22 +00005117 // C++0x [dcl.init.ref]p5:
5118 // In the second case, if the reference is an rvalue reference and
5119 // the second standard conversion sequence of the user-defined
5120 // conversion sequence includes an lvalue-to-rvalue conversion, the
5121 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005122 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005123 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5124 Candidate.Viable = false;
5125 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5126 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005127 break;
5128
5129 case ImplicitConversionSequence::BadConversion:
5130 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005131 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005132 break;
5133
5134 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005135 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005136 "Can only end up with a standard conversion sequence or failure");
5137 }
5138}
5139
Douglas Gregor05155d82009-08-21 23:19:43 +00005140/// \brief Adds a conversion function template specialization
5141/// candidate to the overload set, using template argument deduction
5142/// to deduce the template arguments of the conversion function
5143/// template from the type that we are converting to (C++
5144/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005145void
Douglas Gregor05155d82009-08-21 23:19:43 +00005146Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005147 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005148 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005149 Expr *From, QualType ToType,
5150 OverloadCandidateSet &CandidateSet) {
5151 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5152 "Only conversion function templates permitted here");
5153
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005154 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5155 return;
5156
John McCallbc077cf2010-02-08 23:07:23 +00005157 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005158 CXXConversionDecl *Specialization = 0;
5159 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005160 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005161 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005162 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005163 Candidate.FoundDecl = FoundDecl;
5164 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5165 Candidate.Viable = false;
5166 Candidate.FailureKind = ovl_fail_bad_deduction;
5167 Candidate.IsSurrogate = false;
5168 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005169 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005170 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005171 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005172 return;
5173 }
Mike Stump11289f42009-09-09 15:08:12 +00005174
Douglas Gregor05155d82009-08-21 23:19:43 +00005175 // Add the conversion function template specialization produced by
5176 // template argument deduction as a candidate.
5177 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005178 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005179 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005180}
5181
Douglas Gregorab7897a2008-11-19 22:57:39 +00005182/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5183/// converts the given @c Object to a function pointer via the
5184/// conversion function @c Conversion, and then attempts to call it
5185/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5186/// the type of function that we'll eventually be calling.
5187void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005188 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005189 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005190 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005191 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005192 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005193 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005194 if (!CandidateSet.isNewCandidate(Conversion))
5195 return;
5196
Douglas Gregor27381f32009-11-23 12:27:39 +00005197 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005198 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005199
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005200 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005201 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005202 Candidate.Function = 0;
5203 Candidate.Surrogate = Conversion;
5204 Candidate.Viable = true;
5205 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005206 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005207 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005208
5209 // Determine the implicit conversion sequence for the implicit
5210 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005211 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005212 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005213 Object->Classify(Context),
5214 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005215 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005216 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005217 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005218 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005219 return;
5220 }
5221
5222 // The first conversion is actually a user-defined conversion whose
5223 // first conversion is ObjectInit's standard conversion (which is
5224 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005225 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005226 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005227 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005228 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005229 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005230 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005231 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005232 = Candidate.Conversions[0].UserDefined.Before;
5233 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5234
Mike Stump11289f42009-09-09 15:08:12 +00005235 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005236 unsigned NumArgsInProto = Proto->getNumArgs();
5237
5238 // (C++ 13.3.2p2): A candidate function having fewer than m
5239 // parameters is viable only if it has an ellipsis in its parameter
5240 // list (8.3.5).
5241 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5242 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005243 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005244 return;
5245 }
5246
5247 // Function types don't have any default arguments, so just check if
5248 // we have enough arguments.
5249 if (NumArgs < NumArgsInProto) {
5250 // Not enough arguments.
5251 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005252 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005253 return;
5254 }
5255
5256 // Determine the implicit conversion sequences for each of the
5257 // arguments.
5258 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5259 if (ArgIdx < NumArgsInProto) {
5260 // (C++ 13.3.2p3): for F to be a viable function, there shall
5261 // exist for each argument an implicit conversion sequence
5262 // (13.3.3.1) that converts that argument to the corresponding
5263 // parameter of F.
5264 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005265 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005266 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005267 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005268 /*InOverloadResolution=*/false,
5269 /*AllowObjCWritebackConversion=*/
5270 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005271 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005272 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005273 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005274 break;
5275 }
5276 } else {
5277 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5278 // argument for which there is no corresponding parameter is
5279 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005280 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005281 }
5282 }
5283}
5284
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005285/// \brief Add overload candidates for overloaded operators that are
5286/// member functions.
5287///
5288/// Add the overloaded operator candidates that are member functions
5289/// for the operator Op that was used in an operator expression such
5290/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5291/// CandidateSet will store the added overload candidates. (C++
5292/// [over.match.oper]).
5293void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5294 SourceLocation OpLoc,
5295 Expr **Args, unsigned NumArgs,
5296 OverloadCandidateSet& CandidateSet,
5297 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005298 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5299
5300 // C++ [over.match.oper]p3:
5301 // For a unary operator @ with an operand of a type whose
5302 // cv-unqualified version is T1, and for a binary operator @ with
5303 // a left operand of a type whose cv-unqualified version is T1 and
5304 // a right operand of a type whose cv-unqualified version is T2,
5305 // three sets of candidate functions, designated member
5306 // candidates, non-member candidates and built-in candidates, are
5307 // constructed as follows:
5308 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005309
5310 // -- If T1 is a class type, the set of member candidates is the
5311 // result of the qualified lookup of T1::operator@
5312 // (13.3.1.1.1); otherwise, the set of member candidates is
5313 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005314 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005315 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005316 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005317 return;
Mike Stump11289f42009-09-09 15:08:12 +00005318
John McCall27b18f82009-11-17 02:14:36 +00005319 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5320 LookupQualifiedName(Operators, T1Rec->getDecl());
5321 Operators.suppressDiagnostics();
5322
Mike Stump11289f42009-09-09 15:08:12 +00005323 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005324 OperEnd = Operators.end();
5325 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005326 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005327 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005329 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005330 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005331 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005332}
5333
Douglas Gregora11693b2008-11-12 17:17:38 +00005334/// AddBuiltinCandidate - Add a candidate for a built-in
5335/// operator. ResultTy and ParamTys are the result and parameter types
5336/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005337/// arguments being passed to the candidate. IsAssignmentOperator
5338/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005339/// operator. NumContextualBoolArguments is the number of arguments
5340/// (at the beginning of the argument list) that will be contextually
5341/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005342void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005343 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005344 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005345 bool IsAssignmentOperator,
5346 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005347 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005348 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005349
Douglas Gregora11693b2008-11-12 17:17:38 +00005350 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005351 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005352 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005353 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005354 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005355 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005356 Candidate.BuiltinTypes.ResultTy = ResultTy;
5357 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5358 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5359
5360 // Determine the implicit conversion sequences for each of the
5361 // arguments.
5362 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005363 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005364 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005365 // C++ [over.match.oper]p4:
5366 // For the built-in assignment operators, conversions of the
5367 // left operand are restricted as follows:
5368 // -- no temporaries are introduced to hold the left operand, and
5369 // -- no user-defined conversions are applied to the left
5370 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005371 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005372 //
5373 // We block these conversions by turning off user-defined
5374 // conversions, since that is the only way that initialization of
5375 // a reference to a non-class type can occur from something that
5376 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005377 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005378 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005379 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005380 Candidate.Conversions[ArgIdx]
5381 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005382 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005383 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005384 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005385 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005386 /*InOverloadResolution=*/false,
5387 /*AllowObjCWritebackConversion=*/
5388 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005389 }
John McCall0d1da222010-01-12 00:44:57 +00005390 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005391 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005392 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005393 break;
5394 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005395 }
5396}
5397
5398/// BuiltinCandidateTypeSet - A set of types that will be used for the
5399/// candidate operator functions for built-in operators (C++
5400/// [over.built]). The types are separated into pointer types and
5401/// enumeration types.
5402class BuiltinCandidateTypeSet {
5403 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005404 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005405
5406 /// PointerTypes - The set of pointer types that will be used in the
5407 /// built-in candidates.
5408 TypeSet PointerTypes;
5409
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005410 /// MemberPointerTypes - The set of member pointer types that will be
5411 /// used in the built-in candidates.
5412 TypeSet MemberPointerTypes;
5413
Douglas Gregora11693b2008-11-12 17:17:38 +00005414 /// EnumerationTypes - The set of enumeration types that will be
5415 /// used in the built-in candidates.
5416 TypeSet EnumerationTypes;
5417
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005418 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005419 /// candidates.
5420 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005421
5422 /// \brief A flag indicating non-record types are viable candidates
5423 bool HasNonRecordTypes;
5424
5425 /// \brief A flag indicating whether either arithmetic or enumeration types
5426 /// were present in the candidate set.
5427 bool HasArithmeticOrEnumeralTypes;
5428
Douglas Gregor80af3132011-05-21 23:15:46 +00005429 /// \brief A flag indicating whether the nullptr type was present in the
5430 /// candidate set.
5431 bool HasNullPtrType;
5432
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005433 /// Sema - The semantic analysis instance where we are building the
5434 /// candidate type set.
5435 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005436
Douglas Gregora11693b2008-11-12 17:17:38 +00005437 /// Context - The AST context in which we will build the type sets.
5438 ASTContext &Context;
5439
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005440 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5441 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005442 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005443
5444public:
5445 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005446 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005447
Mike Stump11289f42009-09-09 15:08:12 +00005448 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005449 : HasNonRecordTypes(false),
5450 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005451 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005452 SemaRef(SemaRef),
5453 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005454
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005455 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005456 SourceLocation Loc,
5457 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005458 bool AllowExplicitConversions,
5459 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005460
5461 /// pointer_begin - First pointer type found;
5462 iterator pointer_begin() { return PointerTypes.begin(); }
5463
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005464 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005465 iterator pointer_end() { return PointerTypes.end(); }
5466
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005467 /// member_pointer_begin - First member pointer type found;
5468 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5469
5470 /// member_pointer_end - Past the last member pointer type found;
5471 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5472
Douglas Gregora11693b2008-11-12 17:17:38 +00005473 /// enumeration_begin - First enumeration type found;
5474 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5475
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005476 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005477 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005479 iterator vector_begin() { return VectorTypes.begin(); }
5480 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005481
5482 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5483 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005484 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005485};
5486
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005487/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005488/// the set of pointer types along with any more-qualified variants of
5489/// that type. For example, if @p Ty is "int const *", this routine
5490/// will add "int const *", "int const volatile *", "int const
5491/// restrict *", and "int const volatile restrict *" to the set of
5492/// pointer types. Returns true if the add of @p Ty itself succeeded,
5493/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005494///
5495/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005496bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005497BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5498 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005499
Douglas Gregora11693b2008-11-12 17:17:38 +00005500 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005501 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005502 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005503
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005504 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005505 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005506 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005507 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005508 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005509 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005510 buildObjCPtr = true;
5511 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005512 else
David Blaikie83d382b2011-09-23 05:06:16 +00005513 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005514 }
5515 else
5516 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005517
Sebastian Redl4990a632009-11-18 20:39:26 +00005518 // Don't add qualified variants of arrays. For one, they're not allowed
5519 // (the qualifier would sink to the element type), and for another, the
5520 // only overload situation where it matters is subscript or pointer +- int,
5521 // and those shouldn't have qualifier variants anyway.
5522 if (PointeeTy->isArrayType())
5523 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005524 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005525 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005526 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005527 bool hasVolatile = VisibleQuals.hasVolatile();
5528 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005529
John McCall8ccfcb52009-09-24 19:53:00 +00005530 // Iterate through all strict supersets of BaseCVR.
5531 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5532 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005533 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5534 // in the types.
5535 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5536 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005537 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005538 if (!buildObjCPtr)
5539 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5540 else
5541 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005542 }
5543
5544 return true;
5545}
5546
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005547/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5548/// to the set of pointer types along with any more-qualified variants of
5549/// that type. For example, if @p Ty is "int const *", this routine
5550/// will add "int const *", "int const volatile *", "int const
5551/// restrict *", and "int const volatile restrict *" to the set of
5552/// pointer types. Returns true if the add of @p Ty itself succeeded,
5553/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005554///
5555/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005556bool
5557BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5558 QualType Ty) {
5559 // Insert this type.
5560 if (!MemberPointerTypes.insert(Ty))
5561 return false;
5562
John McCall8ccfcb52009-09-24 19:53:00 +00005563 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5564 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005565
John McCall8ccfcb52009-09-24 19:53:00 +00005566 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005567 // Don't add qualified variants of arrays. For one, they're not allowed
5568 // (the qualifier would sink to the element type), and for another, the
5569 // only overload situation where it matters is subscript or pointer +- int,
5570 // and those shouldn't have qualifier variants anyway.
5571 if (PointeeTy->isArrayType())
5572 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005573 const Type *ClassTy = PointerTy->getClass();
5574
5575 // Iterate through all strict supersets of the pointee type's CVR
5576 // qualifiers.
5577 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5578 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5579 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005580
John McCall8ccfcb52009-09-24 19:53:00 +00005581 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005582 MemberPointerTypes.insert(
5583 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005584 }
5585
5586 return true;
5587}
5588
Douglas Gregora11693b2008-11-12 17:17:38 +00005589/// AddTypesConvertedFrom - Add each of the types to which the type @p
5590/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005591/// primarily interested in pointer types and enumeration types. We also
5592/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005593/// AllowUserConversions is true if we should look at the conversion
5594/// functions of a class type, and AllowExplicitConversions if we
5595/// should also include the explicit conversion functions of a class
5596/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005597void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005598BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005599 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005600 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005601 bool AllowExplicitConversions,
5602 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005603 // Only deal with canonical types.
5604 Ty = Context.getCanonicalType(Ty);
5605
5606 // Look through reference types; they aren't part of the type of an
5607 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005608 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005609 Ty = RefTy->getPointeeType();
5610
John McCall33ddac02011-01-19 10:06:00 +00005611 // If we're dealing with an array type, decay to the pointer.
5612 if (Ty->isArrayType())
5613 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5614
5615 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005616 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005617
Chandler Carruth00a38332010-12-13 01:44:01 +00005618 // Flag if we ever add a non-record type.
5619 const RecordType *TyRec = Ty->getAs<RecordType>();
5620 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5621
Chandler Carruth00a38332010-12-13 01:44:01 +00005622 // Flag if we encounter an arithmetic type.
5623 HasArithmeticOrEnumeralTypes =
5624 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5625
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005626 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5627 PointerTypes.insert(Ty);
5628 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005629 // Insert our type, and its more-qualified variants, into the set
5630 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005631 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005632 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005633 } else if (Ty->isMemberPointerType()) {
5634 // Member pointers are far easier, since the pointee can't be converted.
5635 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5636 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005637 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005638 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005639 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005640 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005641 // We treat vector types as arithmetic types in many contexts as an
5642 // extension.
5643 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005644 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005645 } else if (Ty->isNullPtrType()) {
5646 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005647 } else if (AllowUserConversions && TyRec) {
5648 // No conversion functions in incomplete types.
5649 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5650 return;
Mike Stump11289f42009-09-09 15:08:12 +00005651
Chandler Carruth00a38332010-12-13 01:44:01 +00005652 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5653 const UnresolvedSetImpl *Conversions
5654 = ClassDecl->getVisibleConversionFunctions();
5655 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5656 E = Conversions->end(); I != E; ++I) {
5657 NamedDecl *D = I.getDecl();
5658 if (isa<UsingShadowDecl>(D))
5659 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005660
Chandler Carruth00a38332010-12-13 01:44:01 +00005661 // Skip conversion function templates; they don't tell us anything
5662 // about which builtin types we can convert to.
5663 if (isa<FunctionTemplateDecl>(D))
5664 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005665
Chandler Carruth00a38332010-12-13 01:44:01 +00005666 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5667 if (AllowExplicitConversions || !Conv->isExplicit()) {
5668 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5669 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005670 }
5671 }
5672 }
5673}
5674
Douglas Gregor84605ae2009-08-24 13:43:27 +00005675/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5676/// the volatile- and non-volatile-qualified assignment operators for the
5677/// given type to the candidate set.
5678static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5679 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005680 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005681 unsigned NumArgs,
5682 OverloadCandidateSet &CandidateSet) {
5683 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005684
Douglas Gregor84605ae2009-08-24 13:43:27 +00005685 // T& operator=(T&, T)
5686 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5687 ParamTypes[1] = T;
5688 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5689 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005690
Douglas Gregor84605ae2009-08-24 13:43:27 +00005691 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5692 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005693 ParamTypes[0]
5694 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005695 ParamTypes[1] = T;
5696 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005697 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005698 }
5699}
Mike Stump11289f42009-09-09 15:08:12 +00005700
Sebastian Redl1054fae2009-10-25 17:03:50 +00005701/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5702/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005703static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5704 Qualifiers VRQuals;
5705 const RecordType *TyRec;
5706 if (const MemberPointerType *RHSMPType =
5707 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005708 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005709 else
5710 TyRec = ArgExpr->getType()->getAs<RecordType>();
5711 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005712 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005713 VRQuals.addVolatile();
5714 VRQuals.addRestrict();
5715 return VRQuals;
5716 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005717
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005718 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005719 if (!ClassDecl->hasDefinition())
5720 return VRQuals;
5721
John McCallad371252010-01-20 00:46:10 +00005722 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005723 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724
John McCallad371252010-01-20 00:46:10 +00005725 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005726 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005727 NamedDecl *D = I.getDecl();
5728 if (isa<UsingShadowDecl>(D))
5729 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5730 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005731 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5732 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5733 CanTy = ResTypeRef->getPointeeType();
5734 // Need to go down the pointer/mempointer chain and add qualifiers
5735 // as see them.
5736 bool done = false;
5737 while (!done) {
5738 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5739 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005740 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005741 CanTy->getAs<MemberPointerType>())
5742 CanTy = ResTypeMPtr->getPointeeType();
5743 else
5744 done = true;
5745 if (CanTy.isVolatileQualified())
5746 VRQuals.addVolatile();
5747 if (CanTy.isRestrictQualified())
5748 VRQuals.addRestrict();
5749 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5750 return VRQuals;
5751 }
5752 }
5753 }
5754 return VRQuals;
5755}
John McCall52872982010-11-13 05:51:15 +00005756
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005757namespace {
John McCall52872982010-11-13 05:51:15 +00005758
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005759/// \brief Helper class to manage the addition of builtin operator overload
5760/// candidates. It provides shared state and utility methods used throughout
5761/// the process, as well as a helper method to add each group of builtin
5762/// operator overloads from the standard to a candidate set.
5763class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005764 // Common instance state available to all overload candidate addition methods.
5765 Sema &S;
5766 Expr **Args;
5767 unsigned NumArgs;
5768 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005769 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005770 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005771 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005772
Chandler Carruthc6586e52010-12-12 10:35:00 +00005773 // Define some constants used to index and iterate over the arithemetic types
5774 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005775 // The "promoted arithmetic types" are the arithmetic
5776 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005777 static const unsigned FirstIntegralType = 3;
5778 static const unsigned LastIntegralType = 18;
5779 static const unsigned FirstPromotedIntegralType = 3,
5780 LastPromotedIntegralType = 9;
5781 static const unsigned FirstPromotedArithmeticType = 0,
5782 LastPromotedArithmeticType = 9;
5783 static const unsigned NumArithmeticTypes = 18;
5784
Chandler Carruthc6586e52010-12-12 10:35:00 +00005785 /// \brief Get the canonical type for a given arithmetic type index.
5786 CanQualType getArithmeticType(unsigned index) {
5787 assert(index < NumArithmeticTypes);
5788 static CanQualType ASTContext::* const
5789 ArithmeticTypes[NumArithmeticTypes] = {
5790 // Start of promoted types.
5791 &ASTContext::FloatTy,
5792 &ASTContext::DoubleTy,
5793 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005794
Chandler Carruthc6586e52010-12-12 10:35:00 +00005795 // Start of integral types.
5796 &ASTContext::IntTy,
5797 &ASTContext::LongTy,
5798 &ASTContext::LongLongTy,
5799 &ASTContext::UnsignedIntTy,
5800 &ASTContext::UnsignedLongTy,
5801 &ASTContext::UnsignedLongLongTy,
5802 // End of promoted types.
5803
5804 &ASTContext::BoolTy,
5805 &ASTContext::CharTy,
5806 &ASTContext::WCharTy,
5807 &ASTContext::Char16Ty,
5808 &ASTContext::Char32Ty,
5809 &ASTContext::SignedCharTy,
5810 &ASTContext::ShortTy,
5811 &ASTContext::UnsignedCharTy,
5812 &ASTContext::UnsignedShortTy,
5813 // End of integral types.
5814 // FIXME: What about complex?
5815 };
5816 return S.Context.*ArithmeticTypes[index];
5817 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005818
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005819 /// \brief Gets the canonical type resulting from the usual arithemetic
5820 /// converions for the given arithmetic types.
5821 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5822 // Accelerator table for performing the usual arithmetic conversions.
5823 // The rules are basically:
5824 // - if either is floating-point, use the wider floating-point
5825 // - if same signedness, use the higher rank
5826 // - if same size, use unsigned of the higher rank
5827 // - use the larger type
5828 // These rules, together with the axiom that higher ranks are
5829 // never smaller, are sufficient to precompute all of these results
5830 // *except* when dealing with signed types of higher rank.
5831 // (we could precompute SLL x UI for all known platforms, but it's
5832 // better not to make any assumptions).
5833 enum PromotedType {
5834 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5835 };
5836 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5837 [LastPromotedArithmeticType] = {
5838 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5839 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5840 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5841 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5842 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5843 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5844 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5845 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5846 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5847 };
5848
5849 assert(L < LastPromotedArithmeticType);
5850 assert(R < LastPromotedArithmeticType);
5851 int Idx = ConversionsTable[L][R];
5852
5853 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005854 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005855
5856 // Slow path: we need to compare widths.
5857 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005858 CanQualType LT = getArithmeticType(L),
5859 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005860 unsigned LW = S.Context.getIntWidth(LT),
5861 RW = S.Context.getIntWidth(RT);
5862
5863 // If they're different widths, use the signed type.
5864 if (LW > RW) return LT;
5865 else if (LW < RW) return RT;
5866
5867 // Otherwise, use the unsigned type of the signed type's rank.
5868 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5869 assert(L == SLL || R == SLL);
5870 return S.Context.UnsignedLongLongTy;
5871 }
5872
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005873 /// \brief Helper method to factor out the common pattern of adding overloads
5874 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005875 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5876 bool HasVolatile) {
5877 QualType ParamTypes[2] = {
5878 S.Context.getLValueReferenceType(CandidateTy),
5879 S.Context.IntTy
5880 };
5881
5882 // Non-volatile version.
5883 if (NumArgs == 1)
5884 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5885 else
5886 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5887
5888 // Use a heuristic to reduce number of builtin candidates in the set:
5889 // add volatile version only if there are conversions to a volatile type.
5890 if (HasVolatile) {
5891 ParamTypes[0] =
5892 S.Context.getLValueReferenceType(
5893 S.Context.getVolatileType(CandidateTy));
5894 if (NumArgs == 1)
5895 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5896 else
5897 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5898 }
5899 }
5900
5901public:
5902 BuiltinOperatorOverloadBuilder(
5903 Sema &S, Expr **Args, unsigned NumArgs,
5904 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005905 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005906 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005907 OverloadCandidateSet &CandidateSet)
5908 : S(S), Args(Args), NumArgs(NumArgs),
5909 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005910 HasArithmeticOrEnumeralCandidateType(
5911 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005912 CandidateTypes(CandidateTypes),
5913 CandidateSet(CandidateSet) {
5914 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005915 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005916 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005917 assert(getArithmeticType(LastPromotedIntegralType - 1)
5918 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005919 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005920 assert(getArithmeticType(FirstPromotedArithmeticType)
5921 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005922 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005923 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5924 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005925 "Invalid last promoted arithmetic type");
5926 }
5927
5928 // C++ [over.built]p3:
5929 //
5930 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5931 // is either volatile or empty, there exist candidate operator
5932 // functions of the form
5933 //
5934 // VQ T& operator++(VQ T&);
5935 // T operator++(VQ T&, int);
5936 //
5937 // C++ [over.built]p4:
5938 //
5939 // For every pair (T, VQ), where T is an arithmetic type other
5940 // than bool, and VQ is either volatile or empty, there exist
5941 // candidate operator functions of the form
5942 //
5943 // VQ T& operator--(VQ T&);
5944 // T operator--(VQ T&, int);
5945 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005946 if (!HasArithmeticOrEnumeralCandidateType)
5947 return;
5948
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005949 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5950 Arith < NumArithmeticTypes; ++Arith) {
5951 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005952 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005953 VisibleTypeConversionsQuals.hasVolatile());
5954 }
5955 }
5956
5957 // C++ [over.built]p5:
5958 //
5959 // For every pair (T, VQ), where T is a cv-qualified or
5960 // cv-unqualified object type, and VQ is either volatile or
5961 // empty, there exist candidate operator functions of the form
5962 //
5963 // T*VQ& operator++(T*VQ&);
5964 // T*VQ& operator--(T*VQ&);
5965 // T* operator++(T*VQ&, int);
5966 // T* operator--(T*VQ&, int);
5967 void addPlusPlusMinusMinusPointerOverloads() {
5968 for (BuiltinCandidateTypeSet::iterator
5969 Ptr = CandidateTypes[0].pointer_begin(),
5970 PtrEnd = CandidateTypes[0].pointer_end();
5971 Ptr != PtrEnd; ++Ptr) {
5972 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005973 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005974 continue;
5975
5976 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5977 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5978 VisibleTypeConversionsQuals.hasVolatile()));
5979 }
5980 }
5981
5982 // C++ [over.built]p6:
5983 // For every cv-qualified or cv-unqualified object type T, there
5984 // exist candidate operator functions of the form
5985 //
5986 // T& operator*(T*);
5987 //
5988 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005989 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005990 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005991 // T& operator*(T*);
5992 void addUnaryStarPointerOverloads() {
5993 for (BuiltinCandidateTypeSet::iterator
5994 Ptr = CandidateTypes[0].pointer_begin(),
5995 PtrEnd = CandidateTypes[0].pointer_end();
5996 Ptr != PtrEnd; ++Ptr) {
5997 QualType ParamTy = *Ptr;
5998 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005999 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6000 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006001
Douglas Gregor02824322011-01-26 19:30:28 +00006002 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6003 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6004 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006005
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006006 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6007 &ParamTy, Args, 1, CandidateSet);
6008 }
6009 }
6010
6011 // C++ [over.built]p9:
6012 // For every promoted arithmetic type T, there exist candidate
6013 // operator functions of the form
6014 //
6015 // T operator+(T);
6016 // T operator-(T);
6017 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006018 if (!HasArithmeticOrEnumeralCandidateType)
6019 return;
6020
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006021 for (unsigned Arith = FirstPromotedArithmeticType;
6022 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006023 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006024 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6025 }
6026
6027 // Extension: We also add these operators for vector types.
6028 for (BuiltinCandidateTypeSet::iterator
6029 Vec = CandidateTypes[0].vector_begin(),
6030 VecEnd = CandidateTypes[0].vector_end();
6031 Vec != VecEnd; ++Vec) {
6032 QualType VecTy = *Vec;
6033 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6034 }
6035 }
6036
6037 // C++ [over.built]p8:
6038 // For every type T, there exist candidate operator functions of
6039 // the form
6040 //
6041 // T* operator+(T*);
6042 void addUnaryPlusPointerOverloads() {
6043 for (BuiltinCandidateTypeSet::iterator
6044 Ptr = CandidateTypes[0].pointer_begin(),
6045 PtrEnd = CandidateTypes[0].pointer_end();
6046 Ptr != PtrEnd; ++Ptr) {
6047 QualType ParamTy = *Ptr;
6048 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6049 }
6050 }
6051
6052 // C++ [over.built]p10:
6053 // For every promoted integral type T, there exist candidate
6054 // operator functions of the form
6055 //
6056 // T operator~(T);
6057 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006058 if (!HasArithmeticOrEnumeralCandidateType)
6059 return;
6060
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006061 for (unsigned Int = FirstPromotedIntegralType;
6062 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006063 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006064 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6065 }
6066
6067 // Extension: We also add this operator for vector types.
6068 for (BuiltinCandidateTypeSet::iterator
6069 Vec = CandidateTypes[0].vector_begin(),
6070 VecEnd = CandidateTypes[0].vector_end();
6071 Vec != VecEnd; ++Vec) {
6072 QualType VecTy = *Vec;
6073 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6074 }
6075 }
6076
6077 // C++ [over.match.oper]p16:
6078 // For every pointer to member type T, there exist candidate operator
6079 // functions of the form
6080 //
6081 // bool operator==(T,T);
6082 // bool operator!=(T,T);
6083 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6084 /// Set of (canonical) types that we've already handled.
6085 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6086
6087 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6088 for (BuiltinCandidateTypeSet::iterator
6089 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6090 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6091 MemPtr != MemPtrEnd;
6092 ++MemPtr) {
6093 // Don't add the same builtin candidate twice.
6094 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6095 continue;
6096
6097 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6098 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6099 CandidateSet);
6100 }
6101 }
6102 }
6103
6104 // C++ [over.built]p15:
6105 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006106 // For every T, where T is an enumeration type, a pointer type, or
6107 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006108 //
6109 // bool operator<(T, T);
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);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006115 void addRelationalPointerOrEnumeralOverloads() {
6116 // C++ [over.built]p1:
6117 // If there is a user-written candidate with the same name and parameter
6118 // types as a built-in candidate operator function, the built-in operator
6119 // function is hidden and is not included in the set of candidate
6120 // functions.
6121 //
6122 // The text is actually in a note, but if we don't implement it then we end
6123 // up with ambiguities when the user provides an overloaded operator for
6124 // an enumeration type. Note that only enumeration types have this problem,
6125 // so we track which enumeration types we've seen operators for. Also, the
6126 // only other overloaded operator with enumeration argumenst, operator=,
6127 // cannot be overloaded for enumeration types, so this is the only place
6128 // where we must suppress candidates like this.
6129 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6130 UserDefinedBinaryOperators;
6131
6132 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6133 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6134 CandidateTypes[ArgIdx].enumeration_end()) {
6135 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6136 CEnd = CandidateSet.end();
6137 C != CEnd; ++C) {
6138 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6139 continue;
6140
6141 QualType FirstParamType =
6142 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6143 QualType SecondParamType =
6144 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6145
6146 // Skip if either parameter isn't of enumeral type.
6147 if (!FirstParamType->isEnumeralType() ||
6148 !SecondParamType->isEnumeralType())
6149 continue;
6150
6151 // Add this operator to the set of known user-defined operators.
6152 UserDefinedBinaryOperators.insert(
6153 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6154 S.Context.getCanonicalType(SecondParamType)));
6155 }
6156 }
6157 }
6158
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006159 /// Set of (canonical) types that we've already handled.
6160 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6161
6162 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6163 for (BuiltinCandidateTypeSet::iterator
6164 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6165 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6166 Ptr != PtrEnd; ++Ptr) {
6167 // Don't add the same builtin candidate twice.
6168 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6169 continue;
6170
6171 QualType ParamTypes[2] = { *Ptr, *Ptr };
6172 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6173 CandidateSet);
6174 }
6175 for (BuiltinCandidateTypeSet::iterator
6176 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6177 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6178 Enum != EnumEnd; ++Enum) {
6179 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6180
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006181 // Don't add the same builtin candidate twice, or if a user defined
6182 // candidate exists.
6183 if (!AddedTypes.insert(CanonType) ||
6184 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6185 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006186 continue;
6187
6188 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006189 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6190 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006191 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006192
6193 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6194 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6195 if (AddedTypes.insert(NullPtrTy) &&
6196 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6197 NullPtrTy))) {
6198 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6199 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6200 CandidateSet);
6201 }
6202 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006203 }
6204 }
6205
6206 // C++ [over.built]p13:
6207 //
6208 // For every cv-qualified or cv-unqualified object type T
6209 // there exist candidate operator functions of the form
6210 //
6211 // T* operator+(T*, ptrdiff_t);
6212 // T& operator[](T*, ptrdiff_t); [BELOW]
6213 // T* operator-(T*, ptrdiff_t);
6214 // T* operator+(ptrdiff_t, T*);
6215 // T& operator[](ptrdiff_t, T*); [BELOW]
6216 //
6217 // C++ [over.built]p14:
6218 //
6219 // For every T, where T is a pointer to object type, there
6220 // exist candidate operator functions of the form
6221 //
6222 // ptrdiff_t operator-(T, T);
6223 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6224 /// Set of (canonical) types that we've already handled.
6225 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6226
6227 for (int Arg = 0; Arg < 2; ++Arg) {
6228 QualType AsymetricParamTypes[2] = {
6229 S.Context.getPointerDiffType(),
6230 S.Context.getPointerDiffType(),
6231 };
6232 for (BuiltinCandidateTypeSet::iterator
6233 Ptr = CandidateTypes[Arg].pointer_begin(),
6234 PtrEnd = CandidateTypes[Arg].pointer_end();
6235 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006236 QualType PointeeTy = (*Ptr)->getPointeeType();
6237 if (!PointeeTy->isObjectType())
6238 continue;
6239
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006240 AsymetricParamTypes[Arg] = *Ptr;
6241 if (Arg == 0 || Op == OO_Plus) {
6242 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6243 // T* operator+(ptrdiff_t, T*);
6244 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6245 CandidateSet);
6246 }
6247 if (Op == OO_Minus) {
6248 // ptrdiff_t operator-(T, T);
6249 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6250 continue;
6251
6252 QualType ParamTypes[2] = { *Ptr, *Ptr };
6253 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6254 Args, 2, CandidateSet);
6255 }
6256 }
6257 }
6258 }
6259
6260 // C++ [over.built]p12:
6261 //
6262 // For every pair of promoted arithmetic types L and R, there
6263 // exist candidate operator functions of the form
6264 //
6265 // LR operator*(L, R);
6266 // LR operator/(L, R);
6267 // LR operator+(L, R);
6268 // LR operator-(L, R);
6269 // bool 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 //
6276 // where LR is the result of the usual arithmetic conversions
6277 // between types L and R.
6278 //
6279 // C++ [over.built]p24:
6280 //
6281 // For every pair of promoted arithmetic types L and R, there exist
6282 // candidate operator functions of the form
6283 //
6284 // LR operator?(bool, L, R);
6285 //
6286 // where LR is the result of the usual arithmetic conversions
6287 // between types L and R.
6288 // Our candidates ignore the first parameter.
6289 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006290 if (!HasArithmeticOrEnumeralCandidateType)
6291 return;
6292
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006293 for (unsigned Left = FirstPromotedArithmeticType;
6294 Left < LastPromotedArithmeticType; ++Left) {
6295 for (unsigned Right = FirstPromotedArithmeticType;
6296 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006297 QualType LandR[2] = { getArithmeticType(Left),
6298 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006299 QualType Result =
6300 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006301 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006302 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6303 }
6304 }
6305
6306 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6307 // conditional operator for vector types.
6308 for (BuiltinCandidateTypeSet::iterator
6309 Vec1 = CandidateTypes[0].vector_begin(),
6310 Vec1End = CandidateTypes[0].vector_end();
6311 Vec1 != Vec1End; ++Vec1) {
6312 for (BuiltinCandidateTypeSet::iterator
6313 Vec2 = CandidateTypes[1].vector_begin(),
6314 Vec2End = CandidateTypes[1].vector_end();
6315 Vec2 != Vec2End; ++Vec2) {
6316 QualType LandR[2] = { *Vec1, *Vec2 };
6317 QualType Result = S.Context.BoolTy;
6318 if (!isComparison) {
6319 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6320 Result = *Vec1;
6321 else
6322 Result = *Vec2;
6323 }
6324
6325 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6326 }
6327 }
6328 }
6329
6330 // C++ [over.built]p17:
6331 //
6332 // For every pair of promoted integral types L and R, there
6333 // exist candidate operator functions of the form
6334 //
6335 // LR operator%(L, R);
6336 // LR operator&(L, R);
6337 // LR operator^(L, R);
6338 // LR operator|(L, R);
6339 // L operator<<(L, R);
6340 // L operator>>(L, R);
6341 //
6342 // where LR is the result of the usual arithmetic conversions
6343 // between types L and R.
6344 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006345 if (!HasArithmeticOrEnumeralCandidateType)
6346 return;
6347
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006348 for (unsigned Left = FirstPromotedIntegralType;
6349 Left < LastPromotedIntegralType; ++Left) {
6350 for (unsigned Right = FirstPromotedIntegralType;
6351 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006352 QualType LandR[2] = { getArithmeticType(Left),
6353 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006354 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6355 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006356 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006357 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6358 }
6359 }
6360 }
6361
6362 // C++ [over.built]p20:
6363 //
6364 // For every pair (T, VQ), where T is an enumeration or
6365 // pointer to member type and VQ is either volatile or
6366 // empty, there exist candidate operator functions of the form
6367 //
6368 // VQ T& operator=(VQ T&, T);
6369 void addAssignmentMemberPointerOrEnumeralOverloads() {
6370 /// Set of (canonical) types that we've already handled.
6371 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6372
6373 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6374 for (BuiltinCandidateTypeSet::iterator
6375 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6376 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6377 Enum != EnumEnd; ++Enum) {
6378 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6379 continue;
6380
6381 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6382 CandidateSet);
6383 }
6384
6385 for (BuiltinCandidateTypeSet::iterator
6386 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6387 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6388 MemPtr != MemPtrEnd; ++MemPtr) {
6389 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6390 continue;
6391
6392 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6393 CandidateSet);
6394 }
6395 }
6396 }
6397
6398 // C++ [over.built]p19:
6399 //
6400 // For every pair (T, VQ), where T is any type and VQ is either
6401 // volatile or empty, there exist candidate operator functions
6402 // of the form
6403 //
6404 // T*VQ& operator=(T*VQ&, T*);
6405 //
6406 // C++ [over.built]p21:
6407 //
6408 // For every pair (T, VQ), where T is a cv-qualified or
6409 // cv-unqualified object type and VQ is either volatile or
6410 // empty, there exist candidate operator functions of the form
6411 //
6412 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6413 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6414 void addAssignmentPointerOverloads(bool isEqualOp) {
6415 /// Set of (canonical) types that we've already handled.
6416 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6417
6418 for (BuiltinCandidateTypeSet::iterator
6419 Ptr = CandidateTypes[0].pointer_begin(),
6420 PtrEnd = CandidateTypes[0].pointer_end();
6421 Ptr != PtrEnd; ++Ptr) {
6422 // If this is operator=, keep track of the builtin candidates we added.
6423 if (isEqualOp)
6424 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006425 else if (!(*Ptr)->getPointeeType()->isObjectType())
6426 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006427
6428 // non-volatile version
6429 QualType ParamTypes[2] = {
6430 S.Context.getLValueReferenceType(*Ptr),
6431 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6432 };
6433 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6434 /*IsAssigmentOperator=*/ isEqualOp);
6435
6436 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6437 VisibleTypeConversionsQuals.hasVolatile()) {
6438 // volatile version
6439 ParamTypes[0] =
6440 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6441 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6442 /*IsAssigmentOperator=*/isEqualOp);
6443 }
6444 }
6445
6446 if (isEqualOp) {
6447 for (BuiltinCandidateTypeSet::iterator
6448 Ptr = CandidateTypes[1].pointer_begin(),
6449 PtrEnd = CandidateTypes[1].pointer_end();
6450 Ptr != PtrEnd; ++Ptr) {
6451 // Make sure we don't add the same candidate twice.
6452 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6453 continue;
6454
Chandler Carruth8e543b32010-12-12 08:17:55 +00006455 QualType ParamTypes[2] = {
6456 S.Context.getLValueReferenceType(*Ptr),
6457 *Ptr,
6458 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006459
6460 // non-volatile version
6461 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6462 /*IsAssigmentOperator=*/true);
6463
6464 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6465 VisibleTypeConversionsQuals.hasVolatile()) {
6466 // volatile version
6467 ParamTypes[0] =
6468 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6470 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006471 }
6472 }
6473 }
6474 }
6475
6476 // C++ [over.built]p18:
6477 //
6478 // For every triple (L, VQ, R), where L is an arithmetic type,
6479 // VQ is either volatile or empty, and R is a promoted
6480 // arithmetic type, there exist candidate operator functions of
6481 // the form
6482 //
6483 // VQ L& operator=(VQ L&, R);
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 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006489 if (!HasArithmeticOrEnumeralCandidateType)
6490 return;
6491
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006492 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6493 for (unsigned Right = FirstPromotedArithmeticType;
6494 Right < LastPromotedArithmeticType; ++Right) {
6495 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006496 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006497
6498 // Add this built-in operator as a candidate (VQ is empty).
6499 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006500 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006501 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6502 /*IsAssigmentOperator=*/isEqualOp);
6503
6504 // Add this built-in operator as a candidate (VQ is 'volatile').
6505 if (VisibleTypeConversionsQuals.hasVolatile()) {
6506 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006507 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006508 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006509 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6510 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006511 /*IsAssigmentOperator=*/isEqualOp);
6512 }
6513 }
6514 }
6515
6516 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6517 for (BuiltinCandidateTypeSet::iterator
6518 Vec1 = CandidateTypes[0].vector_begin(),
6519 Vec1End = CandidateTypes[0].vector_end();
6520 Vec1 != Vec1End; ++Vec1) {
6521 for (BuiltinCandidateTypeSet::iterator
6522 Vec2 = CandidateTypes[1].vector_begin(),
6523 Vec2End = CandidateTypes[1].vector_end();
6524 Vec2 != Vec2End; ++Vec2) {
6525 QualType ParamTypes[2];
6526 ParamTypes[1] = *Vec2;
6527 // Add this built-in operator as a candidate (VQ is empty).
6528 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6529 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6530 /*IsAssigmentOperator=*/isEqualOp);
6531
6532 // Add this built-in operator as a candidate (VQ is 'volatile').
6533 if (VisibleTypeConversionsQuals.hasVolatile()) {
6534 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6535 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006536 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6537 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006538 /*IsAssigmentOperator=*/isEqualOp);
6539 }
6540 }
6541 }
6542 }
6543
6544 // C++ [over.built]p22:
6545 //
6546 // For every triple (L, VQ, R), where L is an integral type, VQ
6547 // is either volatile or empty, and R is a promoted integral
6548 // type, there exist candidate operator functions of the form
6549 //
6550 // VQ L& operator%=(VQ L&, R);
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 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006557 if (!HasArithmeticOrEnumeralCandidateType)
6558 return;
6559
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006560 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6561 for (unsigned Right = FirstPromotedIntegralType;
6562 Right < LastPromotedIntegralType; ++Right) {
6563 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006564 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006565
6566 // Add this built-in operator as a candidate (VQ is empty).
6567 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006568 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006569 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6570 if (VisibleTypeConversionsQuals.hasVolatile()) {
6571 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006572 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006573 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6574 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6575 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6576 CandidateSet);
6577 }
6578 }
6579 }
6580 }
6581
6582 // C++ [over.operator]p23:
6583 //
6584 // There also exist candidate operator functions of the form
6585 //
6586 // bool operator!(bool);
6587 // bool operator&&(bool, bool);
6588 // bool operator||(bool, bool);
6589 void addExclaimOverload() {
6590 QualType ParamTy = S.Context.BoolTy;
6591 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6592 /*IsAssignmentOperator=*/false,
6593 /*NumContextualBoolArguments=*/1);
6594 }
6595 void addAmpAmpOrPipePipeOverload() {
6596 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6597 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6598 /*IsAssignmentOperator=*/false,
6599 /*NumContextualBoolArguments=*/2);
6600 }
6601
6602 // C++ [over.built]p13:
6603 //
6604 // For every cv-qualified or cv-unqualified object type T there
6605 // exist candidate operator functions of the form
6606 //
6607 // T* operator+(T*, ptrdiff_t); [ABOVE]
6608 // T& operator[](T*, ptrdiff_t);
6609 // T* operator-(T*, ptrdiff_t); [ABOVE]
6610 // T* operator+(ptrdiff_t, T*); [ABOVE]
6611 // T& operator[](ptrdiff_t, T*);
6612 void addSubscriptOverloads() {
6613 for (BuiltinCandidateTypeSet::iterator
6614 Ptr = CandidateTypes[0].pointer_begin(),
6615 PtrEnd = CandidateTypes[0].pointer_end();
6616 Ptr != PtrEnd; ++Ptr) {
6617 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6618 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006619 if (!PointeeType->isObjectType())
6620 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006621
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006622 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6623
6624 // T& operator[](T*, ptrdiff_t)
6625 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6626 }
6627
6628 for (BuiltinCandidateTypeSet::iterator
6629 Ptr = CandidateTypes[1].pointer_begin(),
6630 PtrEnd = CandidateTypes[1].pointer_end();
6631 Ptr != PtrEnd; ++Ptr) {
6632 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6633 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006634 if (!PointeeType->isObjectType())
6635 continue;
6636
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006637 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6638
6639 // T& operator[](ptrdiff_t, T*)
6640 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6641 }
6642 }
6643
6644 // C++ [over.built]p11:
6645 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6646 // C1 is the same type as C2 or is a derived class of C2, T is an object
6647 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6648 // there exist candidate operator functions of the form
6649 //
6650 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6651 //
6652 // where CV12 is the union of CV1 and CV2.
6653 void addArrowStarOverloads() {
6654 for (BuiltinCandidateTypeSet::iterator
6655 Ptr = CandidateTypes[0].pointer_begin(),
6656 PtrEnd = CandidateTypes[0].pointer_end();
6657 Ptr != PtrEnd; ++Ptr) {
6658 QualType C1Ty = (*Ptr);
6659 QualType C1;
6660 QualifierCollector Q1;
6661 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6662 if (!isa<RecordType>(C1))
6663 continue;
6664 // heuristic to reduce number of builtin candidates in the set.
6665 // Add volatile/restrict version only if there are conversions to a
6666 // volatile/restrict type.
6667 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6668 continue;
6669 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6670 continue;
6671 for (BuiltinCandidateTypeSet::iterator
6672 MemPtr = CandidateTypes[1].member_pointer_begin(),
6673 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6674 MemPtr != MemPtrEnd; ++MemPtr) {
6675 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6676 QualType C2 = QualType(mptr->getClass(), 0);
6677 C2 = C2.getUnqualifiedType();
6678 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6679 break;
6680 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6681 // build CV12 T&
6682 QualType T = mptr->getPointeeType();
6683 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6684 T.isVolatileQualified())
6685 continue;
6686 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6687 T.isRestrictQualified())
6688 continue;
6689 T = Q1.apply(S.Context, T);
6690 QualType ResultTy = S.Context.getLValueReferenceType(T);
6691 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6692 }
6693 }
6694 }
6695
6696 // Note that we don't consider the first argument, since it has been
6697 // contextually converted to bool long ago. The candidates below are
6698 // therefore added as binary.
6699 //
6700 // C++ [over.built]p25:
6701 // For every type T, where T is a pointer, pointer-to-member, or scoped
6702 // enumeration type, there exist candidate operator functions of the form
6703 //
6704 // T operator?(bool, T, T);
6705 //
6706 void addConditionalOperatorOverloads() {
6707 /// Set of (canonical) types that we've already handled.
6708 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6709
6710 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6711 for (BuiltinCandidateTypeSet::iterator
6712 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6713 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6714 Ptr != PtrEnd; ++Ptr) {
6715 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6716 continue;
6717
6718 QualType ParamTypes[2] = { *Ptr, *Ptr };
6719 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6720 }
6721
6722 for (BuiltinCandidateTypeSet::iterator
6723 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6724 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6725 MemPtr != MemPtrEnd; ++MemPtr) {
6726 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6727 continue;
6728
6729 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6730 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6731 }
6732
6733 if (S.getLangOptions().CPlusPlus0x) {
6734 for (BuiltinCandidateTypeSet::iterator
6735 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6736 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6737 Enum != EnumEnd; ++Enum) {
6738 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6739 continue;
6740
6741 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6742 continue;
6743
6744 QualType ParamTypes[2] = { *Enum, *Enum };
6745 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6746 }
6747 }
6748 }
6749 }
6750};
6751
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006752} // end anonymous namespace
6753
6754/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6755/// operator overloads to the candidate set (C++ [over.built]), based
6756/// on the operator @p Op and the arguments given. For example, if the
6757/// operator is a binary '+', this routine might add "int
6758/// operator+(int, int)" to cover integer addition.
6759void
6760Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6761 SourceLocation OpLoc,
6762 Expr **Args, unsigned NumArgs,
6763 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006764 // Find all of the types that the arguments can convert to, but only
6765 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006766 // that make use of these types. Also record whether we encounter non-record
6767 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006768 Qualifiers VisibleTypeConversionsQuals;
6769 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006770 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6771 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006772
6773 bool HasNonRecordCandidateType = false;
6774 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006775 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006776 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6777 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6778 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6779 OpLoc,
6780 true,
6781 (Op == OO_Exclaim ||
6782 Op == OO_AmpAmp ||
6783 Op == OO_PipePipe),
6784 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006785 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6786 CandidateTypes[ArgIdx].hasNonRecordTypes();
6787 HasArithmeticOrEnumeralCandidateType =
6788 HasArithmeticOrEnumeralCandidateType ||
6789 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006790 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006791
Chandler Carruth00a38332010-12-13 01:44:01 +00006792 // Exit early when no non-record types have been added to the candidate set
6793 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006794 //
6795 // We can't exit early for !, ||, or &&, since there we have always have
6796 // 'bool' overloads.
6797 if (!HasNonRecordCandidateType &&
6798 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006799 return;
6800
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006801 // Setup an object to manage the common state for building overloads.
6802 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6803 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006804 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006805 CandidateTypes, CandidateSet);
6806
6807 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006808 switch (Op) {
6809 case OO_None:
6810 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006811 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006812
Chandler Carruth5184de02010-12-12 08:51:33 +00006813 case OO_New:
6814 case OO_Delete:
6815 case OO_Array_New:
6816 case OO_Array_Delete:
6817 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006818 llvm_unreachable(
6819 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006820
6821 case OO_Comma:
6822 case OO_Arrow:
6823 // C++ [over.match.oper]p3:
6824 // -- For the operator ',', the unary operator '&', or the
6825 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006826 break;
6827
6828 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006829 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006830 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006831 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006832
6833 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006834 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006835 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006836 } else {
6837 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6838 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6839 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006840 break;
6841
Chandler Carruth5184de02010-12-12 08:51:33 +00006842 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006843 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006844 OpBuilder.addUnaryStarPointerOverloads();
6845 else
6846 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6847 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006848
Chandler Carruth5184de02010-12-12 08:51:33 +00006849 case OO_Slash:
6850 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006851 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006852
6853 case OO_PlusPlus:
6854 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006855 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6856 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006857 break;
6858
Douglas Gregor84605ae2009-08-24 13:43:27 +00006859 case OO_EqualEqual:
6860 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006861 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006862 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006863
Douglas Gregora11693b2008-11-12 17:17:38 +00006864 case OO_Less:
6865 case OO_Greater:
6866 case OO_LessEqual:
6867 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006868 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006869 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6870 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006871
Douglas Gregora11693b2008-11-12 17:17:38 +00006872 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006873 case OO_Caret:
6874 case OO_Pipe:
6875 case OO_LessLess:
6876 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006877 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006878 break;
6879
Chandler Carruth5184de02010-12-12 08:51:33 +00006880 case OO_Amp: // '&' is either unary or binary
6881 if (NumArgs == 1)
6882 // C++ [over.match.oper]p3:
6883 // -- For the operator ',', the unary operator '&', or the
6884 // operator '->', the built-in candidates set is empty.
6885 break;
6886
6887 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6888 break;
6889
6890 case OO_Tilde:
6891 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6892 break;
6893
Douglas Gregora11693b2008-11-12 17:17:38 +00006894 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006895 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006896 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006897
6898 case OO_PlusEqual:
6899 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006900 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006901 // Fall through.
6902
6903 case OO_StarEqual:
6904 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006905 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006906 break;
6907
6908 case OO_PercentEqual:
6909 case OO_LessLessEqual:
6910 case OO_GreaterGreaterEqual:
6911 case OO_AmpEqual:
6912 case OO_CaretEqual:
6913 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006914 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006915 break;
6916
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006917 case OO_Exclaim:
6918 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006919 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006920
Douglas Gregora11693b2008-11-12 17:17:38 +00006921 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006922 case OO_PipePipe:
6923 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006924 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006925
6926 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006927 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006928 break;
6929
6930 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006931 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006932 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006933
6934 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006935 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006936 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6937 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006938 }
6939}
6940
Douglas Gregore254f902009-02-04 00:32:51 +00006941/// \brief Add function candidates found via argument-dependent lookup
6942/// to the set of overloading candidates.
6943///
6944/// This routine performs argument-dependent name lookup based on the
6945/// given function name (which may also be an operator name) and adds
6946/// all of the overload candidates found by ADL to the overload
6947/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006948void
Douglas Gregore254f902009-02-04 00:32:51 +00006949Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006950 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006951 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006952 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006953 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006954 bool PartialOverloading,
6955 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006956 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006957
John McCall91f61fc2010-01-26 06:04:06 +00006958 // FIXME: This approach for uniquing ADL results (and removing
6959 // redundant candidates from the set) relies on pointer-equality,
6960 // which means we need to key off the canonical decl. However,
6961 // always going back to the canonical decl might not get us the
6962 // right set of default arguments. What default arguments are
6963 // we supposed to consider on ADL candidates, anyway?
6964
Douglas Gregorcabea402009-09-22 15:41:20 +00006965 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006966 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6967 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006968
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006969 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006970 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6971 CandEnd = CandidateSet.end();
6972 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006973 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006974 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006975 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006976 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006977 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006978
6979 // For each of the ADL candidates we found, add it to the overload
6980 // set.
John McCall8fe68082010-01-26 07:16:45 +00006981 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006982 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006983 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006984 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006985 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006986
John McCalla0296f72010-03-19 07:35:19 +00006987 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006988 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006989 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006990 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006991 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006992 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006993 }
Douglas Gregore254f902009-02-04 00:32:51 +00006994}
6995
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006996/// isBetterOverloadCandidate - Determines whether the first overload
6997/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006998bool
John McCall5c32be02010-08-24 20:38:10 +00006999isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007000 const OverloadCandidate &Cand1,
7001 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007002 SourceLocation Loc,
7003 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007004 // Define viable functions to be better candidates than non-viable
7005 // functions.
7006 if (!Cand2.Viable)
7007 return Cand1.Viable;
7008 else if (!Cand1.Viable)
7009 return false;
7010
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007011 // C++ [over.match.best]p1:
7012 //
7013 // -- if F is a static member function, ICS1(F) is defined such
7014 // that ICS1(F) is neither better nor worse than ICS1(G) for
7015 // any function G, and, symmetrically, ICS1(G) is neither
7016 // better nor worse than ICS1(F).
7017 unsigned StartArg = 0;
7018 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7019 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007020
Douglas Gregord3cb3562009-07-07 23:38:56 +00007021 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007022 // A viable function F1 is defined to be a better function than another
7023 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007024 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007025 unsigned NumArgs = Cand1.NumConversions;
7026 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007027 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007028 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007029 switch (CompareImplicitConversionSequences(S,
7030 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007031 Cand2.Conversions[ArgIdx])) {
7032 case ImplicitConversionSequence::Better:
7033 // Cand1 has a better conversion sequence.
7034 HasBetterConversion = true;
7035 break;
7036
7037 case ImplicitConversionSequence::Worse:
7038 // Cand1 can't be better than Cand2.
7039 return false;
7040
7041 case ImplicitConversionSequence::Indistinguishable:
7042 // Do nothing.
7043 break;
7044 }
7045 }
7046
Mike Stump11289f42009-09-09 15:08:12 +00007047 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007048 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007049 if (HasBetterConversion)
7050 return true;
7051
Mike Stump11289f42009-09-09 15:08:12 +00007052 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007053 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007054 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007055 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7056 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007057
7058 // -- F1 and F2 are function template specializations, and the function
7059 // template for F1 is more specialized than the template for F2
7060 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007061 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007062 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007063 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007064 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007065 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7066 Cand2.Function->getPrimaryTemplate(),
7067 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007068 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007069 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007070 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007071 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007072 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007073
Douglas Gregora1f013e2008-11-07 22:36:19 +00007074 // -- the context is an initialization by user-defined conversion
7075 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7076 // from the return type of F1 to the destination type (i.e.,
7077 // the type of the entity being initialized) is a better
7078 // conversion sequence than the standard conversion sequence
7079 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007080 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007081 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007082 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00007083 switch (CompareStandardConversionSequences(S,
7084 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007085 Cand2.FinalConversion)) {
7086 case ImplicitConversionSequence::Better:
7087 // Cand1 has a better conversion sequence.
7088 return true;
7089
7090 case ImplicitConversionSequence::Worse:
7091 // Cand1 can't be better than Cand2.
7092 return false;
7093
7094 case ImplicitConversionSequence::Indistinguishable:
7095 // Do nothing
7096 break;
7097 }
7098 }
7099
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007100 return false;
7101}
7102
Mike Stump11289f42009-09-09 15:08:12 +00007103/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007104/// within an overload candidate set.
7105///
7106/// \param CandidateSet the set of candidate functions.
7107///
7108/// \param Loc the location of the function name (or operator symbol) for
7109/// which overload resolution occurs.
7110///
Mike Stump11289f42009-09-09 15:08:12 +00007111/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007112/// function, Best points to the candidate function found.
7113///
7114/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007115OverloadingResult
7116OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007117 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007118 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007119 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007120 Best = end();
7121 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7122 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007123 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007124 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007125 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007126 }
7127
7128 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007129 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007130 return OR_No_Viable_Function;
7131
7132 // Make sure that this function is better than every other viable
7133 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007134 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007135 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007136 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007137 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007138 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007139 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007140 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007141 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007142 }
Mike Stump11289f42009-09-09 15:08:12 +00007143
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007144 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007145 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007146 (Best->Function->isDeleted() ||
7147 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007148 return OR_Deleted;
7149
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007150 return OR_Success;
7151}
7152
John McCall53262c92010-01-12 02:15:36 +00007153namespace {
7154
7155enum OverloadCandidateKind {
7156 oc_function,
7157 oc_method,
7158 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007159 oc_function_template,
7160 oc_method_template,
7161 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007162 oc_implicit_default_constructor,
7163 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007164 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007165 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007166 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007167 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007168};
7169
John McCalle1ac8d12010-01-13 00:25:19 +00007170OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7171 FunctionDecl *Fn,
7172 std::string &Description) {
7173 bool isTemplate = false;
7174
7175 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7176 isTemplate = true;
7177 Description = S.getTemplateArgumentBindingsText(
7178 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7179 }
John McCallfd0b2f82010-01-06 09:43:14 +00007180
7181 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007182 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007183 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007184
Sebastian Redl08905022011-02-05 19:23:19 +00007185 if (Ctor->getInheritedConstructor())
7186 return oc_implicit_inherited_constructor;
7187
Alexis Hunt119c10e2011-05-25 23:16:36 +00007188 if (Ctor->isDefaultConstructor())
7189 return oc_implicit_default_constructor;
7190
7191 if (Ctor->isMoveConstructor())
7192 return oc_implicit_move_constructor;
7193
7194 assert(Ctor->isCopyConstructor() &&
7195 "unexpected sort of implicit constructor");
7196 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007197 }
7198
7199 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7200 // This actually gets spelled 'candidate function' for now, but
7201 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007202 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007203 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007204
Alexis Hunt119c10e2011-05-25 23:16:36 +00007205 if (Meth->isMoveAssignmentOperator())
7206 return oc_implicit_move_assignment;
7207
Douglas Gregorec3bec02010-09-27 22:37:28 +00007208 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007209 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007210 return oc_implicit_copy_assignment;
7211 }
7212
John McCalle1ac8d12010-01-13 00:25:19 +00007213 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007214}
7215
Sebastian Redl08905022011-02-05 19:23:19 +00007216void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7217 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7218 if (!Ctor) return;
7219
7220 Ctor = Ctor->getInheritedConstructor();
7221 if (!Ctor) return;
7222
7223 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7224}
7225
John McCall53262c92010-01-12 02:15:36 +00007226} // end anonymous namespace
7227
7228// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007229void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007230 std::string FnDesc;
7231 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007232 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7233 << (unsigned) K << FnDesc;
7234 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7235 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007236 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007237}
7238
Douglas Gregorb491ed32011-02-19 21:32:49 +00007239//Notes the location of all overload candidates designated through
7240// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007241void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007242 assert(OverloadedExpr->getType() == Context.OverloadTy);
7243
7244 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7245 OverloadExpr *OvlExpr = Ovl.Expression;
7246
7247 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7248 IEnd = OvlExpr->decls_end();
7249 I != IEnd; ++I) {
7250 if (FunctionTemplateDecl *FunTmpl =
7251 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007252 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007253 } else if (FunctionDecl *Fun
7254 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007255 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007256 }
7257 }
7258}
7259
John McCall0d1da222010-01-12 00:44:57 +00007260/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7261/// "lead" diagnostic; it will be given two arguments, the source and
7262/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007263void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7264 Sema &S,
7265 SourceLocation CaretLoc,
7266 const PartialDiagnostic &PDiag) const {
7267 S.Diag(CaretLoc, PDiag)
7268 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007269 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007270 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7271 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007272 }
John McCall12f97bc2010-01-08 04:41:39 +00007273}
7274
John McCall0d1da222010-01-12 00:44:57 +00007275namespace {
7276
John McCall6a61b522010-01-13 09:16:55 +00007277void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7278 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7279 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007280 assert(Cand->Function && "for now, candidate must be a function");
7281 FunctionDecl *Fn = Cand->Function;
7282
7283 // There's a conversion slot for the object argument if this is a
7284 // non-constructor method. Note that 'I' corresponds the
7285 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007286 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007287 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007288 if (I == 0)
7289 isObjectArgument = true;
7290 else
7291 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007292 }
7293
John McCalle1ac8d12010-01-13 00:25:19 +00007294 std::string FnDesc;
7295 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7296
John McCall6a61b522010-01-13 09:16:55 +00007297 Expr *FromExpr = Conv.Bad.FromExpr;
7298 QualType FromTy = Conv.Bad.getFromType();
7299 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007300
John McCallfb7ad0f2010-02-02 02:42:52 +00007301 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007302 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007303 Expr *E = FromExpr->IgnoreParens();
7304 if (isa<UnaryOperator>(E))
7305 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007306 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007307
7308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7309 << (unsigned) FnKind << FnDesc
7310 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7311 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007312 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007313 return;
7314 }
7315
John McCall6d174642010-01-23 08:10:49 +00007316 // Do some hand-waving analysis to see if the non-viability is due
7317 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007318 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7319 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7320 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7321 CToTy = RT->getPointeeType();
7322 else {
7323 // TODO: detect and diagnose the full richness of const mismatches.
7324 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7325 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7326 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7327 }
7328
7329 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7330 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7331 // It is dumb that we have to do this here.
7332 while (isa<ArrayType>(CFromTy))
7333 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7334 while (isa<ArrayType>(CToTy))
7335 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7336
7337 Qualifiers FromQs = CFromTy.getQualifiers();
7338 Qualifiers ToQs = CToTy.getQualifiers();
7339
7340 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7341 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7342 << (unsigned) FnKind << FnDesc
7343 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7344 << FromTy
7345 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7346 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007347 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007348 return;
7349 }
7350
John McCall31168b02011-06-15 23:02:42 +00007351 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007352 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007353 << (unsigned) FnKind << FnDesc
7354 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7355 << FromTy
7356 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7357 << (unsigned) isObjectArgument << I+1;
7358 MaybeEmitInheritedConstructorNote(S, Fn);
7359 return;
7360 }
7361
Douglas Gregoraec25842011-04-26 23:16:46 +00007362 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7364 << (unsigned) FnKind << FnDesc
7365 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7366 << FromTy
7367 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7368 << (unsigned) isObjectArgument << I+1;
7369 MaybeEmitInheritedConstructorNote(S, Fn);
7370 return;
7371 }
7372
John McCall47000992010-01-14 03:28:57 +00007373 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7374 assert(CVR && "unexpected qualifiers mismatch");
7375
7376 if (isObjectArgument) {
7377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7378 << (unsigned) FnKind << FnDesc
7379 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7380 << FromTy << (CVR - 1);
7381 } else {
7382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7383 << (unsigned) FnKind << FnDesc
7384 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7385 << FromTy << (CVR - 1) << I+1;
7386 }
Sebastian Redl08905022011-02-05 19:23:19 +00007387 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007388 return;
7389 }
7390
Sebastian Redla72462c2011-09-24 17:48:32 +00007391 // Special diagnostic for failure to convert an initializer list, since
7392 // telling the user that it has type void is not useful.
7393 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7394 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7395 << (unsigned) FnKind << FnDesc
7396 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7397 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7398 MaybeEmitInheritedConstructorNote(S, Fn);
7399 return;
7400 }
7401
John McCall6d174642010-01-23 08:10:49 +00007402 // Diagnose references or pointers to incomplete types differently,
7403 // since it's far from impossible that the incompleteness triggered
7404 // the failure.
7405 QualType TempFromTy = FromTy.getNonReferenceType();
7406 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7407 TempFromTy = PTy->getPointeeType();
7408 if (TempFromTy->isIncompleteType()) {
7409 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7410 << (unsigned) FnKind << FnDesc
7411 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7412 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007413 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007414 return;
7415 }
7416
Douglas Gregor56f2e342010-06-30 23:01:39 +00007417 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007418 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007419 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7420 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7421 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7422 FromPtrTy->getPointeeType()) &&
7423 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7424 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007425 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007426 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007427 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007428 }
7429 } else if (const ObjCObjectPointerType *FromPtrTy
7430 = FromTy->getAs<ObjCObjectPointerType>()) {
7431 if (const ObjCObjectPointerType *ToPtrTy
7432 = ToTy->getAs<ObjCObjectPointerType>())
7433 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7434 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7435 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7436 FromPtrTy->getPointeeType()) &&
7437 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007438 BaseToDerivedConversion = 2;
7439 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7440 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7441 !FromTy->isIncompleteType() &&
7442 !ToRefTy->getPointeeType()->isIncompleteType() &&
7443 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7444 BaseToDerivedConversion = 3;
7445 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007446
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007447 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007448 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007449 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007450 << (unsigned) FnKind << FnDesc
7451 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007452 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007454 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007455 return;
7456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007457
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007458 if (isa<ObjCObjectPointerType>(CFromTy) &&
7459 isa<PointerType>(CToTy)) {
7460 Qualifiers FromQs = CFromTy.getQualifiers();
7461 Qualifiers ToQs = CToTy.getQualifiers();
7462 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7463 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7464 << (unsigned) FnKind << FnDesc
7465 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7466 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7467 MaybeEmitInheritedConstructorNote(S, Fn);
7468 return;
7469 }
7470 }
7471
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007472 // Emit the generic diagnostic and, optionally, add the hints to it.
7473 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7474 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007475 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007476 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7477 << (unsigned) (Cand->Fix.Kind);
7478
7479 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00007480 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
7481 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007482 FDiag << *HI;
7483 S.Diag(Fn->getLocation(), FDiag);
7484
Sebastian Redl08905022011-02-05 19:23:19 +00007485 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007486}
7487
7488void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7489 unsigned NumFormalArgs) {
7490 // TODO: treat calls to a missing default constructor as a special case
7491
7492 FunctionDecl *Fn = Cand->Function;
7493 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7494
7495 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007496
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007497 // With invalid overloaded operators, it's possible that we think we
7498 // have an arity mismatch when it fact it looks like we have the
7499 // right number of arguments, because only overloaded operators have
7500 // the weird behavior of overloading member and non-member functions.
7501 // Just don't report anything.
7502 if (Fn->isInvalidDecl() &&
7503 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7504 return;
7505
John McCall6a61b522010-01-13 09:16:55 +00007506 // at least / at most / exactly
7507 unsigned mode, modeCount;
7508 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007509 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7510 (Cand->FailureKind == ovl_fail_bad_deduction &&
7511 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007512 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007513 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007514 mode = 0; // "at least"
7515 else
7516 mode = 2; // "exactly"
7517 modeCount = MinParams;
7518 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007519 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7520 (Cand->FailureKind == ovl_fail_bad_deduction &&
7521 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007522 if (MinParams != FnTy->getNumArgs())
7523 mode = 1; // "at most"
7524 else
7525 mode = 2; // "exactly"
7526 modeCount = FnTy->getNumArgs();
7527 }
7528
7529 std::string Description;
7530 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7531
7532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007533 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007534 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007535 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007536}
7537
John McCall8b9ed552010-02-01 18:53:26 +00007538/// Diagnose a failed template-argument deduction.
7539void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7540 Expr **Args, unsigned NumArgs) {
7541 FunctionDecl *Fn = Cand->Function; // pattern
7542
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007543 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007544 NamedDecl *ParamD;
7545 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7546 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7547 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007548 switch (Cand->DeductionFailure.Result) {
7549 case Sema::TDK_Success:
7550 llvm_unreachable("TDK_success while diagnosing bad deduction");
7551
7552 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007553 assert(ParamD && "no parameter found for incomplete deduction result");
7554 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7555 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007556 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007557 return;
7558 }
7559
John McCall42d7d192010-08-05 09:05:08 +00007560 case Sema::TDK_Underqualified: {
7561 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7562 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7563
7564 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7565
7566 // Param will have been canonicalized, but it should just be a
7567 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007568 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007569 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007570 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007571 assert(S.Context.hasSameType(Param, NonCanonParam));
7572
7573 // Arg has also been canonicalized, but there's nothing we can do
7574 // about that. It also doesn't matter as much, because it won't
7575 // have any template parameters in it (because deduction isn't
7576 // done on dependent types).
7577 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7578
7579 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7580 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007581 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007582 return;
7583 }
7584
7585 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007586 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007587 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007588 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007589 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007590 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007591 which = 1;
7592 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007593 which = 2;
7594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007595
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007597 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007598 << *Cand->DeductionFailure.getFirstArg()
7599 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007600 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007601 return;
7602 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007603
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007604 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007605 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007606 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007607 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007608 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7609 << ParamD->getDeclName();
7610 else {
7611 int index = 0;
7612 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7613 index = TTP->getIndex();
7614 else if (NonTypeTemplateParmDecl *NTTP
7615 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7616 index = NTTP->getIndex();
7617 else
7618 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007619 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007620 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7621 << (index + 1);
7622 }
Sebastian Redl08905022011-02-05 19:23:19 +00007623 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007624 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007625
Douglas Gregor02eb4832010-05-08 18:13:28 +00007626 case Sema::TDK_TooManyArguments:
7627 case Sema::TDK_TooFewArguments:
7628 DiagnoseArityMismatch(S, Cand, NumArgs);
7629 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007630
7631 case Sema::TDK_InstantiationDepth:
7632 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007633 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007634 return;
7635
7636 case Sema::TDK_SubstitutionFailure: {
7637 std::string ArgString;
7638 if (TemplateArgumentList *Args
7639 = Cand->DeductionFailure.getTemplateArgumentList())
7640 ArgString = S.getTemplateArgumentBindingsText(
7641 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7642 *Args);
7643 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7644 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007645 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007646 return;
7647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007648
John McCall8b9ed552010-02-01 18:53:26 +00007649 // TODO: diagnose these individually, then kill off
7650 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007651 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007652 case Sema::TDK_FailedOverloadResolution:
7653 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007654 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007655 return;
7656 }
7657}
7658
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007659/// CUDA: diagnose an invalid call across targets.
7660void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7661 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7662 FunctionDecl *Callee = Cand->Function;
7663
7664 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7665 CalleeTarget = S.IdentifyCUDATarget(Callee);
7666
7667 std::string FnDesc;
7668 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7669
7670 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7671 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7672}
7673
John McCall8b9ed552010-02-01 18:53:26 +00007674/// Generates a 'note' diagnostic for an overload candidate. We've
7675/// already generated a primary error at the call site.
7676///
7677/// It really does need to be a single diagnostic with its caret
7678/// pointed at the candidate declaration. Yes, this creates some
7679/// major challenges of technical writing. Yes, this makes pointing
7680/// out problems with specific arguments quite awkward. It's still
7681/// better than generating twenty screens of text for every failed
7682/// overload.
7683///
7684/// It would be great to be able to express per-candidate problems
7685/// more richly for those diagnostic clients that cared, but we'd
7686/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007687void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7688 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007689 FunctionDecl *Fn = Cand->Function;
7690
John McCall12f97bc2010-01-08 04:41:39 +00007691 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007692 if (Cand->Viable && (Fn->isDeleted() ||
7693 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007694 std::string FnDesc;
7695 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007696
7697 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007698 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007699 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007700 return;
John McCall12f97bc2010-01-08 04:41:39 +00007701 }
7702
John McCalle1ac8d12010-01-13 00:25:19 +00007703 // We don't really have anything else to say about viable candidates.
7704 if (Cand->Viable) {
7705 S.NoteOverloadCandidate(Fn);
7706 return;
7707 }
John McCall0d1da222010-01-12 00:44:57 +00007708
John McCall6a61b522010-01-13 09:16:55 +00007709 switch (Cand->FailureKind) {
7710 case ovl_fail_too_many_arguments:
7711 case ovl_fail_too_few_arguments:
7712 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007713
John McCall6a61b522010-01-13 09:16:55 +00007714 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007715 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7716
John McCallfe796dd2010-01-23 05:17:32 +00007717 case ovl_fail_trivial_conversion:
7718 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007719 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007720 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007721
John McCall65eb8792010-02-25 01:37:24 +00007722 case ovl_fail_bad_conversion: {
7723 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007724 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007725 if (Cand->Conversions[I].isBad())
7726 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007727
John McCall6a61b522010-01-13 09:16:55 +00007728 // FIXME: this currently happens when we're called from SemaInit
7729 // when user-conversion overload fails. Figure out how to handle
7730 // those conditions and diagnose them well.
7731 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007732 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007733
7734 case ovl_fail_bad_target:
7735 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007736 }
John McCalld3224162010-01-08 00:58:21 +00007737}
7738
7739void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7740 // Desugar the type of the surrogate down to a function type,
7741 // retaining as many typedefs as possible while still showing
7742 // the function type (and, therefore, its parameter types).
7743 QualType FnType = Cand->Surrogate->getConversionType();
7744 bool isLValueReference = false;
7745 bool isRValueReference = false;
7746 bool isPointer = false;
7747 if (const LValueReferenceType *FnTypeRef =
7748 FnType->getAs<LValueReferenceType>()) {
7749 FnType = FnTypeRef->getPointeeType();
7750 isLValueReference = true;
7751 } else if (const RValueReferenceType *FnTypeRef =
7752 FnType->getAs<RValueReferenceType>()) {
7753 FnType = FnTypeRef->getPointeeType();
7754 isRValueReference = true;
7755 }
7756 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7757 FnType = FnTypePtr->getPointeeType();
7758 isPointer = true;
7759 }
7760 // Desugar down to a function type.
7761 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7762 // Reconstruct the pointer/reference as appropriate.
7763 if (isPointer) FnType = S.Context.getPointerType(FnType);
7764 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7765 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7766
7767 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7768 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007769 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007770}
7771
7772void NoteBuiltinOperatorCandidate(Sema &S,
7773 const char *Opc,
7774 SourceLocation OpLoc,
7775 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00007776 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00007777 std::string TypeStr("operator");
7778 TypeStr += Opc;
7779 TypeStr += "(";
7780 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00007781 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00007782 TypeStr += ")";
7783 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7784 } else {
7785 TypeStr += ", ";
7786 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7787 TypeStr += ")";
7788 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7789 }
7790}
7791
7792void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7793 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00007794 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00007795 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7796 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007797 if (ICS.isBad()) break; // all meaningless after first invalid
7798 if (!ICS.isAmbiguous()) continue;
7799
John McCall5c32be02010-08-24 20:38:10 +00007800 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007801 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007802 }
7803}
7804
John McCall3712d9e2010-01-15 23:32:50 +00007805SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7806 if (Cand->Function)
7807 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007808 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007809 return Cand->Surrogate->getLocation();
7810 return SourceLocation();
7811}
7812
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007813static unsigned
7814RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007815 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007816 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007817 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007818
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007819 case Sema::TDK_Incomplete:
7820 return 1;
7821
7822 case Sema::TDK_Underqualified:
7823 case Sema::TDK_Inconsistent:
7824 return 2;
7825
7826 case Sema::TDK_SubstitutionFailure:
7827 case Sema::TDK_NonDeducedMismatch:
7828 return 3;
7829
7830 case Sema::TDK_InstantiationDepth:
7831 case Sema::TDK_FailedOverloadResolution:
7832 return 4;
7833
7834 case Sema::TDK_InvalidExplicitArguments:
7835 return 5;
7836
7837 case Sema::TDK_TooManyArguments:
7838 case Sema::TDK_TooFewArguments:
7839 return 6;
7840 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007841 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007842}
7843
John McCallad2587a2010-01-12 00:48:53 +00007844struct CompareOverloadCandidatesForDisplay {
7845 Sema &S;
7846 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007847
7848 bool operator()(const OverloadCandidate *L,
7849 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007850 // Fast-path this check.
7851 if (L == R) return false;
7852
John McCall12f97bc2010-01-08 04:41:39 +00007853 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007854 if (L->Viable) {
7855 if (!R->Viable) return true;
7856
7857 // TODO: introduce a tri-valued comparison for overload
7858 // candidates. Would be more worthwhile if we had a sort
7859 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007860 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7861 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007862 } else if (R->Viable)
7863 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007864
John McCall3712d9e2010-01-15 23:32:50 +00007865 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007866
John McCall3712d9e2010-01-15 23:32:50 +00007867 // Criteria by which we can sort non-viable candidates:
7868 if (!L->Viable) {
7869 // 1. Arity mismatches come after other candidates.
7870 if (L->FailureKind == ovl_fail_too_many_arguments ||
7871 L->FailureKind == ovl_fail_too_few_arguments)
7872 return false;
7873 if (R->FailureKind == ovl_fail_too_many_arguments ||
7874 R->FailureKind == ovl_fail_too_few_arguments)
7875 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007876
John McCallfe796dd2010-01-23 05:17:32 +00007877 // 2. Bad conversions come first and are ordered by the number
7878 // of bad conversions and quality of good conversions.
7879 if (L->FailureKind == ovl_fail_bad_conversion) {
7880 if (R->FailureKind != ovl_fail_bad_conversion)
7881 return true;
7882
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007883 // The conversion that can be fixed with a smaller number of changes,
7884 // comes first.
7885 unsigned numLFixes = L->Fix.NumConversionsFixed;
7886 unsigned numRFixes = R->Fix.NumConversionsFixed;
7887 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7888 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007889 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007890 if (numLFixes < numRFixes)
7891 return true;
7892 else
7893 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007894 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007895
John McCallfe796dd2010-01-23 05:17:32 +00007896 // If there's any ordering between the defined conversions...
7897 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00007898 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00007899
7900 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007901 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007902 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007903 switch (CompareImplicitConversionSequences(S,
7904 L->Conversions[I],
7905 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007906 case ImplicitConversionSequence::Better:
7907 leftBetter++;
7908 break;
7909
7910 case ImplicitConversionSequence::Worse:
7911 leftBetter--;
7912 break;
7913
7914 case ImplicitConversionSequence::Indistinguishable:
7915 break;
7916 }
7917 }
7918 if (leftBetter > 0) return true;
7919 if (leftBetter < 0) return false;
7920
7921 } else if (R->FailureKind == ovl_fail_bad_conversion)
7922 return false;
7923
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007924 if (L->FailureKind == ovl_fail_bad_deduction) {
7925 if (R->FailureKind != ovl_fail_bad_deduction)
7926 return true;
7927
7928 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7929 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007930 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007931 } else if (R->FailureKind == ovl_fail_bad_deduction)
7932 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007933
John McCall3712d9e2010-01-15 23:32:50 +00007934 // TODO: others?
7935 }
7936
7937 // Sort everything else by location.
7938 SourceLocation LLoc = GetLocationForCandidate(L);
7939 SourceLocation RLoc = GetLocationForCandidate(R);
7940
7941 // Put candidates without locations (e.g. builtins) at the end.
7942 if (LLoc.isInvalid()) return false;
7943 if (RLoc.isInvalid()) return true;
7944
7945 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007946 }
7947};
7948
John McCallfe796dd2010-01-23 05:17:32 +00007949/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007950/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007951void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7952 Expr **Args, unsigned NumArgs) {
7953 assert(!Cand->Viable);
7954
7955 // Don't do anything on failures other than bad conversion.
7956 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7957
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007958 // We only want the FixIts if all the arguments can be corrected.
7959 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007960 // Use a implicit copy initialization to check conversion fixes.
7961 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007962
John McCallfe796dd2010-01-23 05:17:32 +00007963 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007964 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007965 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00007966 while (true) {
7967 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7968 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007969 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007970 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007971 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007972 }
John McCallfe796dd2010-01-23 05:17:32 +00007973 }
7974
7975 if (ConvIdx == ConvCount)
7976 return;
7977
John McCall65eb8792010-02-25 01:37:24 +00007978 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7979 "remaining conversion is initialized?");
7980
Douglas Gregoradc7a702010-04-16 17:45:54 +00007981 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007982 // operation somehow.
7983 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007984
7985 const FunctionProtoType* Proto;
7986 unsigned ArgIdx = ConvIdx;
7987
7988 if (Cand->IsSurrogate) {
7989 QualType ConvType
7990 = Cand->Surrogate->getConversionType().getNonReferenceType();
7991 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7992 ConvType = ConvPtrType->getPointeeType();
7993 Proto = ConvType->getAs<FunctionProtoType>();
7994 ArgIdx--;
7995 } else if (Cand->Function) {
7996 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7997 if (isa<CXXMethodDecl>(Cand->Function) &&
7998 !isa<CXXConstructorDecl>(Cand->Function))
7999 ArgIdx--;
8000 } else {
8001 // Builtin binary operator with a bad first conversion.
8002 assert(ConvCount <= 3);
8003 for (; ConvIdx != ConvCount; ++ConvIdx)
8004 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008005 = TryCopyInitialization(S, Args[ConvIdx],
8006 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008007 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008008 /*InOverloadResolution*/ true,
8009 /*AllowObjCWritebackConversion=*/
8010 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008011 return;
8012 }
8013
8014 // Fill in the rest of the conversions.
8015 unsigned NumArgsInProto = Proto->getNumArgs();
8016 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008017 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008018 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008019 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008020 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008021 /*InOverloadResolution=*/true,
8022 /*AllowObjCWritebackConversion=*/
8023 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008024 // Store the FixIt in the candidate if it exists.
8025 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008026 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008027 }
John McCallfe796dd2010-01-23 05:17:32 +00008028 else
8029 Cand->Conversions[ConvIdx].setEllipsis();
8030 }
8031}
8032
John McCalld3224162010-01-08 00:58:21 +00008033} // end anonymous namespace
8034
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008035/// PrintOverloadCandidates - When overload resolution fails, prints
8036/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008037/// set.
John McCall5c32be02010-08-24 20:38:10 +00008038void OverloadCandidateSet::NoteCandidates(Sema &S,
8039 OverloadCandidateDisplayKind OCD,
8040 Expr **Args, unsigned NumArgs,
8041 const char *Opc,
8042 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008043 // Sort the candidates by viability and position. Sorting directly would
8044 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008045 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008046 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8047 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008048 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008049 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008050 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008051 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008052 if (Cand->Function || Cand->IsSurrogate)
8053 Cands.push_back(Cand);
8054 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8055 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008056 }
8057 }
8058
John McCallad2587a2010-01-12 00:48:53 +00008059 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008060 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008061
John McCall0d1da222010-01-12 00:44:57 +00008062 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008063
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008064 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008065 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8066 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008067 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008068 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8069 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008070
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008071 // Set an arbitrary limit on the number of candidate functions we'll spam
8072 // the user with. FIXME: This limit should depend on details of the
8073 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008074 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008075 break;
8076 }
8077 ++CandsShown;
8078
John McCalld3224162010-01-08 00:58:21 +00008079 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008080 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008081 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008082 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008083 else {
8084 assert(Cand->Viable &&
8085 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008086 // Generally we only see ambiguities including viable builtin
8087 // operators if overload resolution got screwed up by an
8088 // ambiguous user-defined conversion.
8089 //
8090 // FIXME: It's quite possible for different conversions to see
8091 // different ambiguities, though.
8092 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008093 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008094 ReportedAmbiguousConversions = true;
8095 }
John McCalld3224162010-01-08 00:58:21 +00008096
John McCall0d1da222010-01-12 00:44:57 +00008097 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008098 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008099 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008100 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008101
8102 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008103 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008104}
8105
Douglas Gregorb491ed32011-02-19 21:32:49 +00008106// [PossiblyAFunctionType] --> [Return]
8107// NonFunctionType --> NonFunctionType
8108// R (A) --> R(A)
8109// R (*)(A) --> R (A)
8110// R (&)(A) --> R (A)
8111// R (S::*)(A) --> R (A)
8112QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8113 QualType Ret = PossiblyAFunctionType;
8114 if (const PointerType *ToTypePtr =
8115 PossiblyAFunctionType->getAs<PointerType>())
8116 Ret = ToTypePtr->getPointeeType();
8117 else if (const ReferenceType *ToTypeRef =
8118 PossiblyAFunctionType->getAs<ReferenceType>())
8119 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008120 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008121 PossiblyAFunctionType->getAs<MemberPointerType>())
8122 Ret = MemTypePtr->getPointeeType();
8123 Ret =
8124 Context.getCanonicalType(Ret).getUnqualifiedType();
8125 return Ret;
8126}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008127
Douglas Gregorb491ed32011-02-19 21:32:49 +00008128// A helper class to help with address of function resolution
8129// - allows us to avoid passing around all those ugly parameters
8130class AddressOfFunctionResolver
8131{
8132 Sema& S;
8133 Expr* SourceExpr;
8134 const QualType& TargetType;
8135 QualType TargetFunctionType; // Extracted function type from target type
8136
8137 bool Complain;
8138 //DeclAccessPair& ResultFunctionAccessPair;
8139 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008140
Douglas Gregorb491ed32011-02-19 21:32:49 +00008141 bool TargetTypeIsNonStaticMemberFunction;
8142 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008143
Douglas Gregorb491ed32011-02-19 21:32:49 +00008144 OverloadExpr::FindResult OvlExprInfo;
8145 OverloadExpr *OvlExpr;
8146 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008147 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008148
Douglas Gregorb491ed32011-02-19 21:32:49 +00008149public:
8150 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8151 const QualType& TargetType, bool Complain)
8152 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8153 Complain(Complain), Context(S.getASTContext()),
8154 TargetTypeIsNonStaticMemberFunction(
8155 !!TargetType->getAs<MemberPointerType>()),
8156 FoundNonTemplateFunction(false),
8157 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8158 OvlExpr(OvlExprInfo.Expression)
8159 {
8160 ExtractUnqualifiedFunctionTypeFromTargetType();
8161
8162 if (!TargetFunctionType->isFunctionType()) {
8163 if (OvlExpr->hasExplicitTemplateArgs()) {
8164 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008165 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008166 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008167
8168 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8169 if (!Method->isStatic()) {
8170 // If the target type is a non-function type and the function
8171 // found is a non-static member function, pretend as if that was
8172 // the target, it's the only possible type to end up with.
8173 TargetTypeIsNonStaticMemberFunction = true;
8174
8175 // And skip adding the function if its not in the proper form.
8176 // We'll diagnose this due to an empty set of functions.
8177 if (!OvlExprInfo.HasFormOfMemberPointer)
8178 return;
8179 }
8180 }
8181
Douglas Gregorb491ed32011-02-19 21:32:49 +00008182 Matches.push_back(std::make_pair(dap,Fn));
8183 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008184 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008185 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008186 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008187
8188 if (OvlExpr->hasExplicitTemplateArgs())
8189 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008190
Douglas Gregorb491ed32011-02-19 21:32:49 +00008191 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8192 // C++ [over.over]p4:
8193 // If more than one function is selected, [...]
8194 if (Matches.size() > 1) {
8195 if (FoundNonTemplateFunction)
8196 EliminateAllTemplateMatches();
8197 else
8198 EliminateAllExceptMostSpecializedTemplate();
8199 }
8200 }
8201 }
8202
8203private:
8204 bool isTargetTypeAFunction() const {
8205 return TargetFunctionType->isFunctionType();
8206 }
8207
8208 // [ToType] [Return]
8209
8210 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8211 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8212 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8213 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8214 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8215 }
8216
8217 // return true if any matching specializations were found
8218 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8219 const DeclAccessPair& CurAccessFunPair) {
8220 if (CXXMethodDecl *Method
8221 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8222 // Skip non-static function templates when converting to pointer, and
8223 // static when converting to member pointer.
8224 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8225 return false;
8226 }
8227 else if (TargetTypeIsNonStaticMemberFunction)
8228 return false;
8229
8230 // C++ [over.over]p2:
8231 // If the name is a function template, template argument deduction is
8232 // done (14.8.2.2), and if the argument deduction succeeds, the
8233 // resulting template argument list is used to generate a single
8234 // function template specialization, which is added to the set of
8235 // overloaded functions considered.
8236 FunctionDecl *Specialization = 0;
8237 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8238 if (Sema::TemplateDeductionResult Result
8239 = S.DeduceTemplateArguments(FunctionTemplate,
8240 &OvlExplicitTemplateArgs,
8241 TargetFunctionType, Specialization,
8242 Info)) {
8243 // FIXME: make a note of the failed deduction for diagnostics.
8244 (void)Result;
8245 return false;
8246 }
8247
8248 // Template argument deduction ensures that we have an exact match.
8249 // This function template specicalization works.
8250 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8251 assert(TargetFunctionType
8252 == Context.getCanonicalType(Specialization->getType()));
8253 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8254 return true;
8255 }
8256
8257 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8258 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008259 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008260 // Skip non-static functions when converting to pointer, and static
8261 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008262 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8263 return false;
8264 }
8265 else if (TargetTypeIsNonStaticMemberFunction)
8266 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008267
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008268 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008269 if (S.getLangOptions().CUDA)
8270 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8271 if (S.CheckCUDATarget(Caller, FunDecl))
8272 return false;
8273
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008274 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008275 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8276 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008277 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8278 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008279 Matches.push_back(std::make_pair(CurAccessFunPair,
8280 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008281 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008282 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008283 }
Mike Stump11289f42009-09-09 15:08:12 +00008284 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008285
8286 return false;
8287 }
8288
8289 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8290 bool Ret = false;
8291
8292 // If the overload expression doesn't have the form of a pointer to
8293 // member, don't try to convert it to a pointer-to-member type.
8294 if (IsInvalidFormOfPointerToMemberFunction())
8295 return false;
8296
8297 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8298 E = OvlExpr->decls_end();
8299 I != E; ++I) {
8300 // Look through any using declarations to find the underlying function.
8301 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8302
8303 // C++ [over.over]p3:
8304 // Non-member functions and static member functions match
8305 // targets of type "pointer-to-function" or "reference-to-function."
8306 // Nonstatic member functions match targets of
8307 // type "pointer-to-member-function."
8308 // Note that according to DR 247, the containing class does not matter.
8309 if (FunctionTemplateDecl *FunctionTemplate
8310 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8311 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8312 Ret = true;
8313 }
8314 // If we have explicit template arguments supplied, skip non-templates.
8315 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8316 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8317 Ret = true;
8318 }
8319 assert(Ret || Matches.empty());
8320 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008321 }
8322
Douglas Gregorb491ed32011-02-19 21:32:49 +00008323 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008324 // [...] and any given function template specialization F1 is
8325 // eliminated if the set contains a second function template
8326 // specialization whose function template is more specialized
8327 // than the function template of F1 according to the partial
8328 // ordering rules of 14.5.5.2.
8329
8330 // The algorithm specified above is quadratic. We instead use a
8331 // two-pass algorithm (similar to the one used to identify the
8332 // best viable function in an overload set) that identifies the
8333 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008334
8335 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8336 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8337 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008338
John McCall58cc69d2010-01-27 01:50:18 +00008339 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008340 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8341 TPOC_Other, 0, SourceExpr->getLocStart(),
8342 S.PDiag(),
8343 S.PDiag(diag::err_addr_ovl_ambiguous)
8344 << Matches[0].second->getDeclName(),
8345 S.PDiag(diag::note_ovl_candidate)
8346 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008347 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008348
Douglas Gregorb491ed32011-02-19 21:32:49 +00008349 if (Result != MatchesCopy.end()) {
8350 // Make it the first and only element
8351 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8352 Matches[0].second = cast<FunctionDecl>(*Result);
8353 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008354 }
8355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008356
Douglas Gregorb491ed32011-02-19 21:32:49 +00008357 void EliminateAllTemplateMatches() {
8358 // [...] any function template specializations in the set are
8359 // eliminated if the set also contains a non-template function, [...]
8360 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8361 if (Matches[I].second->getPrimaryTemplate() == 0)
8362 ++I;
8363 else {
8364 Matches[I] = Matches[--N];
8365 Matches.set_size(N);
8366 }
8367 }
8368 }
8369
8370public:
8371 void ComplainNoMatchesFound() const {
8372 assert(Matches.empty());
8373 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8374 << OvlExpr->getName() << TargetFunctionType
8375 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008376 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008377 }
8378
8379 bool IsInvalidFormOfPointerToMemberFunction() const {
8380 return TargetTypeIsNonStaticMemberFunction &&
8381 !OvlExprInfo.HasFormOfMemberPointer;
8382 }
8383
8384 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8385 // TODO: Should we condition this on whether any functions might
8386 // have matched, or is it more appropriate to do that in callers?
8387 // TODO: a fixit wouldn't hurt.
8388 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8389 << TargetType << OvlExpr->getSourceRange();
8390 }
8391
8392 void ComplainOfInvalidConversion() const {
8393 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8394 << OvlExpr->getName() << TargetType;
8395 }
8396
8397 void ComplainMultipleMatchesFound() const {
8398 assert(Matches.size() > 1);
8399 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8400 << OvlExpr->getName()
8401 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008402 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008403 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008404
8405 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8406
Douglas Gregorb491ed32011-02-19 21:32:49 +00008407 int getNumMatches() const { return Matches.size(); }
8408
8409 FunctionDecl* getMatchingFunctionDecl() const {
8410 if (Matches.size() != 1) return 0;
8411 return Matches[0].second;
8412 }
8413
8414 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8415 if (Matches.size() != 1) return 0;
8416 return &Matches[0].first;
8417 }
8418};
8419
8420/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8421/// an overloaded function (C++ [over.over]), where @p From is an
8422/// expression with overloaded function type and @p ToType is the type
8423/// we're trying to resolve to. For example:
8424///
8425/// @code
8426/// int f(double);
8427/// int f(int);
8428///
8429/// int (*pfd)(double) = f; // selects f(double)
8430/// @endcode
8431///
8432/// This routine returns the resulting FunctionDecl if it could be
8433/// resolved, and NULL otherwise. When @p Complain is true, this
8434/// routine will emit diagnostics if there is an error.
8435FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008436Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8437 QualType TargetType,
8438 bool Complain,
8439 DeclAccessPair &FoundResult,
8440 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008441 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008442
8443 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8444 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008445 int NumMatches = Resolver.getNumMatches();
8446 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008447 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008448 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8449 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8450 else
8451 Resolver.ComplainNoMatchesFound();
8452 }
8453 else if (NumMatches > 1 && Complain)
8454 Resolver.ComplainMultipleMatchesFound();
8455 else if (NumMatches == 1) {
8456 Fn = Resolver.getMatchingFunctionDecl();
8457 assert(Fn);
8458 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8459 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008460 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008461 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008462 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008463
8464 if (pHadMultipleCandidates)
8465 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008466 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008467}
8468
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008469/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008470/// resolve that overloaded function expression down to a single function.
8471///
8472/// This routine can only resolve template-ids that refer to a single function
8473/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008474/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008475/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008476FunctionDecl *
8477Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8478 bool Complain,
8479 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008480 // C++ [over.over]p1:
8481 // [...] [Note: any redundant set of parentheses surrounding the
8482 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008483 // C++ [over.over]p1:
8484 // [...] The overloaded function name can be preceded by the &
8485 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008486
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008487 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008488 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008489 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008490
8491 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008492 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008493
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008494 // Look through all of the overloaded functions, searching for one
8495 // whose type matches exactly.
8496 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008497 for (UnresolvedSetIterator I = ovl->decls_begin(),
8498 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008499 // C++0x [temp.arg.explicit]p3:
8500 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008501 // where deduction is not done, if a template argument list is
8502 // specified and it, along with any default template arguments,
8503 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008504 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008505 FunctionTemplateDecl *FunctionTemplate
8506 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008507
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008508 // C++ [over.over]p2:
8509 // If the name is a function template, template argument deduction is
8510 // done (14.8.2.2), and if the argument deduction succeeds, the
8511 // resulting template argument list is used to generate a single
8512 // function template specialization, which is added to the set of
8513 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008514 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008515 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008516 if (TemplateDeductionResult Result
8517 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8518 Specialization, Info)) {
8519 // FIXME: make a note of the failed deduction for diagnostics.
8520 (void)Result;
8521 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008522 }
8523
John McCall0009fcc2011-04-26 20:42:42 +00008524 assert(Specialization && "no specialization and no error?");
8525
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008526 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008527 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008528 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008529 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8530 << ovl->getName();
8531 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008532 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008533 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008534 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008535
John McCall0009fcc2011-04-26 20:42:42 +00008536 Matched = Specialization;
8537 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008539
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008540 return Matched;
8541}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008542
Douglas Gregor1beec452011-03-12 01:48:56 +00008543
8544
8545
John McCall50a2c2c2011-10-11 23:14:30 +00008546// Resolve and fix an overloaded expression that can be resolved
8547// because it identifies a single function template specialization.
8548//
Douglas Gregor1beec452011-03-12 01:48:56 +00008549// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008550//
8551// Return true if it was logically possible to so resolve the
8552// expression, regardless of whether or not it succeeded. Always
8553// returns true if 'complain' is set.
8554bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8555 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8556 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008557 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008558 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008559 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008560
John McCall50a2c2c2011-10-11 23:14:30 +00008561 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008562
John McCall0009fcc2011-04-26 20:42:42 +00008563 DeclAccessPair found;
8564 ExprResult SingleFunctionExpression;
8565 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8566 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008567 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8568 SrcExpr = ExprError();
8569 return true;
8570 }
John McCall0009fcc2011-04-26 20:42:42 +00008571
8572 // It is only correct to resolve to an instance method if we're
8573 // resolving a form that's permitted to be a pointer to member.
8574 // Otherwise we'll end up making a bound member expression, which
8575 // is illegal in all the contexts we resolve like this.
8576 if (!ovl.HasFormOfMemberPointer &&
8577 isa<CXXMethodDecl>(fn) &&
8578 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008579 if (!complain) return false;
8580
8581 Diag(ovl.Expression->getExprLoc(),
8582 diag::err_bound_member_function)
8583 << 0 << ovl.Expression->getSourceRange();
8584
8585 // TODO: I believe we only end up here if there's a mix of
8586 // static and non-static candidates (otherwise the expression
8587 // would have 'bound member' type, not 'overload' type).
8588 // Ideally we would note which candidate was chosen and why
8589 // the static candidates were rejected.
8590 SrcExpr = ExprError();
8591 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008592 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008593
John McCall0009fcc2011-04-26 20:42:42 +00008594 // Fix the expresion to refer to 'fn'.
8595 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008596 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008597
8598 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008599 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008600 SingleFunctionExpression =
8601 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008602 if (SingleFunctionExpression.isInvalid()) {
8603 SrcExpr = ExprError();
8604 return true;
8605 }
8606 }
John McCall0009fcc2011-04-26 20:42:42 +00008607 }
8608
8609 if (!SingleFunctionExpression.isUsable()) {
8610 if (complain) {
8611 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8612 << ovl.Expression->getName()
8613 << DestTypeForComplaining
8614 << OpRangeForComplaining
8615 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008616 NoteAllOverloadCandidates(SrcExpr.get());
8617
8618 SrcExpr = ExprError();
8619 return true;
8620 }
8621
8622 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008623 }
8624
John McCall50a2c2c2011-10-11 23:14:30 +00008625 SrcExpr = SingleFunctionExpression;
8626 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008627}
8628
Douglas Gregorcabea402009-09-22 15:41:20 +00008629/// \brief Add a single candidate to the overload set.
8630static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008631 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008632 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008633 Expr **Args, unsigned NumArgs,
8634 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008635 bool PartialOverloading,
8636 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008637 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008638 if (isa<UsingShadowDecl>(Callee))
8639 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8640
Douglas Gregorcabea402009-09-22 15:41:20 +00008641 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008642 if (ExplicitTemplateArgs) {
8643 assert(!KnownValid && "Explicit template arguments?");
8644 return;
8645 }
John McCalla0296f72010-03-19 07:35:19 +00008646 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008647 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008648 return;
John McCalld14a8642009-11-21 08:51:07 +00008649 }
8650
8651 if (FunctionTemplateDecl *FuncTemplate
8652 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008653 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8654 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008655 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008656 return;
8657 }
8658
Richard Smith95ce4f62011-06-26 22:19:54 +00008659 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008660}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008661
Douglas Gregorcabea402009-09-22 15:41:20 +00008662/// \brief Add the overload candidates named by callee and/or found by argument
8663/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008664void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008665 Expr **Args, unsigned NumArgs,
8666 OverloadCandidateSet &CandidateSet,
8667 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008668
8669#ifndef NDEBUG
8670 // Verify that ArgumentDependentLookup is consistent with the rules
8671 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008672 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008673 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8674 // and let Y be the lookup set produced by argument dependent
8675 // lookup (defined as follows). If X contains
8676 //
8677 // -- a declaration of a class member, or
8678 //
8679 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008680 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008681 //
8682 // -- a declaration that is neither a function or a function
8683 // template
8684 //
8685 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008686
John McCall57500772009-12-16 12:17:52 +00008687 if (ULE->requiresADL()) {
8688 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8689 E = ULE->decls_end(); I != E; ++I) {
8690 assert(!(*I)->getDeclContext()->isRecord());
8691 assert(isa<UsingShadowDecl>(*I) ||
8692 !(*I)->getDeclContext()->isFunctionOrMethod());
8693 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008694 }
8695 }
8696#endif
8697
John McCall57500772009-12-16 12:17:52 +00008698 // It would be nice to avoid this copy.
8699 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008700 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008701 if (ULE->hasExplicitTemplateArgs()) {
8702 ULE->copyTemplateArgumentsInto(TABuffer);
8703 ExplicitTemplateArgs = &TABuffer;
8704 }
8705
8706 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8707 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008708 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008709 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008710 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008711
John McCall57500772009-12-16 12:17:52 +00008712 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008713 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8714 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008715 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008716 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008717 PartialOverloading,
8718 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008719}
John McCalld681c392009-12-16 08:11:27 +00008720
Richard Smith998a5912011-06-05 22:42:48 +00008721/// Attempt to recover from an ill-formed use of a non-dependent name in a
8722/// template, where the non-dependent name was declared after the template
8723/// was defined. This is common in code written for a compilers which do not
8724/// correctly implement two-stage name lookup.
8725///
8726/// Returns true if a viable candidate was found and a diagnostic was issued.
8727static bool
8728DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8729 const CXXScopeSpec &SS, LookupResult &R,
8730 TemplateArgumentListInfo *ExplicitTemplateArgs,
8731 Expr **Args, unsigned NumArgs) {
8732 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8733 return false;
8734
8735 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8736 SemaRef.LookupQualifiedName(R, DC);
8737
8738 if (!R.empty()) {
8739 R.suppressDiagnostics();
8740
8741 if (isa<CXXRecordDecl>(DC)) {
8742 // Don't diagnose names we find in classes; we get much better
8743 // diagnostics for these from DiagnoseEmptyLookup.
8744 R.clear();
8745 return false;
8746 }
8747
8748 OverloadCandidateSet Candidates(FnLoc);
8749 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8750 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8751 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008752 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008753
8754 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008755 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008756 // No viable functions. Don't bother the user with notes for functions
8757 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008758 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008759 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008760 }
Richard Smith998a5912011-06-05 22:42:48 +00008761
8762 // Find the namespaces where ADL would have looked, and suggest
8763 // declaring the function there instead.
8764 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8765 Sema::AssociatedClassSet AssociatedClasses;
8766 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8767 AssociatedNamespaces,
8768 AssociatedClasses);
8769 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008770 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008771 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008772 for (Sema::AssociatedNamespaceSet::iterator
8773 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008774 end = AssociatedNamespaces.end(); it != end; ++it) {
8775 if (!Std->Encloses(*it))
8776 SuggestedNamespaces.insert(*it);
8777 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008778 } else {
8779 // Lacking the 'std::' namespace, use all of the associated namespaces.
8780 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008781 }
8782
8783 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8784 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008785 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008786 SemaRef.Diag(Best->Function->getLocation(),
8787 diag::note_not_found_by_two_phase_lookup)
8788 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008789 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008790 SemaRef.Diag(Best->Function->getLocation(),
8791 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008792 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008793 } else {
8794 // FIXME: It would be useful to list the associated namespaces here,
8795 // but the diagnostics infrastructure doesn't provide a way to produce
8796 // a localized representation of a list of items.
8797 SemaRef.Diag(Best->Function->getLocation(),
8798 diag::note_not_found_by_two_phase_lookup)
8799 << R.getLookupName() << 2;
8800 }
8801
8802 // Try to recover by calling this function.
8803 return true;
8804 }
8805
8806 R.clear();
8807 }
8808
8809 return false;
8810}
8811
8812/// Attempt to recover from ill-formed use of a non-dependent operator in a
8813/// template, where the non-dependent operator was declared after the template
8814/// was defined.
8815///
8816/// Returns true if a viable candidate was found and a diagnostic was issued.
8817static bool
8818DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8819 SourceLocation OpLoc,
8820 Expr **Args, unsigned NumArgs) {
8821 DeclarationName OpName =
8822 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8823 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8824 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8825 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8826}
8827
John McCalld681c392009-12-16 08:11:27 +00008828/// Attempts to recover from a call where no functions were found.
8829///
8830/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008831static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008832BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008833 UnresolvedLookupExpr *ULE,
8834 SourceLocation LParenLoc,
8835 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008836 SourceLocation RParenLoc,
8837 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008838
8839 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008840 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008841
John McCall57500772009-12-16 12:17:52 +00008842 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008843 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008844 if (ULE->hasExplicitTemplateArgs()) {
8845 ULE->copyTemplateArgumentsInto(TABuffer);
8846 ExplicitTemplateArgs = &TABuffer;
8847 }
8848
John McCalld681c392009-12-16 08:11:27 +00008849 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8850 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008851 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8852 ExplicitTemplateArgs, Args, NumArgs) &&
8853 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008854 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008855 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008856 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008857
John McCall57500772009-12-16 12:17:52 +00008858 assert(!R.empty() && "lookup results empty despite recovery");
8859
8860 // Build an implicit member call if appropriate. Just drop the
8861 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008862 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008863 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008864 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8865 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008866 else if (ExplicitTemplateArgs)
8867 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8868 else
8869 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8870
8871 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008872 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008873
8874 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008875 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008876 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008877 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008878 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008879}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008880
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008881/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008882/// (which eventually refers to the declaration Func) and the call
8883/// arguments Args/NumArgs, attempt to resolve the function call down
8884/// to a specific function. If overload resolution succeeds, returns
8885/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008886/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008887/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008888ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008889Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008890 SourceLocation LParenLoc,
8891 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008892 SourceLocation RParenLoc,
8893 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008894#ifndef NDEBUG
8895 if (ULE->requiresADL()) {
8896 // To do ADL, we must have found an unqualified name.
8897 assert(!ULE->getQualifier() && "qualified name with ADL");
8898
8899 // We don't perform ADL for implicit declarations of builtins.
8900 // Verify that this was correctly set up.
8901 FunctionDecl *F;
8902 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8903 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8904 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008905 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008906
John McCall57500772009-12-16 12:17:52 +00008907 // We don't perform ADL in C.
8908 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008909 } else
8910 assert(!ULE->isStdAssociatedNamespace() &&
8911 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008912#endif
8913
John McCall4124c492011-10-17 18:40:02 +00008914 UnbridgedCastsSet UnbridgedCasts;
8915 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8916 return ExprError();
8917
John McCallbc077cf2010-02-08 23:07:23 +00008918 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008919
John McCall57500772009-12-16 12:17:52 +00008920 // Add the functions denoted by the callee to the set of candidate
8921 // functions, including those from argument-dependent lookup.
8922 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008923
8924 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008925 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8926 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008927 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008928 // In Microsoft mode, if we are inside a template class member function then
8929 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008930 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008931 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00008932 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00008933 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008934 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8935 Context.DependentTy, VK_RValue,
8936 RParenLoc);
8937 CE->setTypeDependent(true);
8938 return Owned(CE);
8939 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008940 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008941 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008942 }
John McCalld681c392009-12-16 08:11:27 +00008943
John McCall4124c492011-10-17 18:40:02 +00008944 UnbridgedCasts.restore();
8945
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008946 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008947 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008948 case OR_Success: {
8949 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008950 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008951 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008952 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008953 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008954 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8955 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008956 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008957
Richard Smith998a5912011-06-05 22:42:48 +00008958 case OR_No_Viable_Function: {
8959 // Try to recover by looking for viable functions which the user might
8960 // have meant to call.
8961 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8962 Args, NumArgs, RParenLoc,
8963 /*EmptyLookup=*/false);
8964 if (!Recovery.isInvalid())
8965 return Recovery;
8966
Chris Lattner45d9d602009-02-17 07:29:20 +00008967 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008968 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008969 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008970 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008971 break;
Richard Smith998a5912011-06-05 22:42:48 +00008972 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008973
8974 case OR_Ambiguous:
8975 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008976 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008977 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008978 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008979
8980 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008981 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008982 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8983 << Best->Function->isDeleted()
8984 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008985 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008986 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008987 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00008988
8989 // We emitted an error for the unvailable/deleted function call but keep
8990 // the call in the AST.
8991 FunctionDecl *FDecl = Best->Function;
8992 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8993 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8994 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008995 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008996 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008997 }
8998
Douglas Gregorb412e172010-07-25 18:17:45 +00008999 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00009000 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00009001}
9002
John McCall4c4c1df2010-01-26 03:27:55 +00009003static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009004 return Functions.size() > 1 ||
9005 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9006}
9007
Douglas Gregor084d8552009-03-13 23:49:33 +00009008/// \brief Create a unary operation that may resolve to an overloaded
9009/// operator.
9010///
9011/// \param OpLoc The location of the operator itself (e.g., '*').
9012///
9013/// \param OpcIn The UnaryOperator::Opcode that describes this
9014/// operator.
9015///
9016/// \param Functions The set of non-member functions that will be
9017/// considered by overload resolution. The caller needs to build this
9018/// set based on the context using, e.g.,
9019/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9020/// set should not contain any member functions; those will be added
9021/// by CreateOverloadedUnaryOp().
9022///
9023/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009024ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009025Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9026 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009027 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009028 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009029
9030 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9031 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9032 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009033 // TODO: provide better source location info.
9034 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009035
John McCall4124c492011-10-17 18:40:02 +00009036 if (checkPlaceholderForOverload(*this, Input))
9037 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009038
Douglas Gregor084d8552009-03-13 23:49:33 +00009039 Expr *Args[2] = { Input, 0 };
9040 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009041
Douglas Gregor084d8552009-03-13 23:49:33 +00009042 // For post-increment and post-decrement, add the implicit '0' as
9043 // the second argument, so that we know this is a post-increment or
9044 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009045 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009046 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009047 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9048 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009049 NumArgs = 2;
9050 }
9051
9052 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009053 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009054 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009055 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009056 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009057 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009058 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009059
John McCall58cc69d2010-01-27 01:50:18 +00009060 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009061 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009062 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009063 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009064 /*ADL*/ true, IsOverloaded(Fns),
9065 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009066 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009067 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009068 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009069 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009070 OpLoc));
9071 }
9072
9073 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009074 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009075
9076 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009077 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009078
9079 // Add operator candidates that are member functions.
9080 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9081
John McCall4c4c1df2010-01-26 03:27:55 +00009082 // Add candidates from ADL.
9083 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009084 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009085 /*ExplicitTemplateArgs*/ 0,
9086 CandidateSet);
9087
Douglas Gregor084d8552009-03-13 23:49:33 +00009088 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009089 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009090
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009091 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9092
Douglas Gregor084d8552009-03-13 23:49:33 +00009093 // Perform overload resolution.
9094 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009095 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009096 case OR_Success: {
9097 // We found a built-in operator or an overloaded operator.
9098 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009099
Douglas Gregor084d8552009-03-13 23:49:33 +00009100 if (FnDecl) {
9101 // We matched an overloaded operator. Build a call to that
9102 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009103
Chandler Carruth30141632011-02-25 19:41:05 +00009104 MarkDeclarationReferenced(OpLoc, FnDecl);
9105
Douglas Gregor084d8552009-03-13 23:49:33 +00009106 // Convert the arguments.
9107 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009108 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009109
John Wiegley01296292011-04-08 18:41:53 +00009110 ExprResult InputRes =
9111 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9112 Best->FoundDecl, Method);
9113 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009114 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009115 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009116 } else {
9117 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009118 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009119 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009120 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009121 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009122 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009123 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009124 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009125 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009126 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009127 }
9128
John McCall4fa0d5f2010-05-06 18:15:07 +00009129 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9130
John McCall7decc9e2010-11-18 06:31:45 +00009131 // Determine the result type.
9132 QualType ResultTy = FnDecl->getResultType();
9133 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9134 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009135
Douglas Gregor084d8552009-03-13 23:49:33 +00009136 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009137 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9138 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009139 if (FnExpr.isInvalid())
9140 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009141
Eli Friedman030eee42009-11-18 03:58:17 +00009142 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009143 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009144 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009145 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009146
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009147 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009148 FnDecl))
9149 return ExprError();
9150
John McCallb268a282010-08-23 23:25:46 +00009151 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009152 } else {
9153 // We matched a built-in operator. Convert the arguments, then
9154 // break out so that we will build the appropriate built-in
9155 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009156 ExprResult InputRes =
9157 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9158 Best->Conversions[0], AA_Passing);
9159 if (InputRes.isInvalid())
9160 return ExprError();
9161 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009162 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009163 }
John Wiegley01296292011-04-08 18:41:53 +00009164 }
9165
9166 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009167 // This is an erroneous use of an operator which can be overloaded by
9168 // a non-member function. Check for non-member operators which were
9169 // defined too late to be candidates.
9170 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9171 // FIXME: Recover by calling the found function.
9172 return ExprError();
9173
John Wiegley01296292011-04-08 18:41:53 +00009174 // No viable function; fall through to handling this as a
9175 // built-in operator, which will produce an error message for us.
9176 break;
9177
9178 case OR_Ambiguous:
9179 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9180 << UnaryOperator::getOpcodeStr(Opc)
9181 << Input->getType()
9182 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009183 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009184 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9185 return ExprError();
9186
9187 case OR_Deleted:
9188 Diag(OpLoc, diag::err_ovl_deleted_oper)
9189 << Best->Function->isDeleted()
9190 << UnaryOperator::getOpcodeStr(Opc)
9191 << getDeletedOrUnavailableSuffix(Best->Function)
9192 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009193 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9194 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009195 return ExprError();
9196 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009197
9198 // Either we found no viable overloaded operator or we matched a
9199 // built-in operator. In either case, fall through to trying to
9200 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009201 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009202}
9203
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009204/// \brief Create a binary operation that may resolve to an overloaded
9205/// operator.
9206///
9207/// \param OpLoc The location of the operator itself (e.g., '+').
9208///
9209/// \param OpcIn The BinaryOperator::Opcode that describes this
9210/// operator.
9211///
9212/// \param Functions The set of non-member functions that will be
9213/// considered by overload resolution. The caller needs to build this
9214/// set based on the context using, e.g.,
9215/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9216/// set should not contain any member functions; those will be added
9217/// by CreateOverloadedBinOp().
9218///
9219/// \param LHS Left-hand argument.
9220/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009221ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009222Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009223 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009224 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009225 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009226 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009227 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009228
9229 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9230 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9231 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9232
9233 // If either side is type-dependent, create an appropriate dependent
9234 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009235 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009236 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009237 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009238 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009239 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009240 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009241 Context.DependentTy,
9242 VK_RValue, OK_Ordinary,
9243 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009244
Douglas Gregor5287f092009-11-05 00:51:44 +00009245 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9246 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009247 VK_LValue,
9248 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009249 Context.DependentTy,
9250 Context.DependentTy,
9251 OpLoc));
9252 }
John McCall4c4c1df2010-01-26 03:27:55 +00009253
9254 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009255 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009256 // TODO: provide better source location info in DNLoc component.
9257 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009258 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009259 = UnresolvedLookupExpr::Create(Context, NamingClass,
9260 NestedNameSpecifierLoc(), OpNameInfo,
9261 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009262 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009263 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009264 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009265 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009266 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009267 OpLoc));
9268 }
9269
John McCall4124c492011-10-17 18:40:02 +00009270 // Always do placeholder-like conversions on the RHS.
9271 if (checkPlaceholderForOverload(*this, Args[1]))
9272 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009273
John McCall526ab472011-10-25 17:37:35 +00009274 // Do placeholder-like conversion on the LHS; note that we should
9275 // not get here with a PseudoObject LHS.
9276 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009277 if (checkPlaceholderForOverload(*this, Args[0]))
9278 return ExprError();
9279
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009280 // If this is the assignment operator, we only perform overload resolution
9281 // if the left-hand side is a class or enumeration type. This is actually
9282 // a hack. The standard requires that we do overload resolution between the
9283 // various built-in candidates, but as DR507 points out, this can lead to
9284 // problems. So we do it this way, which pretty much follows what GCC does.
9285 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009286 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009287 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009288
John McCalle26a8722010-12-04 08:14:53 +00009289 // If this is the .* operator, which is not overloadable, just
9290 // create a built-in binary operator.
9291 if (Opc == BO_PtrMemD)
9292 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9293
Douglas Gregor084d8552009-03-13 23:49:33 +00009294 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009295 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009296
9297 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009298 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009299
9300 // Add operator candidates that are member functions.
9301 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9302
John McCall4c4c1df2010-01-26 03:27:55 +00009303 // Add candidates from ADL.
9304 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9305 Args, 2,
9306 /*ExplicitTemplateArgs*/ 0,
9307 CandidateSet);
9308
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009309 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009310 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009311
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009312 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9313
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009314 // Perform overload resolution.
9315 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009316 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009317 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009318 // We found a built-in operator or an overloaded operator.
9319 FunctionDecl *FnDecl = Best->Function;
9320
9321 if (FnDecl) {
9322 // We matched an overloaded operator. Build a call to that
9323 // operator.
9324
Chandler Carruth30141632011-02-25 19:41:05 +00009325 MarkDeclarationReferenced(OpLoc, FnDecl);
9326
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009327 // Convert the arguments.
9328 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009329 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009330 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009331
Chandler Carruth8e543b32010-12-12 08:17:55 +00009332 ExprResult Arg1 =
9333 PerformCopyInitialization(
9334 InitializedEntity::InitializeParameter(Context,
9335 FnDecl->getParamDecl(0)),
9336 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009337 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009338 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009339
John Wiegley01296292011-04-08 18:41:53 +00009340 ExprResult Arg0 =
9341 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9342 Best->FoundDecl, Method);
9343 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009344 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009345 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009346 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009347 } else {
9348 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009349 ExprResult Arg0 = PerformCopyInitialization(
9350 InitializedEntity::InitializeParameter(Context,
9351 FnDecl->getParamDecl(0)),
9352 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009353 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009354 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009355
Chandler Carruth8e543b32010-12-12 08:17:55 +00009356 ExprResult Arg1 =
9357 PerformCopyInitialization(
9358 InitializedEntity::InitializeParameter(Context,
9359 FnDecl->getParamDecl(1)),
9360 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009361 if (Arg1.isInvalid())
9362 return ExprError();
9363 Args[0] = LHS = Arg0.takeAs<Expr>();
9364 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009365 }
9366
John McCall4fa0d5f2010-05-06 18:15:07 +00009367 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9368
John McCall7decc9e2010-11-18 06:31:45 +00009369 // Determine the result type.
9370 QualType ResultTy = FnDecl->getResultType();
9371 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9372 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009373
9374 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009375 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9376 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009377 if (FnExpr.isInvalid())
9378 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009379
John McCallb268a282010-08-23 23:25:46 +00009380 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009381 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009382 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009383
9384 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009385 FnDecl))
9386 return ExprError();
9387
John McCallb268a282010-08-23 23:25:46 +00009388 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009389 } else {
9390 // We matched a built-in operator. Convert the arguments, then
9391 // break out so that we will build the appropriate built-in
9392 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009393 ExprResult ArgsRes0 =
9394 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9395 Best->Conversions[0], AA_Passing);
9396 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009397 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009398 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009399
John Wiegley01296292011-04-08 18:41:53 +00009400 ExprResult ArgsRes1 =
9401 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9402 Best->Conversions[1], AA_Passing);
9403 if (ArgsRes1.isInvalid())
9404 return ExprError();
9405 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009406 break;
9407 }
9408 }
9409
Douglas Gregor66950a32009-09-30 21:46:01 +00009410 case OR_No_Viable_Function: {
9411 // C++ [over.match.oper]p9:
9412 // If the operator is the operator , [...] and there are no
9413 // viable functions, then the operator is assumed to be the
9414 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009415 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009416 break;
9417
Chandler Carruth8e543b32010-12-12 08:17:55 +00009418 // For class as left operand for assignment or compound assigment
9419 // operator do not fall through to handling in built-in, but report that
9420 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009421 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009422 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009423 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009424 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9425 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009426 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009427 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009428 // This is an erroneous use of an operator which can be overloaded by
9429 // a non-member function. Check for non-member operators which were
9430 // defined too late to be candidates.
9431 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9432 // FIXME: Recover by calling the found function.
9433 return ExprError();
9434
Douglas Gregor66950a32009-09-30 21:46:01 +00009435 // No viable function; try to create a built-in operation, which will
9436 // produce an error. Then, show the non-viable candidates.
9437 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009439 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009440 "C++ binary operator overloading is missing candidates!");
9441 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009442 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9443 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009444 return move(Result);
9445 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009446
9447 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009448 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009449 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009450 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009451 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009452 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9453 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009454 return ExprError();
9455
9456 case OR_Deleted:
9457 Diag(OpLoc, diag::err_ovl_deleted_oper)
9458 << Best->Function->isDeleted()
9459 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009460 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009461 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009462 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9463 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009464 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009465 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009466
Douglas Gregor66950a32009-09-30 21:46:01 +00009467 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009468 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009469}
9470
John McCalldadc5752010-08-24 06:29:42 +00009471ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009472Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9473 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009474 Expr *Base, Expr *Idx) {
9475 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009476 DeclarationName OpName =
9477 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9478
9479 // If either side is type-dependent, create an appropriate dependent
9480 // expression.
9481 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9482
John McCall58cc69d2010-01-27 01:50:18 +00009483 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009484 // CHECKME: no 'operator' keyword?
9485 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9486 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009487 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009488 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009489 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009490 /*ADL*/ true, /*Overloaded*/ false,
9491 UnresolvedSetIterator(),
9492 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009493 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009494
Sebastian Redladba46e2009-10-29 20:17:01 +00009495 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9496 Args, 2,
9497 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009498 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009499 RLoc));
9500 }
9501
John McCall4124c492011-10-17 18:40:02 +00009502 // Handle placeholders on both operands.
9503 if (checkPlaceholderForOverload(*this, Args[0]))
9504 return ExprError();
9505 if (checkPlaceholderForOverload(*this, Args[1]))
9506 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009507
Sebastian Redladba46e2009-10-29 20:17:01 +00009508 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009509 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009510
9511 // Subscript can only be overloaded as a member function.
9512
9513 // Add operator candidates that are member functions.
9514 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9515
9516 // Add builtin operator candidates.
9517 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9518
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009519 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9520
Sebastian Redladba46e2009-10-29 20:17:01 +00009521 // Perform overload resolution.
9522 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009523 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009524 case OR_Success: {
9525 // We found a built-in operator or an overloaded operator.
9526 FunctionDecl *FnDecl = Best->Function;
9527
9528 if (FnDecl) {
9529 // We matched an overloaded operator. Build a call to that
9530 // operator.
9531
Chandler Carruth30141632011-02-25 19:41:05 +00009532 MarkDeclarationReferenced(LLoc, FnDecl);
9533
John McCalla0296f72010-03-19 07:35:19 +00009534 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009535 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009536
Sebastian Redladba46e2009-10-29 20:17:01 +00009537 // Convert the arguments.
9538 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009539 ExprResult Arg0 =
9540 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9541 Best->FoundDecl, Method);
9542 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009543 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009544 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009545
Anders Carlssona68e51e2010-01-29 18:37:50 +00009546 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009547 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009548 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009549 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009550 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009551 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009552 Owned(Args[1]));
9553 if (InputInit.isInvalid())
9554 return ExprError();
9555
9556 Args[1] = InputInit.takeAs<Expr>();
9557
Sebastian Redladba46e2009-10-29 20:17:01 +00009558 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009559 QualType ResultTy = FnDecl->getResultType();
9560 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9561 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009562
9563 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009564 DeclarationNameLoc LocInfo;
9565 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9566 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009567 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9568 HadMultipleCandidates,
9569 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009570 if (FnExpr.isInvalid())
9571 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009572
John McCallb268a282010-08-23 23:25:46 +00009573 CXXOperatorCallExpr *TheCall =
9574 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009575 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009576 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009577
John McCallb268a282010-08-23 23:25:46 +00009578 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009579 FnDecl))
9580 return ExprError();
9581
John McCallb268a282010-08-23 23:25:46 +00009582 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009583 } else {
9584 // We matched a built-in operator. Convert the arguments, then
9585 // break out so that we will build the appropriate built-in
9586 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009587 ExprResult ArgsRes0 =
9588 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9589 Best->Conversions[0], AA_Passing);
9590 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009591 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009592 Args[0] = ArgsRes0.take();
9593
9594 ExprResult ArgsRes1 =
9595 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9596 Best->Conversions[1], AA_Passing);
9597 if (ArgsRes1.isInvalid())
9598 return ExprError();
9599 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009600
9601 break;
9602 }
9603 }
9604
9605 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009606 if (CandidateSet.empty())
9607 Diag(LLoc, diag::err_ovl_no_oper)
9608 << Args[0]->getType() << /*subscript*/ 0
9609 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9610 else
9611 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9612 << Args[0]->getType()
9613 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009614 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9615 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009616 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009617 }
9618
9619 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009620 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009621 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009622 << Args[0]->getType() << Args[1]->getType()
9623 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009624 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9625 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009626 return ExprError();
9627
9628 case OR_Deleted:
9629 Diag(LLoc, diag::err_ovl_deleted_oper)
9630 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009631 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009632 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009633 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9634 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009635 return ExprError();
9636 }
9637
9638 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009639 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009640}
9641
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009642/// BuildCallToMemberFunction - Build a call to a member
9643/// function. MemExpr is the expression that refers to the member
9644/// function (and includes the object parameter), Args/NumArgs are the
9645/// arguments to the function call (not including the object
9646/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009647/// expression refers to a non-static member function or an overloaded
9648/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009649ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009650Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9651 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009652 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009653 assert(MemExprE->getType() == Context.BoundMemberTy ||
9654 MemExprE->getType() == Context.OverloadTy);
9655
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009656 // Dig out the member expression. This holds both the object
9657 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009658 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009659
John McCall0009fcc2011-04-26 20:42:42 +00009660 // Determine whether this is a call to a pointer-to-member function.
9661 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9662 assert(op->getType() == Context.BoundMemberTy);
9663 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9664
9665 QualType fnType =
9666 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9667
9668 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9669 QualType resultType = proto->getCallResultType(Context);
9670 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9671
9672 // Check that the object type isn't more qualified than the
9673 // member function we're calling.
9674 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9675
9676 QualType objectType = op->getLHS()->getType();
9677 if (op->getOpcode() == BO_PtrMemI)
9678 objectType = objectType->castAs<PointerType>()->getPointeeType();
9679 Qualifiers objectQuals = objectType.getQualifiers();
9680
9681 Qualifiers difference = objectQuals - funcQuals;
9682 difference.removeObjCGCAttr();
9683 difference.removeAddressSpace();
9684 if (difference) {
9685 std::string qualsString = difference.getAsString();
9686 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9687 << fnType.getUnqualifiedType()
9688 << qualsString
9689 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9690 }
9691
9692 CXXMemberCallExpr *call
9693 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9694 resultType, valueKind, RParenLoc);
9695
9696 if (CheckCallReturnType(proto->getResultType(),
9697 op->getRHS()->getSourceRange().getBegin(),
9698 call, 0))
9699 return ExprError();
9700
9701 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9702 return ExprError();
9703
9704 return MaybeBindToTemporary(call);
9705 }
9706
John McCall4124c492011-10-17 18:40:02 +00009707 UnbridgedCastsSet UnbridgedCasts;
9708 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9709 return ExprError();
9710
John McCall10eae182009-11-30 22:42:35 +00009711 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009712 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009713 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009714 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009715 if (isa<MemberExpr>(NakedMemExpr)) {
9716 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009717 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009718 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009719 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009720 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009721 } else {
9722 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009723 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009724
John McCall6e9f8f62009-12-03 04:06:58 +00009725 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009726 Expr::Classification ObjectClassification
9727 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9728 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009729
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009730 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009731 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009732
John McCall2d74de92009-12-01 22:10:20 +00009733 // FIXME: avoid copy.
9734 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9735 if (UnresExpr->hasExplicitTemplateArgs()) {
9736 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9737 TemplateArgs = &TemplateArgsBuffer;
9738 }
9739
John McCall10eae182009-11-30 22:42:35 +00009740 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9741 E = UnresExpr->decls_end(); I != E; ++I) {
9742
John McCall6e9f8f62009-12-03 04:06:58 +00009743 NamedDecl *Func = *I;
9744 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9745 if (isa<UsingShadowDecl>(Func))
9746 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9747
Douglas Gregor02824322011-01-26 19:30:28 +00009748
Francois Pichet64225792011-01-18 05:04:39 +00009749 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009750 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009751 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9752 CandidateSet);
9753 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009754 // If explicit template arguments were provided, we can't call a
9755 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009756 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009757 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009758
John McCalla0296f72010-03-19 07:35:19 +00009759 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009760 ObjectClassification,
9761 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009762 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009763 } else {
John McCall10eae182009-11-30 22:42:35 +00009764 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009765 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009766 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009767 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009768 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009769 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009770 }
Mike Stump11289f42009-09-09 15:08:12 +00009771
John McCall10eae182009-11-30 22:42:35 +00009772 DeclarationName DeclName = UnresExpr->getMemberName();
9773
John McCall4124c492011-10-17 18:40:02 +00009774 UnbridgedCasts.restore();
9775
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009776 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009777 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009778 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009779 case OR_Success:
9780 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009781 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009782 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009783 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009784 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009785 break;
9786
9787 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009788 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009789 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009790 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009791 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009792 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009793 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009794
9795 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009796 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009797 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009798 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009799 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009800 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009801
9802 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009803 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009804 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009805 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009806 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009807 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009809 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009810 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009811 }
9812
John McCall16df1e52010-03-30 21:47:33 +00009813 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009814
John McCall2d74de92009-12-01 22:10:20 +00009815 // If overload resolution picked a static member, build a
9816 // non-member call based on that function.
9817 if (Method->isStatic()) {
9818 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9819 Args, NumArgs, RParenLoc);
9820 }
9821
John McCall10eae182009-11-30 22:42:35 +00009822 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009823 }
9824
John McCall7decc9e2010-11-18 06:31:45 +00009825 QualType ResultType = Method->getResultType();
9826 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9827 ResultType = ResultType.getNonLValueExprType(Context);
9828
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009829 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009830 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009831 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009832 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009833
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009834 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009835 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009836 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009837 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009838
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009839 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009840 // We only need to do this if there was actually an overload; otherwise
9841 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009842 if (!Method->isStatic()) {
9843 ExprResult ObjectArg =
9844 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9845 FoundDecl, Method);
9846 if (ObjectArg.isInvalid())
9847 return ExprError();
9848 MemExpr->setBase(ObjectArg.take());
9849 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009850
9851 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009852 const FunctionProtoType *Proto =
9853 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009854 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009855 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009856 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009857
John McCallb268a282010-08-23 23:25:46 +00009858 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009859 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009860
Anders Carlsson47061ee2011-05-06 14:25:31 +00009861 if ((isa<CXXConstructorDecl>(CurContext) ||
9862 isa<CXXDestructorDecl>(CurContext)) &&
9863 TheCall->getMethodDecl()->isPure()) {
9864 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9865
Chandler Carruth59259262011-06-27 08:31:58 +00009866 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009867 Diag(MemExpr->getLocStart(),
9868 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9869 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9870 << MD->getParent()->getDeclName();
9871
9872 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009873 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009874 }
John McCallb268a282010-08-23 23:25:46 +00009875 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009876}
9877
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009878/// BuildCallToObjectOfClassType - Build a call to an object of class
9879/// type (C++ [over.call.object]), which can end up invoking an
9880/// overloaded function call operator (@c operator()) or performing a
9881/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009882ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009883Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009884 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009885 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009886 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009887 if (checkPlaceholderForOverload(*this, Obj))
9888 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009889 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009890
9891 UnbridgedCastsSet UnbridgedCasts;
9892 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9893 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009894
John Wiegley01296292011-04-08 18:41:53 +00009895 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9896 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009897
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009898 // C++ [over.call.object]p1:
9899 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009900 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009901 // candidate functions includes at least the function call
9902 // operators of T. The function call operators of T are obtained by
9903 // ordinary lookup of the name operator() in the context of
9904 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009905 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009906 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009907
John Wiegley01296292011-04-08 18:41:53 +00009908 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009909 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009910 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009911 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009912
John McCall27b18f82009-11-17 02:14:36 +00009913 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9914 LookupQualifiedName(R, Record->getDecl());
9915 R.suppressDiagnostics();
9916
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009917 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009918 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009919 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9920 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009921 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009922 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009923
Douglas Gregorab7897a2008-11-19 22:57:39 +00009924 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009925 // In addition, for each (non-explicit in C++0x) conversion function
9926 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009927 //
9928 // operator conversion-type-id () cv-qualifier;
9929 //
9930 // where cv-qualifier is the same cv-qualification as, or a
9931 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009932 // denotes the type "pointer to function of (P1,...,Pn) returning
9933 // R", or the type "reference to pointer to function of
9934 // (P1,...,Pn) returning R", or the type "reference to function
9935 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009936 // is also considered as a candidate function. Similarly,
9937 // surrogate call functions are added to the set of candidate
9938 // functions for each conversion function declared in an
9939 // accessible base class provided the function is not hidden
9940 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009941 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009942 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009943 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009944 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009945 NamedDecl *D = *I;
9946 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9947 if (isa<UsingShadowDecl>(D))
9948 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009949
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009950 // Skip over templated conversion functions; they aren't
9951 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009952 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009953 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009954
John McCall6e9f8f62009-12-03 04:06:58 +00009955 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009956 if (!Conv->isExplicit()) {
9957 // Strip the reference type (if any) and then the pointer type (if
9958 // any) to get down to what might be a function type.
9959 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9960 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9961 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009962
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009963 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9964 {
9965 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9966 Object.get(), Args, NumArgs, CandidateSet);
9967 }
9968 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009969 }
Mike Stump11289f42009-09-09 15:08:12 +00009970
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009971 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9972
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009973 // Perform overload resolution.
9974 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009975 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009976 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009977 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009978 // Overload resolution succeeded; we'll build the appropriate call
9979 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009980 break;
9981
9982 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009983 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009984 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9985 << Object.get()->getType() << /*call*/ 1
9986 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009987 else
John Wiegley01296292011-04-08 18:41:53 +00009988 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009989 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009990 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009991 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009992 break;
9993
9994 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009995 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009996 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009997 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009998 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009999 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010000
10001 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +000010002 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010003 diag::err_ovl_deleted_object_call)
10004 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010005 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010006 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010007 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010008 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010009 break;
Mike Stump11289f42009-09-09 15:08:12 +000010010 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010011
Douglas Gregorb412e172010-07-25 18:17:45 +000010012 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010013 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010014
John McCall4124c492011-10-17 18:40:02 +000010015 UnbridgedCasts.restore();
10016
Douglas Gregorab7897a2008-11-19 22:57:39 +000010017 if (Best->Function == 0) {
10018 // Since there is no function declaration, this is one of the
10019 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010020 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010021 = cast<CXXConversionDecl>(
10022 Best->Conversions[0].UserDefined.ConversionFunction);
10023
John Wiegley01296292011-04-08 18:41:53 +000010024 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010025 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010026
Douglas Gregorab7897a2008-11-19 22:57:39 +000010027 // We selected one of the surrogate functions that converts the
10028 // object parameter to a function pointer. Perform the conversion
10029 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010030
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010031 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010032 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010033 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10034 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010035 if (Call.isInvalid())
10036 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010037 // Record usage of conversion in an implicit cast.
10038 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10039 CK_UserDefinedConversion,
10040 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010041
Douglas Gregor668443e2011-01-20 00:18:04 +000010042 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010043 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010044 }
10045
Chandler Carruth30141632011-02-25 19:41:05 +000010046 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010047 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010048 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010049
Douglas Gregorab7897a2008-11-19 22:57:39 +000010050 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10051 // that calls this method, using Object for the implicit object
10052 // parameter and passing along the remaining arguments.
10053 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010054 const FunctionProtoType *Proto =
10055 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010056
10057 unsigned NumArgsInProto = Proto->getNumArgs();
10058 unsigned NumArgsToCheck = NumArgs;
10059
10060 // Build the full argument list for the method call (the
10061 // implicit object parameter is placed at the beginning of the
10062 // list).
10063 Expr **MethodArgs;
10064 if (NumArgs < NumArgsInProto) {
10065 NumArgsToCheck = NumArgsInProto;
10066 MethodArgs = new Expr*[NumArgsInProto + 1];
10067 } else {
10068 MethodArgs = new Expr*[NumArgs + 1];
10069 }
John Wiegley01296292011-04-08 18:41:53 +000010070 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010071 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10072 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010073
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010074 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10075 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010076 if (NewFn.isInvalid())
10077 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010078
10079 // Once we've built TheCall, all of the expressions are properly
10080 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010081 QualType ResultTy = Method->getResultType();
10082 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10083 ResultTy = ResultTy.getNonLValueExprType(Context);
10084
John McCallb268a282010-08-23 23:25:46 +000010085 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010086 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010087 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010088 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010089 delete [] MethodArgs;
10090
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010091 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010092 Method))
10093 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010094
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010095 // We may have default arguments. If so, we need to allocate more
10096 // slots in the call for them.
10097 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010098 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010099 else if (NumArgs > NumArgsInProto)
10100 NumArgsToCheck = NumArgsInProto;
10101
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010102 bool IsError = false;
10103
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010104 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010105 ExprResult ObjRes =
10106 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10107 Best->FoundDecl, Method);
10108 if (ObjRes.isInvalid())
10109 IsError = true;
10110 else
10111 Object = move(ObjRes);
10112 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010113
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010114 // Check the argument types.
10115 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010116 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010117 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010118 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010119
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010120 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010121
John McCalldadc5752010-08-24 06:29:42 +000010122 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010123 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010124 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010125 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010126 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010127
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010128 IsError |= InputInit.isInvalid();
10129 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010130 } else {
John McCalldadc5752010-08-24 06:29:42 +000010131 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010132 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10133 if (DefArg.isInvalid()) {
10134 IsError = true;
10135 break;
10136 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010137
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010138 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010139 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010140
10141 TheCall->setArg(i + 1, Arg);
10142 }
10143
10144 // If this is a variadic call, handle args passed through "...".
10145 if (Proto->isVariadic()) {
10146 // Promote the arguments (C99 6.5.2.2p7).
10147 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010148 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10149 IsError |= Arg.isInvalid();
10150 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010151 }
10152 }
10153
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010154 if (IsError) return true;
10155
John McCallb268a282010-08-23 23:25:46 +000010156 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010157 return true;
10158
John McCalle172be52010-08-24 06:09:16 +000010159 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010160}
10161
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010162/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010163/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010164/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010165ExprResult
John McCallb268a282010-08-23 23:25:46 +000010166Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010167 assert(Base->getType()->isRecordType() &&
10168 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010169
John McCall4124c492011-10-17 18:40:02 +000010170 if (checkPlaceholderForOverload(*this, Base))
10171 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010172
John McCallbc077cf2010-02-08 23:07:23 +000010173 SourceLocation Loc = Base->getExprLoc();
10174
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010175 // C++ [over.ref]p1:
10176 //
10177 // [...] An expression x->m is interpreted as (x.operator->())->m
10178 // for a class object x of type T if T::operator->() exists and if
10179 // the operator is selected as the best match function by the
10180 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010181 DeclarationName OpName =
10182 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010183 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010184 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010185
John McCallbc077cf2010-02-08 23:07:23 +000010186 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010187 PDiag(diag::err_typecheck_incomplete_tag)
10188 << Base->getSourceRange()))
10189 return ExprError();
10190
John McCall27b18f82009-11-17 02:14:36 +000010191 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10192 LookupQualifiedName(R, BaseRecord->getDecl());
10193 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010194
10195 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010196 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010197 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10198 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010199 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010200
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010201 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10202
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010203 // Perform overload resolution.
10204 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010205 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010206 case OR_Success:
10207 // Overload resolution succeeded; we'll build the call below.
10208 break;
10209
10210 case OR_No_Viable_Function:
10211 if (CandidateSet.empty())
10212 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010213 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010214 else
10215 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010216 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010217 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010218 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010219
10220 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010221 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10222 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010223 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010224 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010225
10226 case OR_Deleted:
10227 Diag(OpLoc, diag::err_ovl_deleted_oper)
10228 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010229 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010230 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010231 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010232 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010233 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010234 }
10235
Chandler Carruth30141632011-02-25 19:41:05 +000010236 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010237 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010238 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010239
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010240 // Convert the object parameter.
10241 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010242 ExprResult BaseResult =
10243 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10244 Best->FoundDecl, Method);
10245 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010246 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010247 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010248
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010249 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010250 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10251 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010252 if (FnExpr.isInvalid())
10253 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010254
John McCall7decc9e2010-11-18 06:31:45 +000010255 QualType ResultTy = Method->getResultType();
10256 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10257 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010258 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010259 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010260 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010261
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010262 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010263 Method))
10264 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010265
10266 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010267}
10268
Douglas Gregorcd695e52008-11-10 20:40:00 +000010269/// FixOverloadedFunctionReference - E is an expression that refers to
10270/// a C++ overloaded function (possibly with some parentheses and
10271/// perhaps a '&' around it). We have resolved the overloaded function
10272/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010273/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010274Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010275 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010276 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010277 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10278 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010279 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010280 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010281
Douglas Gregor51c538b2009-11-20 19:42:02 +000010282 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010283 }
10284
Douglas Gregor51c538b2009-11-20 19:42:02 +000010285 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010286 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10287 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010288 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010289 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010290 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010291 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010292 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010293 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010294
10295 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010296 ICE->getCastKind(),
10297 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010298 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010299 }
10300
Douglas Gregor51c538b2009-11-20 19:42:02 +000010301 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010302 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010303 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010304 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10305 if (Method->isStatic()) {
10306 // Do nothing: static member functions aren't any different
10307 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010308 } else {
John McCalle66edc12009-11-24 19:00:30 +000010309 // Fix the sub expression, which really has to be an
10310 // UnresolvedLookupExpr holding an overloaded member function
10311 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010312 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10313 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010314 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010315 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010316
John McCalld14a8642009-11-21 08:51:07 +000010317 assert(isa<DeclRefExpr>(SubExpr)
10318 && "fixed to something other than a decl ref");
10319 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10320 && "fixed to a member ref with no nested name qualifier");
10321
10322 // We have taken the address of a pointer to member
10323 // function. Perform the computation here so that we get the
10324 // appropriate pointer to member type.
10325 QualType ClassType
10326 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10327 QualType MemPtrType
10328 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10329
John McCall7decc9e2010-11-18 06:31:45 +000010330 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10331 VK_RValue, OK_Ordinary,
10332 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010333 }
10334 }
John McCall16df1e52010-03-30 21:47:33 +000010335 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10336 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010337 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010338 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010339
John McCalle3027922010-08-25 11:45:40 +000010340 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010341 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010342 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010343 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010344 }
John McCalld14a8642009-11-21 08:51:07 +000010345
10346 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010347 // FIXME: avoid copy.
10348 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010349 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010350 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10351 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010352 }
10353
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010354 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10355 ULE->getQualifierLoc(),
10356 Fn,
10357 ULE->getNameLoc(),
10358 Fn->getType(),
10359 VK_LValue,
10360 Found.getDecl(),
10361 TemplateArgs);
10362 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10363 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010364 }
10365
John McCall10eae182009-11-30 22:42:35 +000010366 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010367 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010368 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10369 if (MemExpr->hasExplicitTemplateArgs()) {
10370 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10371 TemplateArgs = &TemplateArgsBuffer;
10372 }
John McCall6b51f282009-11-23 01:53:49 +000010373
John McCall2d74de92009-12-01 22:10:20 +000010374 Expr *Base;
10375
John McCall7decc9e2010-11-18 06:31:45 +000010376 // If we're filling in a static method where we used to have an
10377 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010378 if (MemExpr->isImplicitAccess()) {
10379 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010380 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10381 MemExpr->getQualifierLoc(),
10382 Fn,
10383 MemExpr->getMemberLoc(),
10384 Fn->getType(),
10385 VK_LValue,
10386 Found.getDecl(),
10387 TemplateArgs);
10388 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10389 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010390 } else {
10391 SourceLocation Loc = MemExpr->getMemberLoc();
10392 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010393 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000010394 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000010395 Base = new (Context) CXXThisExpr(Loc,
10396 MemExpr->getBaseType(),
10397 /*isImplicit=*/true);
10398 }
John McCall2d74de92009-12-01 22:10:20 +000010399 } else
John McCallc3007a22010-10-26 07:05:15 +000010400 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010401
John McCall4adb38c2011-04-27 00:36:17 +000010402 ExprValueKind valueKind;
10403 QualType type;
10404 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10405 valueKind = VK_LValue;
10406 type = Fn->getType();
10407 } else {
10408 valueKind = VK_RValue;
10409 type = Context.BoundMemberTy;
10410 }
10411
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010412 MemberExpr *ME = MemberExpr::Create(Context, Base,
10413 MemExpr->isArrow(),
10414 MemExpr->getQualifierLoc(),
10415 Fn,
10416 Found,
10417 MemExpr->getMemberNameInfo(),
10418 TemplateArgs,
10419 type, valueKind, OK_Ordinary);
10420 ME->setHadMultipleCandidates(true);
10421 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010423
John McCallc3007a22010-10-26 07:05:15 +000010424 llvm_unreachable("Invalid reference to overloaded function");
10425 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010426}
10427
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010428ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010429 DeclAccessPair Found,
10430 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010431 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010432}
10433
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010434} // end namespace clang