blob: 7ddb151e8a572aa73e9da66170ddfc49812457e2 [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() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000544 inherited::clear();
545 Functions.clear();
546}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
John McCall4124c492011-10-17 18:40:02 +0000548namespace {
549 class UnbridgedCastsSet {
550 struct Entry {
551 Expr **Addr;
552 Expr *Saved;
553 };
554 SmallVector<Entry, 2> Entries;
555
556 public:
557 void save(Sema &S, Expr *&E) {
558 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
559 Entry entry = { &E, E };
560 Entries.push_back(entry);
561 E = S.stripARCUnbridgedCast(E);
562 }
563
564 void restore() {
565 for (SmallVectorImpl<Entry>::iterator
566 i = Entries.begin(), e = Entries.end(); i != e; ++i)
567 *i->Addr = i->Saved;
568 }
569 };
570}
571
572/// checkPlaceholderForOverload - Do any interesting placeholder-like
573/// preprocessing on the given expression.
574///
575/// \param unbridgedCasts a collection to which to add unbridged casts;
576/// without this, they will be immediately diagnosed as errors
577///
578/// Return true on unrecoverable error.
579static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
580 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000581 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
582 // We can't handle overloaded expressions here because overload
583 // resolution might reasonably tweak them.
584 if (placeholder->getKind() == BuiltinType::Overload) return false;
585
586 // If the context potentially accepts unbridged ARC casts, strip
587 // the unbridged cast and add it to the collection for later restoration.
588 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
589 unbridgedCasts) {
590 unbridgedCasts->save(S, E);
591 return false;
592 }
593
594 // Go ahead and check everything else.
595 ExprResult result = S.CheckPlaceholderExpr(E);
596 if (result.isInvalid())
597 return true;
598
599 E = result.take();
600 return false;
601 }
602
603 // Nothing to do.
604 return false;
605}
606
607/// checkArgPlaceholdersForOverload - Check a set of call operands for
608/// placeholders.
609static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
610 unsigned numArgs,
611 UnbridgedCastsSet &unbridged) {
612 for (unsigned i = 0; i != numArgs; ++i)
613 if (checkPlaceholderForOverload(S, args[i], &unbridged))
614 return true;
615
616 return false;
617}
618
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000619// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000620// overload of the declarations in Old. This routine returns false if
621// New and Old cannot be overloaded, e.g., if New has the same
622// signature as some function in Old (C++ 1.3.10) or if the Old
623// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000624// it does return false, MatchedDecl will point to the decl that New
625// cannot be overloaded with. This decl may be a UsingShadowDecl on
626// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000627//
628// Example: Given the following input:
629//
630// void f(int, float); // #1
631// void f(int, int); // #2
632// int f(int, int); // #3
633//
634// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000635// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000636//
John McCall3d988d92009-12-02 08:47:38 +0000637// When we process #2, Old contains only the FunctionDecl for #1. By
638// comparing the parameter types, we see that #1 and #2 are overloaded
639// (since they have different signatures), so this routine returns
640// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000641//
John McCall3d988d92009-12-02 08:47:38 +0000642// When we process #3, Old is an overload set containing #1 and #2. We
643// compare the signatures of #3 to #1 (they're overloaded, so we do
644// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
645// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646// signature), IsOverload returns false and MatchedDecl will be set to
647// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000648//
649// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
650// into a class by a using declaration. The rules for whether to hide
651// shadow declarations ignore some properties which otherwise figure
652// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000653Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000654Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
655 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000656 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000657 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000658 NamedDecl *OldD = *I;
659
660 bool OldIsUsingDecl = false;
661 if (isa<UsingShadowDecl>(OldD)) {
662 OldIsUsingDecl = true;
663
664 // We can always introduce two using declarations into the same
665 // context, even if they have identical signatures.
666 if (NewIsUsingDecl) continue;
667
668 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
669 }
670
671 // If either declaration was introduced by a using declaration,
672 // we'll need to use slightly different rules for matching.
673 // Essentially, these rules are the normal rules, except that
674 // function templates hide function templates with different
675 // return types or template parameter lists.
676 bool UseMemberUsingDeclRules =
677 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
678
John McCall3d988d92009-12-02 08:47:38 +0000679 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000680 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
681 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
682 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
683 continue;
684 }
685
John McCalldaa3d6b2009-12-09 03:35:25 +0000686 Match = *I;
687 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000688 }
John McCall3d988d92009-12-02 08:47:38 +0000689 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000690 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
691 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
692 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
693 continue;
694 }
695
John McCalldaa3d6b2009-12-09 03:35:25 +0000696 Match = *I;
697 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000698 }
John McCalla8987a2942010-11-10 03:01:53 +0000699 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000700 // We can overload with these, which can show up when doing
701 // redeclaration checks for UsingDecls.
702 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000703 } else if (isa<TagDecl>(OldD)) {
704 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000705 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
706 // Optimistically assume that an unresolved using decl will
707 // overload; if it doesn't, we'll have to diagnose during
708 // template instantiation.
709 } else {
John McCall1f82f242009-11-18 22:49:29 +0000710 // (C++ 13p1):
711 // Only function declarations can be overloaded; object and type
712 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000713 Match = *I;
714 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000715 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000716 }
John McCall1f82f242009-11-18 22:49:29 +0000717
John McCalldaa3d6b2009-12-09 03:35:25 +0000718 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000719}
720
John McCalle9cccd82010-06-16 08:42:20 +0000721bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
722 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000723 // If both of the functions are extern "C", then they are not
724 // overloads.
725 if (Old->isExternC() && New->isExternC())
726 return false;
727
John McCall1f82f242009-11-18 22:49:29 +0000728 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
729 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
730
731 // C++ [temp.fct]p2:
732 // A function template can be overloaded with other function templates
733 // and with normal (non-template) functions.
734 if ((OldTemplate == 0) != (NewTemplate == 0))
735 return true;
736
737 // Is the function New an overload of the function Old?
738 QualType OldQType = Context.getCanonicalType(Old->getType());
739 QualType NewQType = Context.getCanonicalType(New->getType());
740
741 // Compare the signatures (C++ 1.3.10) of the two functions to
742 // determine whether they are overloads. If we find any mismatch
743 // in the signature, they are overloads.
744
745 // If either of these functions is a K&R-style function (no
746 // prototype), then we consider them to have matching signatures.
747 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
748 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
749 return false;
750
John McCall424cec92011-01-19 06:33:43 +0000751 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
752 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000753
754 // The signature of a function includes the types of its
755 // parameters (C++ 1.3.10), which includes the presence or absence
756 // of the ellipsis; see C++ DR 357).
757 if (OldQType != NewQType &&
758 (OldType->getNumArgs() != NewType->getNumArgs() ||
759 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000760 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000761 return true;
762
763 // C++ [temp.over.link]p4:
764 // The signature of a function template consists of its function
765 // signature, its return type and its template parameter list. The names
766 // of the template parameters are significant only for establishing the
767 // relationship between the template parameters and the rest of the
768 // signature.
769 //
770 // We check the return type and template parameter lists for function
771 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000772 //
773 // However, we don't consider either of these when deciding whether
774 // a member introduced by a shadow declaration is hidden.
775 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000776 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
777 OldTemplate->getTemplateParameters(),
778 false, TPL_TemplateMatch) ||
779 OldType->getResultType() != NewType->getResultType()))
780 return true;
781
782 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000783 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000784 //
785 // As part of this, also check whether one of the member functions
786 // is static, in which case they are not overloads (C++
787 // 13.1p2). While not part of the definition of the signature,
788 // this check is important to determine whether these functions
789 // can be overloaded.
790 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
791 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
792 if (OldMethod && NewMethod &&
793 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000794 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000795 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
796 if (!UseUsingDeclRules &&
797 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
798 (OldMethod->getRefQualifier() == RQ_None ||
799 NewMethod->getRefQualifier() == RQ_None)) {
800 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 // - Member function declarations with the same name and the same
802 // parameter-type-list as well as member function template
803 // declarations with the same name, the same parameter-type-list, and
804 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000805 // them, but not all, have a ref-qualifier (8.3.5).
806 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
807 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
808 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
John McCall1f82f242009-11-18 22:49:29 +0000811 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813
John McCall1f82f242009-11-18 22:49:29 +0000814 // The signatures match; this is not an overload.
815 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816}
817
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000818/// \brief Checks availability of the function depending on the current
819/// function context. Inside an unavailable function, unavailability is ignored.
820///
821/// \returns true if \arg FD is unavailable and current context is inside
822/// an available function, false otherwise.
823bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
824 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
825}
826
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000827/// TryImplicitConversion - Attempt to perform an implicit conversion
828/// from the given expression (Expr) to the given type (ToType). This
829/// function returns an implicit conversion sequence that can be used
830/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831///
832/// void f(float f);
833/// void g(int i) { f(i); }
834///
835/// this routine would produce an implicit conversion sequence to
836/// describe the initialization of f from i, which will be a standard
837/// conversion sequence containing an lvalue-to-rvalue conversion (C++
838/// 4.1) followed by a floating-integral conversion (C++ 4.9).
839//
840/// Note that this routine only determines how the conversion can be
841/// performed; it does not actually perform the conversion. As such,
842/// it will not produce any diagnostics if no conversion is available,
843/// but will instead return an implicit conversion sequence of kind
844/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000845///
846/// If @p SuppressUserConversions, then user-defined conversions are
847/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000848/// If @p AllowExplicit, then explicit user-defined conversions are
849/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000850///
851/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
852/// writeback conversion, which allows __autoreleasing id* parameters to
853/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000854static ImplicitConversionSequence
855TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
856 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000858 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000859 bool CStyle,
860 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000861 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000862 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000863 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000864 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000865 return ICS;
866 }
867
John McCall5c32be02010-08-24 20:38:10 +0000868 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000869 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000870 return ICS;
871 }
872
Douglas Gregor836a7e82010-08-11 02:15:33 +0000873 // C++ [over.ics.user]p4:
874 // A conversion of an expression of class type to the same class
875 // type is given Exact Match rank, and a conversion of an
876 // expression of class type to a base class of that type is
877 // given Conversion rank, in spite of the fact that a copy/move
878 // constructor (i.e., a user-defined conversion function) is
879 // called for those cases.
880 QualType FromType = From->getType();
881 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000882 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
883 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000884 ICS.setStandard();
885 ICS.Standard.setAsIdentityConversion();
886 ICS.Standard.setFromType(FromType);
887 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor5ab11652010-04-17 22:01:05 +0000889 // We don't actually check at this point whether there is a valid
890 // copy/move constructor, since overloading just assumes that it
891 // exists. When we actually perform initialization, we'll find the
892 // appropriate constructor to copy the returned object, if needed.
893 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894
Douglas Gregor5ab11652010-04-17 22:01:05 +0000895 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000896 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000897 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000898
Douglas Gregor836a7e82010-08-11 02:15:33 +0000899 return ICS;
900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901
Douglas Gregor836a7e82010-08-11 02:15:33 +0000902 if (SuppressUserConversions) {
903 // We're not in the case above, so there is no conversion that
904 // we can perform.
905 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000906 return ICS;
907 }
908
909 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000910 OverloadCandidateSet Conversions(From->getExprLoc());
911 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000912 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000913 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000914
915 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000916 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000917 // C++ [over.ics.user]p4:
918 // A conversion of an expression of class type to the same class
919 // type is given Exact Match rank, and a conversion of an
920 // expression of class type to a base class of that type is
921 // given Conversion rank, in spite of the fact that a copy
922 // constructor (i.e., a user-defined conversion function) is
923 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000924 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000925 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000926 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000927 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
928 QualType ToCanon
929 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000930 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000931 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000932 // Turn this into a "standard" conversion sequence, so that it
933 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000934 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000935 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000936 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000937 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000938 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000939 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000940 ICS.Standard.Second = ICK_Derived_To_Base;
941 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000942 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000943
944 // C++ [over.best.ics]p4:
945 // However, when considering the argument of a user-defined
946 // conversion function that is a candidate by 13.3.1.3 when
947 // invoked for the copying of the temporary in the second step
948 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
949 // 13.3.1.6 in all cases, only standard conversion sequences and
950 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000951 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000952 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000953 }
John McCalle8c8cd22010-01-13 22:30:33 +0000954 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000955 ICS.setAmbiguous();
956 ICS.Ambiguous.setFromType(From->getType());
957 ICS.Ambiguous.setToType(ToType);
958 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
959 Cand != Conversions.end(); ++Cand)
960 if (Cand->Viable)
961 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000962 } else {
John McCall65eb8792010-02-25 01:37:24 +0000963 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000964 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000965
966 return ICS;
967}
968
John McCall31168b02011-06-15 23:02:42 +0000969ImplicitConversionSequence
970Sema::TryImplicitConversion(Expr *From, QualType ToType,
971 bool SuppressUserConversions,
972 bool AllowExplicit,
973 bool InOverloadResolution,
974 bool CStyle,
975 bool AllowObjCWritebackConversion) {
976 return clang::TryImplicitConversion(*this, From, ToType,
977 SuppressUserConversions, AllowExplicit,
978 InOverloadResolution, CStyle,
979 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000980}
981
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000982/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000983/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000984/// converted expression. Flavor is the kind of conversion we're
985/// performing, used in the error message. If @p AllowExplicit,
986/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000987ExprResult
988Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +0000989 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000990 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +0000991 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000992}
993
John Wiegley01296292011-04-08 18:41:53 +0000994ExprResult
995Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000996 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +0000997 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +0000998 if (checkPlaceholderForOverload(*this, From))
999 return ExprError();
1000
John McCall31168b02011-06-15 23:02:42 +00001001 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1002 bool AllowObjCWritebackConversion
1003 = getLangOptions().ObjCAutoRefCount &&
1004 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001005
John McCall5c32be02010-08-24 20:38:10 +00001006 ICS = clang::TryImplicitConversion(*this, From, ToType,
1007 /*SuppressUserConversions=*/false,
1008 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001009 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001010 /*CStyle=*/false,
1011 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001012 return PerformImplicitConversion(From, ToType, ICS, Action);
1013}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001014
1015/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001016/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001017bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1018 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001019 if (Context.hasSameUnqualifiedType(FromType, ToType))
1020 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
John McCall991eb4b2010-12-21 00:44:39 +00001022 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1023 // where F adds one of the following at most once:
1024 // - a pointer
1025 // - a member pointer
1026 // - a block pointer
1027 CanQualType CanTo = Context.getCanonicalType(ToType);
1028 CanQualType CanFrom = Context.getCanonicalType(FromType);
1029 Type::TypeClass TyClass = CanTo->getTypeClass();
1030 if (TyClass != CanFrom->getTypeClass()) return false;
1031 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1032 if (TyClass == Type::Pointer) {
1033 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1034 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1035 } else if (TyClass == Type::BlockPointer) {
1036 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1037 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1038 } else if (TyClass == Type::MemberPointer) {
1039 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1040 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1041 } else {
1042 return false;
1043 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001044
John McCall991eb4b2010-12-21 00:44:39 +00001045 TyClass = CanTo->getTypeClass();
1046 if (TyClass != CanFrom->getTypeClass()) return false;
1047 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1048 return false;
1049 }
1050
1051 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1052 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1053 if (!EInfo.getNoReturn()) return false;
1054
1055 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1056 assert(QualType(FromFn, 0).isCanonical());
1057 if (QualType(FromFn, 0) != CanTo) return false;
1058
1059 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001060 return true;
1061}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062
Douglas Gregor46188682010-05-18 22:42:18 +00001063/// \brief Determine whether the conversion from FromType to ToType is a valid
1064/// vector conversion.
1065///
1066/// \param ICK Will be set to the vector conversion kind, if this is a vector
1067/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1069 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001070 // We need at least one of these types to be a vector type to have a vector
1071 // conversion.
1072 if (!ToType->isVectorType() && !FromType->isVectorType())
1073 return false;
1074
1075 // Identical types require no conversions.
1076 if (Context.hasSameUnqualifiedType(FromType, ToType))
1077 return false;
1078
1079 // There are no conversions between extended vector types, only identity.
1080 if (ToType->isExtVectorType()) {
1081 // There are no conversions between extended vector types other than the
1082 // identity conversion.
1083 if (FromType->isExtVectorType())
1084 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085
Douglas Gregor46188682010-05-18 22:42:18 +00001086 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001087 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001088 ICK = ICK_Vector_Splat;
1089 return true;
1090 }
1091 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001092
1093 // We can perform the conversion between vector types in the following cases:
1094 // 1)vector types are equivalent AltiVec and GCC vector types
1095 // 2)lax vector conversions are permitted and the vector types are of the
1096 // same size
1097 if (ToType->isVectorType() && FromType->isVectorType()) {
1098 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001099 (Context.getLangOptions().LaxVectorConversions &&
1100 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001101 ICK = ICK_Vector_Conversion;
1102 return true;
1103 }
Douglas Gregor46188682010-05-18 22:42:18 +00001104 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001105
Douglas Gregor46188682010-05-18 22:42:18 +00001106 return false;
1107}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001109/// IsStandardConversion - Determines whether there is a standard
1110/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1111/// expression From to the type ToType. Standard conversion sequences
1112/// only consider non-class types; for conversions that involve class
1113/// types, use TryImplicitConversion. If a conversion exists, SCS will
1114/// contain the standard conversion sequence required to perform this
1115/// conversion and this routine will return true. Otherwise, this
1116/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001117static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1118 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001119 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001120 bool CStyle,
1121 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001124 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001125 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001126 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001127 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001128 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001129 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001131 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001132 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001133 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001134 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001135 return false;
1136
Mike Stump11289f42009-09-09 15:08:12 +00001137 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001138 }
1139
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 // The first conversion can be an lvalue-to-rvalue conversion,
1141 // array-to-pointer conversion, or function-to-pointer conversion
1142 // (C++ 4p1).
1143
John McCall5c32be02010-08-24 20:38:10 +00001144 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001145 DeclAccessPair AccessPair;
1146 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001147 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001148 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001149 // We were able to resolve the address of the overloaded function,
1150 // so we can convert to the type of that function.
1151 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001152
1153 // we can sometimes resolve &foo<int> regardless of ToType, so check
1154 // if the type matches (identity) or we are converting to bool
1155 if (!S.Context.hasSameUnqualifiedType(
1156 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1157 QualType resultTy;
1158 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001159 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001160 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1161 // otherwise, only a boolean conversion is standard
1162 if (!ToType->isBooleanType())
1163 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165
Chandler Carruthffce2452011-03-29 08:08:18 +00001166 // Check if the "from" expression is taking the address of an overloaded
1167 // function and recompute the FromType accordingly. Take advantage of the
1168 // fact that non-static member functions *must* have such an address-of
1169 // expression.
1170 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1171 if (Method && !Method->isStatic()) {
1172 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1173 "Non-unary operator on non-static member address");
1174 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1175 == UO_AddrOf &&
1176 "Non-address-of operator on non-static member address");
1177 const Type *ClassType
1178 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1179 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001180 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1181 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1182 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001183 "Non-address-of operator for overloaded function expression");
1184 FromType = S.Context.getPointerType(FromType);
1185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186
Douglas Gregor980fb162010-04-29 18:24:40 +00001187 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001188 assert(S.Context.hasSameType(
1189 FromType,
1190 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001191 } else {
1192 return false;
1193 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001194 }
John McCall154a2fd2011-08-30 00:57:29 +00001195 // Lvalue-to-rvalue conversion (C++11 4.1):
1196 // A glvalue (3.10) of a non-function, non-array type T can
1197 // be converted to a prvalue.
1198 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001199 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001200 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001201 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001202 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203
1204 // If T is a non-class type, the type of the rvalue is the
1205 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001206 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1207 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001208 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001209 } else if (FromType->isArrayType()) {
1210 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001211 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001212
1213 // An lvalue or rvalue of type "array of N T" or "array of unknown
1214 // bound of T" can be converted to an rvalue of type "pointer to
1215 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001216 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217
John McCall5c32be02010-08-24 20:38:10 +00001218 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001219 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001220 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001221
1222 // For the purpose of ranking in overload resolution
1223 // (13.3.3.1.1), this conversion is considered an
1224 // array-to-pointer conversion followed by a qualification
1225 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001226 SCS.Second = ICK_Identity;
1227 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001228 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001229 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001230 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231 }
John McCall086a4642010-11-24 05:12:34 +00001232 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001233 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001234 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235
1236 // An lvalue of function type T can be converted to an rvalue of
1237 // type "pointer to T." The result is a pointer to the
1238 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001239 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001240 } else {
1241 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001242 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001243 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001244 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001245
1246 // The second conversion can be an integral promotion, floating
1247 // point promotion, integral conversion, floating point conversion,
1248 // floating-integral conversion, pointer conversion,
1249 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001250 // For overloading in C, this can also be a "compatible-type"
1251 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001252 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001253 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001254 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001255 // The unqualified versions of the types are the same: there's no
1256 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001257 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001258 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001259 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001260 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001261 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001262 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001263 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001264 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001265 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001266 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001267 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001268 SCS.Second = ICK_Complex_Promotion;
1269 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001270 } else if (ToType->isBooleanType() &&
1271 (FromType->isArithmeticType() ||
1272 FromType->isAnyPointerType() ||
1273 FromType->isBlockPointerType() ||
1274 FromType->isMemberPointerType() ||
1275 FromType->isNullPtrType())) {
1276 // Boolean conversions (C++ 4.12).
1277 SCS.Second = ICK_Boolean_Conversion;
1278 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001279 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001280 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001281 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001282 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001283 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001284 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001285 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001286 SCS.Second = ICK_Complex_Conversion;
1287 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001288 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1289 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001290 // Complex-real conversions (C99 6.3.1.7)
1291 SCS.Second = ICK_Complex_Real;
1292 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001293 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001294 // Floating point conversions (C++ 4.8).
1295 SCS.Second = ICK_Floating_Conversion;
1296 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001298 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001299 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001300 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001301 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001302 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001303 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001304 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001305 SCS.Second = ICK_Block_Pointer_Conversion;
1306 } else if (AllowObjCWritebackConversion &&
1307 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1308 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001309 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1310 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001311 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001312 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001313 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001314 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001316 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001317 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001318 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001319 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001320 SCS.Second = SecondICK;
1321 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001322 } else if (!S.getLangOptions().CPlusPlus &&
1323 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001324 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001325 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001326 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001327 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001328 // Treat a conversion that strips "noreturn" as an identity conversion.
1329 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001330 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1331 InOverloadResolution,
1332 SCS, CStyle)) {
1333 SCS.Second = ICK_TransparentUnionConversion;
1334 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001335 } else {
1336 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001337 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001339 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001340
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001341 QualType CanonFrom;
1342 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001343 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001344 bool ObjCLifetimeConversion;
1345 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1346 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001347 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001348 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001350 CanonFrom = S.Context.getCanonicalType(FromType);
1351 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001352 } else {
1353 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001354 SCS.Third = ICK_Identity;
1355
Mike Stump11289f42009-09-09 15:08:12 +00001356 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001357 // [...] Any difference in top-level cv-qualification is
1358 // subsumed by the initialization itself and does not constitute
1359 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001360 CanonFrom = S.Context.getCanonicalType(FromType);
1361 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001362 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001363 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001364 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001365 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1366 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001367 FromType = ToType;
1368 CanonFrom = CanonTo;
1369 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001370 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001371 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001372
1373 // If we have not converted the argument type to the parameter type,
1374 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001375 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001376 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001377
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001378 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001379}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001380
1381static bool
1382IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1383 QualType &ToType,
1384 bool InOverloadResolution,
1385 StandardConversionSequence &SCS,
1386 bool CStyle) {
1387
1388 const RecordType *UT = ToType->getAsUnionType();
1389 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1390 return false;
1391 // The field to initialize within the transparent union.
1392 RecordDecl *UD = UT->getDecl();
1393 // It's compatible if the expression matches any of the fields.
1394 for (RecordDecl::field_iterator it = UD->field_begin(),
1395 itend = UD->field_end();
1396 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001397 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1398 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001399 ToType = it->getType();
1400 return true;
1401 }
1402 }
1403 return false;
1404}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001405
1406/// IsIntegralPromotion - Determines whether the conversion from the
1407/// expression From (whose potentially-adjusted type is FromType) to
1408/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1409/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001410bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001411 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001412 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001413 if (!To) {
1414 return false;
1415 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001416
1417 // An rvalue of type char, signed char, unsigned char, short int, or
1418 // unsigned short int can be converted to an rvalue of type int if
1419 // int can represent all the values of the source type; otherwise,
1420 // the source rvalue can be converted to an rvalue of type unsigned
1421 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001422 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1423 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424 if (// We can promote any signed, promotable integer type to an int
1425 (FromType->isSignedIntegerType() ||
1426 // We can promote any unsigned integer type whose size is
1427 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001428 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001429 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001430 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001431 }
1432
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001433 return To->getKind() == BuiltinType::UInt;
1434 }
1435
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001436 // C++0x [conv.prom]p3:
1437 // A prvalue of an unscoped enumeration type whose underlying type is not
1438 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1439 // following types that can represent all the values of the enumeration
1440 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1441 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001442 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001443 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001444 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001445 // with lowest integer conversion rank (4.13) greater than the rank of long
1446 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001447 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001448 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1449 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1450 // provided for a scoped enumeration.
1451 if (FromEnumType->getDecl()->isScoped())
1452 return false;
1453
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001454 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001455 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001456 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001457 return Context.hasSameUnqualifiedType(ToType,
1458 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001459 }
John McCall56774992009-12-09 09:09:27 +00001460
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001461 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1463 // to an rvalue a prvalue of the first of the following types that can
1464 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001465 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001467 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001469 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001471 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001472 // Determine whether the type we're converting from is signed or
1473 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001474 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001475 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001477 // The types we'll try to promote to, in the appropriate
1478 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001479 QualType PromoteTypes[6] = {
1480 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001481 Context.LongTy, Context.UnsignedLongTy ,
1482 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001483 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001484 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1486 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001487 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1489 // We found the type that we can promote to. If this is the
1490 // type we wanted, we have a promotion. Otherwise, no
1491 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001492 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001493 }
1494 }
1495 }
1496
1497 // An rvalue for an integral bit-field (9.6) can be converted to an
1498 // rvalue of type int if int can represent all the values of the
1499 // bit-field; otherwise, it can be converted to unsigned int if
1500 // unsigned int can represent all the values of the bit-field. If
1501 // the bit-field is larger yet, no integral promotion applies to
1502 // it. If the bit-field has an enumerated type, it is treated as any
1503 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001504 // FIXME: We should delay checking of bit-fields until we actually perform the
1505 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001506 using llvm::APSInt;
1507 if (From)
1508 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001509 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001510 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001511 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1512 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1513 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001514
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001515 // Are we promoting to an int from a bitfield that fits in an int?
1516 if (BitWidth < ToSize ||
1517 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1518 return To->getKind() == BuiltinType::Int;
1519 }
Mike Stump11289f42009-09-09 15:08:12 +00001520
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001521 // Are we promoting to an unsigned int from an unsigned bitfield
1522 // that fits into an unsigned int?
1523 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1524 return To->getKind() == BuiltinType::UInt;
1525 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001527 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001528 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529 }
Mike Stump11289f42009-09-09 15:08:12 +00001530
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 // An rvalue of type bool can be converted to an rvalue of type int,
1532 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001533 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001534 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001535 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001536
1537 return false;
1538}
1539
1540/// IsFloatingPointPromotion - Determines whether the conversion from
1541/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1542/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001543bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001544 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1545 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001546 /// An rvalue of type float can be converted to an rvalue of type
1547 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001548 if (FromBuiltin->getKind() == BuiltinType::Float &&
1549 ToBuiltin->getKind() == BuiltinType::Double)
1550 return true;
1551
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001552 // C99 6.3.1.5p1:
1553 // When a float is promoted to double or long double, or a
1554 // double is promoted to long double [...].
1555 if (!getLangOptions().CPlusPlus &&
1556 (FromBuiltin->getKind() == BuiltinType::Float ||
1557 FromBuiltin->getKind() == BuiltinType::Double) &&
1558 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1559 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001560
1561 // Half can be promoted to float.
1562 if (FromBuiltin->getKind() == BuiltinType::Half &&
1563 ToBuiltin->getKind() == BuiltinType::Float)
1564 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001565 }
1566
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 return false;
1568}
1569
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001570/// \brief Determine if a conversion is a complex promotion.
1571///
1572/// A complex promotion is defined as a complex -> complex conversion
1573/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001574/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001575bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001576 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001577 if (!FromComplex)
1578 return false;
1579
John McCall9dd450b2009-09-21 23:43:11 +00001580 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001581 if (!ToComplex)
1582 return false;
1583
1584 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001585 ToComplex->getElementType()) ||
1586 IsIntegralPromotion(0, FromComplex->getElementType(),
1587 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001588}
1589
Douglas Gregor237f96c2008-11-26 23:31:11 +00001590/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1591/// the pointer type FromPtr to a pointer to type ToPointee, with the
1592/// same type qualifiers as FromPtr has on its pointee type. ToType,
1593/// if non-empty, will be a pointer to ToType that may or may not have
1594/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001595///
Mike Stump11289f42009-09-09 15:08:12 +00001596static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001597BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001598 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001599 ASTContext &Context,
1600 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001601 assert((FromPtr->getTypeClass() == Type::Pointer ||
1602 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1603 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001604
John McCall31168b02011-06-15 23:02:42 +00001605 /// Conversions to 'id' subsume cv-qualifier conversions.
1606 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001607 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001608
1609 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001610 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001611 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001612 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001613
John McCall31168b02011-06-15 23:02:42 +00001614 if (StripObjCLifetime)
1615 Quals.removeObjCLifetime();
1616
Mike Stump11289f42009-09-09 15:08:12 +00001617 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001618 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001619 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001620 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001621 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001622
1623 // Build a pointer to ToPointee. It has the right qualifiers
1624 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001625 if (isa<ObjCObjectPointerType>(ToType))
1626 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001627 return Context.getPointerType(ToPointee);
1628 }
1629
1630 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001631 QualType QualifiedCanonToPointee
1632 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001633
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001634 if (isa<ObjCObjectPointerType>(ToType))
1635 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1636 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001637}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638
Mike Stump11289f42009-09-09 15:08:12 +00001639static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001640 bool InOverloadResolution,
1641 ASTContext &Context) {
1642 // Handle value-dependent integral null pointer constants correctly.
1643 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1644 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001645 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001646 return !InOverloadResolution;
1647
Douglas Gregor56751b52009-09-25 04:25:58 +00001648 return Expr->isNullPointerConstant(Context,
1649 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1650 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001651}
Mike Stump11289f42009-09-09 15:08:12 +00001652
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001653/// IsPointerConversion - Determines whether the conversion of the
1654/// expression From, which has the (possibly adjusted) type FromType,
1655/// can be converted to the type ToType via a pointer conversion (C++
1656/// 4.10). If so, returns true and places the converted type (that
1657/// might differ from ToType in its cv-qualifiers at some level) into
1658/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001659///
Douglas Gregora29dc052008-11-27 01:19:21 +00001660/// This routine also supports conversions to and from block pointers
1661/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1662/// pointers to interfaces. FIXME: Once we've determined the
1663/// appropriate overloading rules for Objective-C, we may want to
1664/// split the Objective-C checks into a different routine; however,
1665/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001666/// conversions, so for now they live here. IncompatibleObjC will be
1667/// set if the conversion is an allowed Objective-C conversion that
1668/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001670 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001671 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001672 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001673 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001674 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1675 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001676 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001677
Mike Stump11289f42009-09-09 15:08:12 +00001678 // Conversion from a null pointer constant to any Objective-C pointer type.
1679 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001680 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001681 ConvertedType = ToType;
1682 return true;
1683 }
1684
Douglas Gregor231d1c62008-11-27 00:15:41 +00001685 // Blocks: Block pointers can be converted to void*.
1686 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001687 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001688 ConvertedType = ToType;
1689 return true;
1690 }
1691 // Blocks: A null pointer constant can be converted to a block
1692 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001693 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001694 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001695 ConvertedType = ToType;
1696 return true;
1697 }
1698
Sebastian Redl576fd422009-05-10 18:38:11 +00001699 // If the left-hand-side is nullptr_t, the right side can be a null
1700 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001702 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001703 ConvertedType = ToType;
1704 return true;
1705 }
1706
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001707 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 if (!ToTypePtr)
1709 return false;
1710
1711 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001712 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 ConvertedType = ToType;
1714 return true;
1715 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001716
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001718 // , including objective-c pointers.
1719 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001720 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1721 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001722 ConvertedType = BuildSimilarlyQualifiedPointerType(
1723 FromType->getAs<ObjCObjectPointerType>(),
1724 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001725 ToType, Context);
1726 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001727 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001728 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001729 if (!FromTypePtr)
1730 return false;
1731
1732 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001733
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001735 // pointer conversion, so don't do all of the work below.
1736 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1737 return false;
1738
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739 // An rvalue of type "pointer to cv T," where T is an object type,
1740 // can be converted to an rvalue of type "pointer to cv void" (C++
1741 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001742 if (FromPointeeType->isIncompleteOrObjectType() &&
1743 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001744 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001745 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001746 ToType, Context,
1747 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 return true;
1749 }
1750
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001751 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001752 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001753 ToPointeeType->isVoidType()) {
1754 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1755 ToPointeeType,
1756 ToType, Context);
1757 return true;
1758 }
1759
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001760 // When we're overloading in C, we allow a special kind of pointer
1761 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001762 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001763 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001764 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001765 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001766 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001767 return true;
1768 }
1769
Douglas Gregor5c407d92008-10-23 00:40:37 +00001770 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001771 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001772 // An rvalue of type "pointer to cv D," where D is a class type,
1773 // can be converted to an rvalue of type "pointer to cv B," where
1774 // B is a base class (clause 10) of D. If B is an inaccessible
1775 // (clause 11) or ambiguous (10.2) base class of D, a program that
1776 // necessitates this conversion is ill-formed. The result of the
1777 // conversion is a pointer to the base class sub-object of the
1778 // derived class object. The null pointer value is converted to
1779 // the null pointer value of the destination type.
1780 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001781 // Note that we do not check for ambiguity or inaccessibility
1782 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001783 if (getLangOptions().CPlusPlus &&
1784 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001785 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001786 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001787 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001788 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001789 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001790 ToType, Context);
1791 return true;
1792 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001793
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001794 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1795 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1796 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1797 ToPointeeType,
1798 ToType, Context);
1799 return true;
1800 }
1801
Douglas Gregora119f102008-12-19 19:13:09 +00001802 return false;
1803}
Douglas Gregoraec25842011-04-26 23:16:46 +00001804
1805/// \brief Adopt the given qualifiers for the given type.
1806static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1807 Qualifiers TQs = T.getQualifiers();
1808
1809 // Check whether qualifiers already match.
1810 if (TQs == Qs)
1811 return T;
1812
1813 if (Qs.compatiblyIncludes(TQs))
1814 return Context.getQualifiedType(T, Qs);
1815
1816 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1817}
Douglas Gregora119f102008-12-19 19:13:09 +00001818
1819/// isObjCPointerConversion - Determines whether this is an
1820/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1821/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001822bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001823 QualType& ConvertedType,
1824 bool &IncompatibleObjC) {
1825 if (!getLangOptions().ObjC1)
1826 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001827
Douglas Gregoraec25842011-04-26 23:16:46 +00001828 // The set of qualifiers on the type we're converting from.
1829 Qualifiers FromQualifiers = FromType.getQualifiers();
1830
Steve Naroff7cae42b2009-07-10 23:34:53 +00001831 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001832 const ObjCObjectPointerType* ToObjCPtr =
1833 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001834 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001835 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001836
Steve Naroff7cae42b2009-07-10 23:34:53 +00001837 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001838 // If the pointee types are the same (ignoring qualifications),
1839 // then this is not a pointer conversion.
1840 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1841 FromObjCPtr->getPointeeType()))
1842 return false;
1843
Douglas Gregoraec25842011-04-26 23:16:46 +00001844 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001845 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001846 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001847 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001848 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001849 return true;
1850 }
1851 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001852 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001853 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001854 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001855 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001856 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001857 return true;
1858 }
1859 // Objective C++: We're able to convert from a pointer to an
1860 // interface to a pointer to a different interface.
1861 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001862 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1863 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1864 if (getLangOptions().CPlusPlus && LHS && RHS &&
1865 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1866 FromObjCPtr->getPointeeType()))
1867 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001869 ToObjCPtr->getPointeeType(),
1870 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001871 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001872 return true;
1873 }
1874
1875 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1876 // Okay: this is some kind of implicit downcast of Objective-C
1877 // interfaces, which is permitted. However, we're going to
1878 // complain about it.
1879 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001880 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001881 ToObjCPtr->getPointeeType(),
1882 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001883 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001884 return true;
1885 }
Mike Stump11289f42009-09-09 15:08:12 +00001886 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001887 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001888 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001889 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001890 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001892 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001893 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001894 // to a block pointer type.
1895 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001896 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001897 return true;
1898 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001899 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001902 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001904 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001905 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001906 return true;
1907 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001908 else
Douglas Gregora119f102008-12-19 19:13:09 +00001909 return false;
1910
Douglas Gregor033f56d2008-12-23 00:53:59 +00001911 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001912 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001913 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001914 else if (const BlockPointerType *FromBlockPtr =
1915 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001916 FromPointeeType = FromBlockPtr->getPointeeType();
1917 else
Douglas Gregora119f102008-12-19 19:13:09 +00001918 return false;
1919
Douglas Gregora119f102008-12-19 19:13:09 +00001920 // If we have pointers to pointers, recursively check whether this
1921 // is an Objective-C conversion.
1922 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1923 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1924 IncompatibleObjC)) {
1925 // We always complain about this conversion.
1926 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001927 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001928 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001929 return true;
1930 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001931 // Allow conversion of pointee being objective-c pointer to another one;
1932 // as in I* to id.
1933 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1934 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1935 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1936 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001937
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001938 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001939 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001940 return true;
1941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001942
Douglas Gregor033f56d2008-12-23 00:53:59 +00001943 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001944 // differences in the argument and result types are in Objective-C
1945 // pointer conversions. If so, we permit the conversion (but
1946 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001947 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001948 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001949 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001950 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001951 if (FromFunctionType && ToFunctionType) {
1952 // If the function types are exactly the same, this isn't an
1953 // Objective-C pointer conversion.
1954 if (Context.getCanonicalType(FromPointeeType)
1955 == Context.getCanonicalType(ToPointeeType))
1956 return false;
1957
1958 // Perform the quick checks that will tell us whether these
1959 // function types are obviously different.
1960 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1961 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1962 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1963 return false;
1964
1965 bool HasObjCConversion = false;
1966 if (Context.getCanonicalType(FromFunctionType->getResultType())
1967 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1968 // Okay, the types match exactly. Nothing to do.
1969 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1970 ToFunctionType->getResultType(),
1971 ConvertedType, IncompatibleObjC)) {
1972 // Okay, we have an Objective-C pointer conversion.
1973 HasObjCConversion = true;
1974 } else {
1975 // Function types are too different. Abort.
1976 return false;
1977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregora119f102008-12-19 19:13:09 +00001979 // Check argument types.
1980 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1981 ArgIdx != NumArgs; ++ArgIdx) {
1982 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1983 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1984 if (Context.getCanonicalType(FromArgType)
1985 == Context.getCanonicalType(ToArgType)) {
1986 // Okay, the types match exactly. Nothing to do.
1987 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1988 ConvertedType, IncompatibleObjC)) {
1989 // Okay, we have an Objective-C pointer conversion.
1990 HasObjCConversion = true;
1991 } else {
1992 // Argument types are too different. Abort.
1993 return false;
1994 }
1995 }
1996
1997 if (HasObjCConversion) {
1998 // We had an Objective-C conversion. Allow this pointer
1999 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002000 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002001 IncompatibleObjC = true;
2002 return true;
2003 }
2004 }
2005
Sebastian Redl72b597d2009-01-25 19:43:20 +00002006 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002007}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
John McCall31168b02011-06-15 23:02:42 +00002009/// \brief Determine whether this is an Objective-C writeback conversion,
2010/// used for parameter passing when performing automatic reference counting.
2011///
2012/// \param FromType The type we're converting form.
2013///
2014/// \param ToType The type we're converting to.
2015///
2016/// \param ConvertedType The type that will be produced after applying
2017/// this conversion.
2018bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2019 QualType &ConvertedType) {
2020 if (!getLangOptions().ObjCAutoRefCount ||
2021 Context.hasSameUnqualifiedType(FromType, ToType))
2022 return false;
2023
2024 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2025 QualType ToPointee;
2026 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2027 ToPointee = ToPointer->getPointeeType();
2028 else
2029 return false;
2030
2031 Qualifiers ToQuals = ToPointee.getQualifiers();
2032 if (!ToPointee->isObjCLifetimeType() ||
2033 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2034 !ToQuals.withoutObjCGLifetime().empty())
2035 return false;
2036
2037 // Argument must be a pointer to __strong to __weak.
2038 QualType FromPointee;
2039 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2040 FromPointee = FromPointer->getPointeeType();
2041 else
2042 return false;
2043
2044 Qualifiers FromQuals = FromPointee.getQualifiers();
2045 if (!FromPointee->isObjCLifetimeType() ||
2046 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2047 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2048 return false;
2049
2050 // Make sure that we have compatible qualifiers.
2051 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2052 if (!ToQuals.compatiblyIncludes(FromQuals))
2053 return false;
2054
2055 // Remove qualifiers from the pointee type we're converting from; they
2056 // aren't used in the compatibility check belong, and we'll be adding back
2057 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2058 FromPointee = FromPointee.getUnqualifiedType();
2059
2060 // The unqualified form of the pointee types must be compatible.
2061 ToPointee = ToPointee.getUnqualifiedType();
2062 bool IncompatibleObjC;
2063 if (Context.typesAreCompatible(FromPointee, ToPointee))
2064 FromPointee = ToPointee;
2065 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2066 IncompatibleObjC))
2067 return false;
2068
2069 /// \brief Construct the type we're converting to, which is a pointer to
2070 /// __autoreleasing pointee.
2071 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2072 ConvertedType = Context.getPointerType(FromPointee);
2073 return true;
2074}
2075
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002076bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2077 QualType& ConvertedType) {
2078 QualType ToPointeeType;
2079 if (const BlockPointerType *ToBlockPtr =
2080 ToType->getAs<BlockPointerType>())
2081 ToPointeeType = ToBlockPtr->getPointeeType();
2082 else
2083 return false;
2084
2085 QualType FromPointeeType;
2086 if (const BlockPointerType *FromBlockPtr =
2087 FromType->getAs<BlockPointerType>())
2088 FromPointeeType = FromBlockPtr->getPointeeType();
2089 else
2090 return false;
2091 // We have pointer to blocks, check whether the only
2092 // differences in the argument and result types are in Objective-C
2093 // pointer conversions. If so, we permit the conversion.
2094
2095 const FunctionProtoType *FromFunctionType
2096 = FromPointeeType->getAs<FunctionProtoType>();
2097 const FunctionProtoType *ToFunctionType
2098 = ToPointeeType->getAs<FunctionProtoType>();
2099
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002100 if (!FromFunctionType || !ToFunctionType)
2101 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002102
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002103 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002104 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002105
2106 // Perform the quick checks that will tell us whether these
2107 // function types are obviously different.
2108 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2109 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2110 return false;
2111
2112 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2113 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2114 if (FromEInfo != ToEInfo)
2115 return false;
2116
2117 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002118 if (Context.hasSameType(FromFunctionType->getResultType(),
2119 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002120 // Okay, the types match exactly. Nothing to do.
2121 } else {
2122 QualType RHS = FromFunctionType->getResultType();
2123 QualType LHS = ToFunctionType->getResultType();
2124 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2125 !RHS.hasQualifiers() && LHS.hasQualifiers())
2126 LHS = LHS.getUnqualifiedType();
2127
2128 if (Context.hasSameType(RHS,LHS)) {
2129 // OK exact match.
2130 } else if (isObjCPointerConversion(RHS, LHS,
2131 ConvertedType, IncompatibleObjC)) {
2132 if (IncompatibleObjC)
2133 return false;
2134 // Okay, we have an Objective-C pointer conversion.
2135 }
2136 else
2137 return false;
2138 }
2139
2140 // Check argument types.
2141 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2142 ArgIdx != NumArgs; ++ArgIdx) {
2143 IncompatibleObjC = false;
2144 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2145 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2146 if (Context.hasSameType(FromArgType, ToArgType)) {
2147 // Okay, the types match exactly. Nothing to do.
2148 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2149 ConvertedType, IncompatibleObjC)) {
2150 if (IncompatibleObjC)
2151 return false;
2152 // Okay, we have an Objective-C pointer conversion.
2153 } else
2154 // Argument types are too different. Abort.
2155 return false;
2156 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002157 if (LangOpts.ObjCAutoRefCount &&
2158 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2159 ToFunctionType))
2160 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002161
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002162 ConvertedType = ToType;
2163 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002164}
2165
Richard Trieucaff2472011-11-23 22:32:32 +00002166enum {
2167 ft_default,
2168 ft_different_class,
2169 ft_parameter_arity,
2170 ft_parameter_mismatch,
2171 ft_return_type,
2172 ft_qualifer_mismatch
2173};
2174
2175/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2176/// function types. Catches different number of parameter, mismatch in
2177/// parameter types, and different return types.
2178void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2179 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002180 // If either type is not valid, include no extra info.
2181 if (FromType.isNull() || ToType.isNull()) {
2182 PDiag << ft_default;
2183 return;
2184 }
2185
Richard Trieucaff2472011-11-23 22:32:32 +00002186 // Get the function type from the pointers.
2187 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2188 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2189 *ToMember = ToType->getAs<MemberPointerType>();
2190 if (FromMember->getClass() != ToMember->getClass()) {
2191 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2192 << QualType(FromMember->getClass(), 0);
2193 return;
2194 }
2195 FromType = FromMember->getPointeeType();
2196 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002197 }
2198
Richard Trieu96ed5b62011-12-13 23:19:45 +00002199 if (FromType->isPointerType())
2200 FromType = FromType->getPointeeType();
2201 if (ToType->isPointerType())
2202 ToType = ToType->getPointeeType();
2203
2204 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002205 FromType = FromType.getNonReferenceType();
2206 ToType = ToType.getNonReferenceType();
2207
Richard Trieucaff2472011-11-23 22:32:32 +00002208 // Don't print extra info for non-specialized template functions.
2209 if (FromType->isInstantiationDependentType() &&
2210 !FromType->getAs<TemplateSpecializationType>()) {
2211 PDiag << ft_default;
2212 return;
2213 }
2214
Richard Trieu96ed5b62011-12-13 23:19:45 +00002215 // No extra info for same types.
2216 if (Context.hasSameType(FromType, ToType)) {
2217 PDiag << ft_default;
2218 return;
2219 }
2220
Richard Trieucaff2472011-11-23 22:32:32 +00002221 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2222 *ToFunction = ToType->getAs<FunctionProtoType>();
2223
2224 // Both types need to be function types.
2225 if (!FromFunction || !ToFunction) {
2226 PDiag << ft_default;
2227 return;
2228 }
2229
2230 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2231 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2232 << FromFunction->getNumArgs();
2233 return;
2234 }
2235
2236 // Handle different parameter types.
2237 unsigned ArgPos;
2238 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2239 PDiag << ft_parameter_mismatch << ArgPos + 1
2240 << ToFunction->getArgType(ArgPos)
2241 << FromFunction->getArgType(ArgPos);
2242 return;
2243 }
2244
2245 // Handle different return type.
2246 if (!Context.hasSameType(FromFunction->getResultType(),
2247 ToFunction->getResultType())) {
2248 PDiag << ft_return_type << ToFunction->getResultType()
2249 << FromFunction->getResultType();
2250 return;
2251 }
2252
2253 unsigned FromQuals = FromFunction->getTypeQuals(),
2254 ToQuals = ToFunction->getTypeQuals();
2255 if (FromQuals != ToQuals) {
2256 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2257 return;
2258 }
2259
2260 // Unable to find a difference, so add no extra info.
2261 PDiag << ft_default;
2262}
2263
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002264/// FunctionArgTypesAreEqual - This routine checks two function proto types
2265/// for equlity of their argument types. Caller has already checked that
2266/// they have same number of arguments. This routine assumes that Objective-C
2267/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002268/// If the parameters are different, ArgPos will have the the parameter index
2269/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002270bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002271 const FunctionProtoType *NewType,
2272 unsigned *ArgPos) {
2273 if (!getLangOptions().ObjC1) {
2274 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2275 N = NewType->arg_type_begin(),
2276 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2277 if (!Context.hasSameType(*O, *N)) {
2278 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2279 return false;
2280 }
2281 }
2282 return true;
2283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002284
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002285 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2286 N = NewType->arg_type_begin(),
2287 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2288 QualType ToType = (*O);
2289 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002290 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002291 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2292 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002293 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2294 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2295 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2296 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002297 continue;
2298 }
John McCall8b07ec22010-05-15 11:32:37 +00002299 else if (const ObjCObjectPointerType *PTTo =
2300 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002302 FromType->getAs<ObjCObjectPointerType>())
2303 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2304 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002305 }
Richard Trieucaff2472011-11-23 22:32:32 +00002306 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002308 }
2309 }
2310 return true;
2311}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002312
Douglas Gregor39c16d42008-10-24 04:54:22 +00002313/// CheckPointerConversion - Check the pointer conversion from the
2314/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002315/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002316/// conversions for which IsPointerConversion has already returned
2317/// true. It returns true and produces a diagnostic if there was an
2318/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002319bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002320 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002321 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002322 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002323 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002324 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002325
John McCall8cb679e2010-11-15 09:13:47 +00002326 Kind = CK_BitCast;
2327
Chandler Carruthffab8732011-04-09 07:32:05 +00002328 if (!IsCStyleOrFunctionalCast &&
2329 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2330 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2331 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002332 PDiag(diag::warn_impcast_bool_to_null_pointer)
2333 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002334
John McCall9320b872011-09-09 05:25:32 +00002335 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2336 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002337 QualType FromPointeeType = FromPtrType->getPointeeType(),
2338 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002339
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002340 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2341 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002342 // We must have a derived-to-base conversion. Check an
2343 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002344 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2345 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002346 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002347 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002348 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002349
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002350 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002351 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002352 }
2353 }
John McCall9320b872011-09-09 05:25:32 +00002354 } else if (const ObjCObjectPointerType *ToPtrType =
2355 ToType->getAs<ObjCObjectPointerType>()) {
2356 if (const ObjCObjectPointerType *FromPtrType =
2357 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002358 // Objective-C++ conversions are always okay.
2359 // FIXME: We should have a different class of conversions for the
2360 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002361 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002362 return false;
John McCall9320b872011-09-09 05:25:32 +00002363 } else if (FromType->isBlockPointerType()) {
2364 Kind = CK_BlockPointerToObjCPointerCast;
2365 } else {
2366 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002367 }
John McCall9320b872011-09-09 05:25:32 +00002368 } else if (ToType->isBlockPointerType()) {
2369 if (!FromType->isBlockPointerType())
2370 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002371 }
John McCall8cb679e2010-11-15 09:13:47 +00002372
2373 // We shouldn't fall into this case unless it's valid for other
2374 // reasons.
2375 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2376 Kind = CK_NullToPointer;
2377
Douglas Gregor39c16d42008-10-24 04:54:22 +00002378 return false;
2379}
2380
Sebastian Redl72b597d2009-01-25 19:43:20 +00002381/// IsMemberPointerConversion - Determines whether the conversion of the
2382/// expression From, which has the (possibly adjusted) type FromType, can be
2383/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2384/// If so, returns true and places the converted type (that might differ from
2385/// ToType in its cv-qualifiers at some level) into ConvertedType.
2386bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002388 bool InOverloadResolution,
2389 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002390 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002391 if (!ToTypePtr)
2392 return false;
2393
2394 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002395 if (From->isNullPointerConstant(Context,
2396 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2397 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002398 ConvertedType = ToType;
2399 return true;
2400 }
2401
2402 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002403 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002404 if (!FromTypePtr)
2405 return false;
2406
2407 // A pointer to member of B can be converted to a pointer to member of D,
2408 // where D is derived from B (C++ 4.11p2).
2409 QualType FromClass(FromTypePtr->getClass(), 0);
2410 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002411
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002412 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2413 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2414 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002415 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2416 ToClass.getTypePtr());
2417 return true;
2418 }
2419
2420 return false;
2421}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002422
Sebastian Redl72b597d2009-01-25 19:43:20 +00002423/// CheckMemberPointerConversion - Check the member pointer conversion from the
2424/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002425/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002426/// for which IsMemberPointerConversion has already returned true. It returns
2427/// true and produces a diagnostic if there was an error, or returns false
2428/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002429bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002430 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002431 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002432 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002433 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002434 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002435 if (!FromPtrType) {
2436 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002437 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002438 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002439 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002440 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002441 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002442 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002443
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002444 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002445 assert(ToPtrType && "No member pointer cast has a target type "
2446 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002447
Sebastian Redled8f2002009-01-28 18:33:18 +00002448 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2449 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002450
Sebastian Redled8f2002009-01-28 18:33:18 +00002451 // FIXME: What about dependent types?
2452 assert(FromClass->isRecordType() && "Pointer into non-class.");
2453 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002454
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002455 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002456 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002457 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2458 assert(DerivationOkay &&
2459 "Should not have been called if derivation isn't OK.");
2460 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002461
Sebastian Redled8f2002009-01-28 18:33:18 +00002462 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2463 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002464 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2465 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2466 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2467 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002468 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002469
Douglas Gregor89ee6822009-02-28 01:32:25 +00002470 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002471 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2472 << FromClass << ToClass << QualType(VBase, 0)
2473 << From->getSourceRange();
2474 return true;
2475 }
2476
John McCall5b0829a2010-02-10 09:31:12 +00002477 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002478 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2479 Paths.front(),
2480 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002481
Anders Carlssond7923c62009-08-22 23:33:40 +00002482 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002483 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002484 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002485 return false;
2486}
2487
Douglas Gregor9a657932008-10-21 23:43:52 +00002488/// IsQualificationConversion - Determines whether the conversion from
2489/// an rvalue of type FromType to ToType is a qualification conversion
2490/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002491///
2492/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2493/// when the qualification conversion involves a change in the Objective-C
2494/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002495bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002496Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002497 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002498 FromType = Context.getCanonicalType(FromType);
2499 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002500 ObjCLifetimeConversion = false;
2501
Douglas Gregor9a657932008-10-21 23:43:52 +00002502 // If FromType and ToType are the same type, this is not a
2503 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002504 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002505 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002506
Douglas Gregor9a657932008-10-21 23:43:52 +00002507 // (C++ 4.4p4):
2508 // A conversion can add cv-qualifiers at levels other than the first
2509 // in multi-level pointers, subject to the following rules: [...]
2510 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002511 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002512 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002513 // Within each iteration of the loop, we check the qualifiers to
2514 // determine if this still looks like a qualification
2515 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002516 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002517 // until there are no more pointers or pointers-to-members left to
2518 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002519 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002520
Douglas Gregor90609aa2011-04-25 18:40:17 +00002521 Qualifiers FromQuals = FromType.getQualifiers();
2522 Qualifiers ToQuals = ToType.getQualifiers();
2523
John McCall31168b02011-06-15 23:02:42 +00002524 // Objective-C ARC:
2525 // Check Objective-C lifetime conversions.
2526 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2527 UnwrappedAnyPointer) {
2528 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2529 ObjCLifetimeConversion = true;
2530 FromQuals.removeObjCLifetime();
2531 ToQuals.removeObjCLifetime();
2532 } else {
2533 // Qualification conversions cannot cast between different
2534 // Objective-C lifetime qualifiers.
2535 return false;
2536 }
2537 }
2538
Douglas Gregorf30053d2011-05-08 06:09:53 +00002539 // Allow addition/removal of GC attributes but not changing GC attributes.
2540 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2541 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2542 FromQuals.removeObjCGCAttr();
2543 ToQuals.removeObjCGCAttr();
2544 }
2545
Douglas Gregor9a657932008-10-21 23:43:52 +00002546 // -- for every j > 0, if const is in cv 1,j then const is in cv
2547 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002548 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002549 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002550
Douglas Gregor9a657932008-10-21 23:43:52 +00002551 // -- if the cv 1,j and cv 2,j are different, then const is in
2552 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002553 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002554 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002555 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002556
Douglas Gregor9a657932008-10-21 23:43:52 +00002557 // Keep track of whether all prior cv-qualifiers in the "to" type
2558 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002559 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002560 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002561 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002562
2563 // We are left with FromType and ToType being the pointee types
2564 // after unwrapping the original FromType and ToType the same number
2565 // of types. If we unwrapped any pointers, and if FromType and
2566 // ToType have the same unqualified type (since we checked
2567 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002568 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002569}
2570
Douglas Gregor576e98c2009-01-30 23:27:23 +00002571/// Determines whether there is a user-defined conversion sequence
2572/// (C++ [over.ics.user]) that converts expression From to the type
2573/// ToType. If such a conversion exists, User will contain the
2574/// user-defined conversion sequence that performs such a conversion
2575/// and this routine will return true. Otherwise, this routine returns
2576/// false and User is unspecified.
2577///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002578/// \param AllowExplicit true if the conversion should consider C++0x
2579/// "explicit" conversion functions as well as non-explicit conversion
2580/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002581static OverloadingResult
2582IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2583 UserDefinedConversionSequence& User,
2584 OverloadCandidateSet& CandidateSet,
2585 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002586 // Whether we will only visit constructors.
2587 bool ConstructorsOnly = false;
2588
2589 // If the type we are conversion to is a class type, enumerate its
2590 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002591 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002592 // C++ [over.match.ctor]p1:
2593 // When objects of class type are direct-initialized (8.5), or
2594 // copy-initialized from an expression of the same or a
2595 // derived class type (8.5), overload resolution selects the
2596 // constructor. [...] For copy-initialization, the candidate
2597 // functions are all the converting constructors (12.3.1) of
2598 // that class. The argument list is the expression-list within
2599 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002600 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002601 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002602 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002603 ConstructorsOnly = true;
2604
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002605 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2606 // RequireCompleteType may have returned true due to some invalid decl
2607 // during template instantiation, but ToType may be complete enough now
2608 // to try to recover.
2609 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002610 // We're not going to find any constructors.
2611 } else if (CXXRecordDecl *ToRecordDecl
2612 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002613 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002614 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002615 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002616 NamedDecl *D = *Con;
2617 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2618
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002619 // Find the constructor (which may be a template).
2620 CXXConstructorDecl *Constructor = 0;
2621 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002622 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002623 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002624 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002625 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2626 else
John McCalla0296f72010-03-19 07:35:19 +00002627 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002628
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002629 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002630 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002631 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002632 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2633 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002634 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002635 /*SuppressUserConversions=*/
2636 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002637 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002638 // Allow one user-defined conversion when user specifies a
2639 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002640 S.AddOverloadCandidate(Constructor, FoundDecl,
2641 &From, 1, CandidateSet,
2642 /*SuppressUserConversions=*/
2643 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002644 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002645 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002646 }
2647 }
2648
Douglas Gregor5ab11652010-04-17 22:01:05 +00002649 // Enumerate conversion functions, if we're allowed to.
2650 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002651 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2652 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002653 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002654 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002655 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002656 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002657 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2658 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002659 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002660 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002661 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002662 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002663 DeclAccessPair FoundDecl = I.getPair();
2664 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002665 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2666 if (isa<UsingShadowDecl>(D))
2667 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2668
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002669 CXXConversionDecl *Conv;
2670 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002671 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2672 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002673 else
John McCallda4458e2010-03-31 01:36:47 +00002674 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002675
2676 if (AllowExplicit || !Conv->isExplicit()) {
2677 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002678 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2679 ActingContext, From, ToType,
2680 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002681 else
John McCall5c32be02010-08-24 20:38:10 +00002682 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2683 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002684 }
2685 }
2686 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002687 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002688
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002689 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2690
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002691 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002692 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002693 case OR_Success:
2694 // Record the standard conversion we used and the conversion function.
2695 if (CXXConstructorDecl *Constructor
2696 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002697 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2698
John McCall5c32be02010-08-24 20:38:10 +00002699 // C++ [over.ics.user]p1:
2700 // If the user-defined conversion is specified by a
2701 // constructor (12.3.1), the initial standard conversion
2702 // sequence converts the source type to the type required by
2703 // the argument of the constructor.
2704 //
2705 QualType ThisType = Constructor->getThisType(S.Context);
2706 if (Best->Conversions[0].isEllipsis())
2707 User.EllipsisConversion = true;
2708 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002709 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002710 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002711 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002712 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002713 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002714 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002715 User.After.setAsIdentityConversion();
2716 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2717 User.After.setAllToTypes(ToType);
2718 return OR_Success;
2719 } else if (CXXConversionDecl *Conversion
2720 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002721 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2722
John McCall5c32be02010-08-24 20:38:10 +00002723 // C++ [over.ics.user]p1:
2724 //
2725 // [...] If the user-defined conversion is specified by a
2726 // conversion function (12.3.2), the initial standard
2727 // conversion sequence converts the source type to the
2728 // implicit object parameter of the conversion function.
2729 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002730 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002731 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002732 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002733 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002734
John McCall5c32be02010-08-24 20:38:10 +00002735 // C++ [over.ics.user]p2:
2736 // The second standard conversion sequence converts the
2737 // result of the user-defined conversion to the target type
2738 // for the sequence. Since an implicit conversion sequence
2739 // is an initialization, the special rules for
2740 // initialization by user-defined conversion apply when
2741 // selecting the best user-defined conversion for a
2742 // user-defined conversion sequence (see 13.3.3 and
2743 // 13.3.3.1).
2744 User.After = Best->FinalConversion;
2745 return OR_Success;
2746 } else {
2747 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002748 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002749 }
2750
John McCall5c32be02010-08-24 20:38:10 +00002751 case OR_No_Viable_Function:
2752 return OR_No_Viable_Function;
2753 case OR_Deleted:
2754 // No conversion here! We're done.
2755 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002756
John McCall5c32be02010-08-24 20:38:10 +00002757 case OR_Ambiguous:
2758 return OR_Ambiguous;
2759 }
2760
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002761 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002762}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002763
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002764bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002765Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002766 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002767 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002768 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002769 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002770 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002771 if (OvResult == OR_Ambiguous)
2772 Diag(From->getSourceRange().getBegin(),
2773 diag::err_typecheck_ambiguous_condition)
2774 << From->getType() << ToType << From->getSourceRange();
2775 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2776 Diag(From->getSourceRange().getBegin(),
2777 diag::err_typecheck_nonviable_condition)
2778 << From->getType() << ToType << From->getSourceRange();
2779 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002780 return false;
John McCall5c32be02010-08-24 20:38:10 +00002781 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002782 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002783}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002784
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002785/// CompareImplicitConversionSequences - Compare two implicit
2786/// conversion sequences to determine whether one is better than the
2787/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002788static ImplicitConversionSequence::CompareKind
2789CompareImplicitConversionSequences(Sema &S,
2790 const ImplicitConversionSequence& ICS1,
2791 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002792{
2793 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2794 // conversion sequences (as defined in 13.3.3.1)
2795 // -- a standard conversion sequence (13.3.3.1.1) is a better
2796 // conversion sequence than a user-defined conversion sequence or
2797 // an ellipsis conversion sequence, and
2798 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2799 // conversion sequence than an ellipsis conversion sequence
2800 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002801 //
John McCall0d1da222010-01-12 00:44:57 +00002802 // C++0x [over.best.ics]p10:
2803 // For the purpose of ranking implicit conversion sequences as
2804 // described in 13.3.3.2, the ambiguous conversion sequence is
2805 // treated as a user-defined sequence that is indistinguishable
2806 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002807 if (ICS1.getKindRank() < ICS2.getKindRank())
2808 return ImplicitConversionSequence::Better;
2809 else if (ICS2.getKindRank() < ICS1.getKindRank())
2810 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002811
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002812 // The following checks require both conversion sequences to be of
2813 // the same kind.
2814 if (ICS1.getKind() != ICS2.getKind())
2815 return ImplicitConversionSequence::Indistinguishable;
2816
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002817 ImplicitConversionSequence::CompareKind Result =
2818 ImplicitConversionSequence::Indistinguishable;
2819
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002820 // Two implicit conversion sequences of the same form are
2821 // indistinguishable conversion sequences unless one of the
2822 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002823 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002824 Result = CompareStandardConversionSequences(S,
2825 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002826 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002827 // User-defined conversion sequence U1 is a better conversion
2828 // sequence than another user-defined conversion sequence U2 if
2829 // they contain the same user-defined conversion function or
2830 // constructor and if the second standard conversion sequence of
2831 // U1 is better than the second standard conversion sequence of
2832 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002833 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002834 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002835 Result = CompareStandardConversionSequences(S,
2836 ICS1.UserDefined.After,
2837 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002838 }
2839
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002840 // List-initialization sequence L1 is a better conversion sequence than
2841 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2842 // for some X and L2 does not.
2843 if (Result == ImplicitConversionSequence::Indistinguishable &&
2844 ICS1.isListInitializationSequence() &&
2845 ICS2.isListInitializationSequence()) {
2846 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2847 }
2848
2849 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002850}
2851
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002852static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2853 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2854 Qualifiers Quals;
2855 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002856 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002858
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002859 return Context.hasSameUnqualifiedType(T1, T2);
2860}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002861
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002862// Per 13.3.3.2p3, compare the given standard conversion sequences to
2863// determine if one is a proper subset of the other.
2864static ImplicitConversionSequence::CompareKind
2865compareStandardConversionSubsets(ASTContext &Context,
2866 const StandardConversionSequence& SCS1,
2867 const StandardConversionSequence& SCS2) {
2868 ImplicitConversionSequence::CompareKind Result
2869 = ImplicitConversionSequence::Indistinguishable;
2870
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002871 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002872 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002873 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2874 return ImplicitConversionSequence::Better;
2875 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2876 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002877
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002878 if (SCS1.Second != SCS2.Second) {
2879 if (SCS1.Second == ICK_Identity)
2880 Result = ImplicitConversionSequence::Better;
2881 else if (SCS2.Second == ICK_Identity)
2882 Result = ImplicitConversionSequence::Worse;
2883 else
2884 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002885 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002886 return ImplicitConversionSequence::Indistinguishable;
2887
2888 if (SCS1.Third == SCS2.Third) {
2889 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2890 : ImplicitConversionSequence::Indistinguishable;
2891 }
2892
2893 if (SCS1.Third == ICK_Identity)
2894 return Result == ImplicitConversionSequence::Worse
2895 ? ImplicitConversionSequence::Indistinguishable
2896 : ImplicitConversionSequence::Better;
2897
2898 if (SCS2.Third == ICK_Identity)
2899 return Result == ImplicitConversionSequence::Better
2900 ? ImplicitConversionSequence::Indistinguishable
2901 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002902
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002903 return ImplicitConversionSequence::Indistinguishable;
2904}
2905
Douglas Gregore696ebb2011-01-26 14:52:12 +00002906/// \brief Determine whether one of the given reference bindings is better
2907/// than the other based on what kind of bindings they are.
2908static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2909 const StandardConversionSequence &SCS2) {
2910 // C++0x [over.ics.rank]p3b4:
2911 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2912 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002914 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002916 // reference*.
2917 //
2918 // FIXME: Rvalue references. We're going rogue with the above edits,
2919 // because the semantics in the current C++0x working paper (N3225 at the
2920 // time of this writing) break the standard definition of std::forward
2921 // and std::reference_wrapper when dealing with references to functions.
2922 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002923 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2924 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2925 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002926
Douglas Gregore696ebb2011-01-26 14:52:12 +00002927 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2928 SCS2.IsLvalueReference) ||
2929 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2930 !SCS2.IsLvalueReference);
2931}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002932
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002933/// CompareStandardConversionSequences - Compare two standard
2934/// conversion sequences to determine whether one is better than the
2935/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002936static ImplicitConversionSequence::CompareKind
2937CompareStandardConversionSequences(Sema &S,
2938 const StandardConversionSequence& SCS1,
2939 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002940{
2941 // Standard conversion sequence S1 is a better conversion sequence
2942 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2943
2944 // -- S1 is a proper subsequence of S2 (comparing the conversion
2945 // sequences in the canonical form defined by 13.3.3.1.1,
2946 // excluding any Lvalue Transformation; the identity conversion
2947 // sequence is considered to be a subsequence of any
2948 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002949 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002950 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002951 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002952
2953 // -- the rank of S1 is better than the rank of S2 (by the rules
2954 // defined below), or, if not that,
2955 ImplicitConversionRank Rank1 = SCS1.getRank();
2956 ImplicitConversionRank Rank2 = SCS2.getRank();
2957 if (Rank1 < Rank2)
2958 return ImplicitConversionSequence::Better;
2959 else if (Rank2 < Rank1)
2960 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002961
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002962 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2963 // are indistinguishable unless one of the following rules
2964 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002965
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002966 // A conversion that is not a conversion of a pointer, or
2967 // pointer to member, to bool is better than another conversion
2968 // that is such a conversion.
2969 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2970 return SCS2.isPointerConversionToBool()
2971 ? ImplicitConversionSequence::Better
2972 : ImplicitConversionSequence::Worse;
2973
Douglas Gregor5c407d92008-10-23 00:40:37 +00002974 // C++ [over.ics.rank]p4b2:
2975 //
2976 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002977 // conversion of B* to A* is better than conversion of B* to
2978 // void*, and conversion of A* to void* is better than conversion
2979 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002980 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002981 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002982 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002983 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002984 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2985 // Exactly one of the conversion sequences is a conversion to
2986 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002987 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2988 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002989 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2990 // Neither conversion sequence converts to a void pointer; compare
2991 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002992 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002993 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002994 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002995 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2996 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002997 // Both conversion sequences are conversions to void
2998 // pointers. Compare the source types to determine if there's an
2999 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003000 QualType FromType1 = SCS1.getFromType();
3001 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003002
3003 // Adjust the types we're converting from via the array-to-pointer
3004 // conversion, if we need to.
3005 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003006 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003007 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003008 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003009
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003010 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3011 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003012
John McCall5c32be02010-08-24 20:38:10 +00003013 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003014 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003015 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003016 return ImplicitConversionSequence::Worse;
3017
3018 // Objective-C++: If one interface is more specific than the
3019 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003020 const ObjCObjectPointerType* FromObjCPtr1
3021 = FromType1->getAs<ObjCObjectPointerType>();
3022 const ObjCObjectPointerType* FromObjCPtr2
3023 = FromType2->getAs<ObjCObjectPointerType>();
3024 if (FromObjCPtr1 && FromObjCPtr2) {
3025 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3026 FromObjCPtr2);
3027 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3028 FromObjCPtr1);
3029 if (AssignLeft != AssignRight) {
3030 return AssignLeft? ImplicitConversionSequence::Better
3031 : ImplicitConversionSequence::Worse;
3032 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003033 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003034 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003035
3036 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3037 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003038 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003039 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003040 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003041
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003042 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003043 // Check for a better reference binding based on the kind of bindings.
3044 if (isBetterReferenceBindingKind(SCS1, SCS2))
3045 return ImplicitConversionSequence::Better;
3046 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3047 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003048
Sebastian Redlb28b4072009-03-22 23:49:27 +00003049 // C++ [over.ics.rank]p3b4:
3050 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3051 // which the references refer are the same type except for
3052 // top-level cv-qualifiers, and the type to which the reference
3053 // initialized by S2 refers is more cv-qualified than the type
3054 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003055 QualType T1 = SCS1.getToType(2);
3056 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003057 T1 = S.Context.getCanonicalType(T1);
3058 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003059 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003060 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3061 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003062 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003063 // Objective-C++ ARC: If the references refer to objects with different
3064 // lifetimes, prefer bindings that don't change lifetime.
3065 if (SCS1.ObjCLifetimeConversionBinding !=
3066 SCS2.ObjCLifetimeConversionBinding) {
3067 return SCS1.ObjCLifetimeConversionBinding
3068 ? ImplicitConversionSequence::Worse
3069 : ImplicitConversionSequence::Better;
3070 }
3071
Chandler Carruth8e543b32010-12-12 08:17:55 +00003072 // If the type is an array type, promote the element qualifiers to the
3073 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003074 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003075 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003076 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003077 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003078 if (T2.isMoreQualifiedThan(T1))
3079 return ImplicitConversionSequence::Better;
3080 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003081 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003082 }
3083 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003084
Francois Pichet08d2fa02011-09-18 21:37:37 +00003085 // In Microsoft mode, prefer an integral conversion to a
3086 // floating-to-integral conversion if the integral conversion
3087 // is between types of the same size.
3088 // For example:
3089 // void f(float);
3090 // void f(int);
3091 // int main {
3092 // long a;
3093 // f(a);
3094 // }
3095 // Here, MSVC will call f(int) instead of generating a compile error
3096 // as clang will do in standard mode.
3097 if (S.getLangOptions().MicrosoftMode &&
3098 SCS1.Second == ICK_Integral_Conversion &&
3099 SCS2.Second == ICK_Floating_Integral &&
3100 S.Context.getTypeSize(SCS1.getFromType()) ==
3101 S.Context.getTypeSize(SCS1.getToType(2)))
3102 return ImplicitConversionSequence::Better;
3103
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003104 return ImplicitConversionSequence::Indistinguishable;
3105}
3106
3107/// CompareQualificationConversions - Compares two standard conversion
3108/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003109/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3110ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003111CompareQualificationConversions(Sema &S,
3112 const StandardConversionSequence& SCS1,
3113 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003114 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003115 // -- S1 and S2 differ only in their qualification conversion and
3116 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3117 // cv-qualification signature of type T1 is a proper subset of
3118 // the cv-qualification signature of type T2, and S1 is not the
3119 // deprecated string literal array-to-pointer conversion (4.2).
3120 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3121 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3122 return ImplicitConversionSequence::Indistinguishable;
3123
3124 // FIXME: the example in the standard doesn't use a qualification
3125 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003126 QualType T1 = SCS1.getToType(2);
3127 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003128 T1 = S.Context.getCanonicalType(T1);
3129 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003130 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003131 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3132 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003133
3134 // If the types are the same, we won't learn anything by unwrapped
3135 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003136 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003137 return ImplicitConversionSequence::Indistinguishable;
3138
Chandler Carruth607f38e2009-12-29 07:16:59 +00003139 // If the type is an array type, promote the element qualifiers to the type
3140 // for comparison.
3141 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003142 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003143 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003144 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003145
Mike Stump11289f42009-09-09 15:08:12 +00003146 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003147 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003148
3149 // Objective-C++ ARC:
3150 // Prefer qualification conversions not involving a change in lifetime
3151 // to qualification conversions that do not change lifetime.
3152 if (SCS1.QualificationIncludesObjCLifetime !=
3153 SCS2.QualificationIncludesObjCLifetime) {
3154 Result = SCS1.QualificationIncludesObjCLifetime
3155 ? ImplicitConversionSequence::Worse
3156 : ImplicitConversionSequence::Better;
3157 }
3158
John McCall5c32be02010-08-24 20:38:10 +00003159 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003160 // Within each iteration of the loop, we check the qualifiers to
3161 // determine if this still looks like a qualification
3162 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003163 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003164 // until there are no more pointers or pointers-to-members left
3165 // to unwrap. This essentially mimics what
3166 // IsQualificationConversion does, but here we're checking for a
3167 // strict subset of qualifiers.
3168 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3169 // The qualifiers are the same, so this doesn't tell us anything
3170 // about how the sequences rank.
3171 ;
3172 else if (T2.isMoreQualifiedThan(T1)) {
3173 // T1 has fewer qualifiers, so it could be the better sequence.
3174 if (Result == ImplicitConversionSequence::Worse)
3175 // Neither has qualifiers that are a subset of the other's
3176 // qualifiers.
3177 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003178
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003179 Result = ImplicitConversionSequence::Better;
3180 } else if (T1.isMoreQualifiedThan(T2)) {
3181 // T2 has fewer qualifiers, so it could be the better sequence.
3182 if (Result == ImplicitConversionSequence::Better)
3183 // Neither has qualifiers that are a subset of the other's
3184 // qualifiers.
3185 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003186
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003187 Result = ImplicitConversionSequence::Worse;
3188 } else {
3189 // Qualifiers are disjoint.
3190 return ImplicitConversionSequence::Indistinguishable;
3191 }
3192
3193 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003194 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003195 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003196 }
3197
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003198 // Check that the winning standard conversion sequence isn't using
3199 // the deprecated string literal array to pointer conversion.
3200 switch (Result) {
3201 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003202 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003203 Result = ImplicitConversionSequence::Indistinguishable;
3204 break;
3205
3206 case ImplicitConversionSequence::Indistinguishable:
3207 break;
3208
3209 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003210 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003211 Result = ImplicitConversionSequence::Indistinguishable;
3212 break;
3213 }
3214
3215 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003216}
3217
Douglas Gregor5c407d92008-10-23 00:40:37 +00003218/// CompareDerivedToBaseConversions - Compares two standard conversion
3219/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003220/// various kinds of derived-to-base conversions (C++
3221/// [over.ics.rank]p4b3). As part of these checks, we also look at
3222/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003223ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003224CompareDerivedToBaseConversions(Sema &S,
3225 const StandardConversionSequence& SCS1,
3226 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003227 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003228 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003229 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003230 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003231
3232 // Adjust the types we're converting from via the array-to-pointer
3233 // conversion, if we need to.
3234 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003235 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003236 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003237 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003238
3239 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003240 FromType1 = S.Context.getCanonicalType(FromType1);
3241 ToType1 = S.Context.getCanonicalType(ToType1);
3242 FromType2 = S.Context.getCanonicalType(FromType2);
3243 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003244
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003245 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003246 //
3247 // If class B is derived directly or indirectly from class A and
3248 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003249 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003250 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003251 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003252 SCS2.Second == ICK_Pointer_Conversion &&
3253 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3254 FromType1->isPointerType() && FromType2->isPointerType() &&
3255 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003256 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003257 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003258 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003259 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003260 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003261 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003262 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003263 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003264
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003265 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003266 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003267 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003268 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003269 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003270 return ImplicitConversionSequence::Worse;
3271 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003272
3273 // -- conversion of B* to A* is better than conversion of C* to A*,
3274 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003275 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003276 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003277 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003278 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003279 }
3280 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3281 SCS2.Second == ICK_Pointer_Conversion) {
3282 const ObjCObjectPointerType *FromPtr1
3283 = FromType1->getAs<ObjCObjectPointerType>();
3284 const ObjCObjectPointerType *FromPtr2
3285 = FromType2->getAs<ObjCObjectPointerType>();
3286 const ObjCObjectPointerType *ToPtr1
3287 = ToType1->getAs<ObjCObjectPointerType>();
3288 const ObjCObjectPointerType *ToPtr2
3289 = ToType2->getAs<ObjCObjectPointerType>();
3290
3291 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3292 // Apply the same conversion ranking rules for Objective-C pointer types
3293 // that we do for C++ pointers to class types. However, we employ the
3294 // Objective-C pseudo-subtyping relationship used for assignment of
3295 // Objective-C pointer types.
3296 bool FromAssignLeft
3297 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3298 bool FromAssignRight
3299 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3300 bool ToAssignLeft
3301 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3302 bool ToAssignRight
3303 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3304
3305 // A conversion to an a non-id object pointer type or qualified 'id'
3306 // type is better than a conversion to 'id'.
3307 if (ToPtr1->isObjCIdType() &&
3308 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3309 return ImplicitConversionSequence::Worse;
3310 if (ToPtr2->isObjCIdType() &&
3311 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3312 return ImplicitConversionSequence::Better;
3313
3314 // A conversion to a non-id object pointer type is better than a
3315 // conversion to a qualified 'id' type
3316 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3317 return ImplicitConversionSequence::Worse;
3318 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3319 return ImplicitConversionSequence::Better;
3320
3321 // A conversion to an a non-Class object pointer type or qualified 'Class'
3322 // type is better than a conversion to 'Class'.
3323 if (ToPtr1->isObjCClassType() &&
3324 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3325 return ImplicitConversionSequence::Worse;
3326 if (ToPtr2->isObjCClassType() &&
3327 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3328 return ImplicitConversionSequence::Better;
3329
3330 // A conversion to a non-Class object pointer type is better than a
3331 // conversion to a qualified 'Class' type.
3332 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3333 return ImplicitConversionSequence::Worse;
3334 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3335 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003336
Douglas Gregor058d3de2011-01-31 18:51:41 +00003337 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3338 if (S.Context.hasSameType(FromType1, FromType2) &&
3339 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3340 (ToAssignLeft != ToAssignRight))
3341 return ToAssignLeft? ImplicitConversionSequence::Worse
3342 : ImplicitConversionSequence::Better;
3343
3344 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3345 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3346 (FromAssignLeft != FromAssignRight))
3347 return FromAssignLeft? ImplicitConversionSequence::Better
3348 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003349 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003350 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003351
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003352 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003353 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3354 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3355 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003356 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003357 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003359 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003360 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003361 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003362 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003363 ToType2->getAs<MemberPointerType>();
3364 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3365 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3366 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3367 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3368 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3369 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3370 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3371 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003372 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003373 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003374 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003375 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003376 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003377 return ImplicitConversionSequence::Better;
3378 }
3379 // conversion of B::* to C::* is better than conversion of A::* to C::*
3380 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003381 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003382 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003383 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003384 return ImplicitConversionSequence::Worse;
3385 }
3386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003387
Douglas Gregor5ab11652010-04-17 22:01:05 +00003388 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003389 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003390 // -- binding of an expression of type C to a reference of type
3391 // B& is better than binding an expression of type C to a
3392 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003393 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3394 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3395 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003396 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003397 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003398 return ImplicitConversionSequence::Worse;
3399 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003400
Douglas Gregor2fe98832008-11-03 19:09:14 +00003401 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003402 // -- binding of an expression of type B to a reference of type
3403 // A& is better than binding an expression of type C to a
3404 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003405 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3406 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3407 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003408 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003409 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003410 return ImplicitConversionSequence::Worse;
3411 }
3412 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003413
Douglas Gregor5c407d92008-10-23 00:40:37 +00003414 return ImplicitConversionSequence::Indistinguishable;
3415}
3416
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003417/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3418/// determine whether they are reference-related,
3419/// reference-compatible, reference-compatible with added
3420/// qualification, or incompatible, for use in C++ initialization by
3421/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3422/// type, and the first type (T1) is the pointee type of the reference
3423/// type being initialized.
3424Sema::ReferenceCompareResult
3425Sema::CompareReferenceRelationship(SourceLocation Loc,
3426 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003427 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003428 bool &ObjCConversion,
3429 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003430 assert(!OrigT1->isReferenceType() &&
3431 "T1 must be the pointee type of the reference type");
3432 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3433
3434 QualType T1 = Context.getCanonicalType(OrigT1);
3435 QualType T2 = Context.getCanonicalType(OrigT2);
3436 Qualifiers T1Quals, T2Quals;
3437 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3438 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3439
3440 // C++ [dcl.init.ref]p4:
3441 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3442 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3443 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003444 DerivedToBase = false;
3445 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003446 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003447 if (UnqualT1 == UnqualT2) {
3448 // Nothing to do.
3449 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003450 IsDerivedFrom(UnqualT2, UnqualT1))
3451 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003452 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3453 UnqualT2->isObjCObjectOrInterfaceType() &&
3454 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3455 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003456 else
3457 return Ref_Incompatible;
3458
3459 // At this point, we know that T1 and T2 are reference-related (at
3460 // least).
3461
3462 // If the type is an array type, promote the element qualifiers to the type
3463 // for comparison.
3464 if (isa<ArrayType>(T1) && T1Quals)
3465 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3466 if (isa<ArrayType>(T2) && T2Quals)
3467 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3468
3469 // C++ [dcl.init.ref]p4:
3470 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3471 // reference-related to T2 and cv1 is the same cv-qualification
3472 // as, or greater cv-qualification than, cv2. For purposes of
3473 // overload resolution, cases for which cv1 is greater
3474 // cv-qualification than cv2 are identified as
3475 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003476 //
3477 // Note that we also require equivalence of Objective-C GC and address-space
3478 // qualifiers when performing these computations, so that e.g., an int in
3479 // address space 1 is not reference-compatible with an int in address
3480 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003481 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3482 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3483 T1Quals.removeObjCLifetime();
3484 T2Quals.removeObjCLifetime();
3485 ObjCLifetimeConversion = true;
3486 }
3487
Douglas Gregord517d552011-04-28 17:56:11 +00003488 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003489 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003490 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003491 return Ref_Compatible_With_Added_Qualification;
3492 else
3493 return Ref_Related;
3494}
3495
Douglas Gregor836a7e82010-08-11 02:15:33 +00003496/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003497/// with DeclType. Return true if something definite is found.
3498static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003499FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3500 QualType DeclType, SourceLocation DeclLoc,
3501 Expr *Init, QualType T2, bool AllowRvalues,
3502 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003503 assert(T2->isRecordType() && "Can only find conversions of record types.");
3504 CXXRecordDecl *T2RecordDecl
3505 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3506
3507 OverloadCandidateSet CandidateSet(DeclLoc);
3508 const UnresolvedSetImpl *Conversions
3509 = T2RecordDecl->getVisibleConversionFunctions();
3510 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3511 E = Conversions->end(); I != E; ++I) {
3512 NamedDecl *D = *I;
3513 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3514 if (isa<UsingShadowDecl>(D))
3515 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3516
3517 FunctionTemplateDecl *ConvTemplate
3518 = dyn_cast<FunctionTemplateDecl>(D);
3519 CXXConversionDecl *Conv;
3520 if (ConvTemplate)
3521 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3522 else
3523 Conv = cast<CXXConversionDecl>(D);
3524
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003525 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003526 // explicit conversions, skip it.
3527 if (!AllowExplicit && Conv->isExplicit())
3528 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529
Douglas Gregor836a7e82010-08-11 02:15:33 +00003530 if (AllowRvalues) {
3531 bool DerivedToBase = false;
3532 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003533 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003534
3535 // If we are initializing an rvalue reference, don't permit conversion
3536 // functions that return lvalues.
3537 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3538 const ReferenceType *RefType
3539 = Conv->getConversionType()->getAs<LValueReferenceType>();
3540 if (RefType && !RefType->getPointeeType()->isFunctionType())
3541 continue;
3542 }
3543
Douglas Gregor836a7e82010-08-11 02:15:33 +00003544 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003545 S.CompareReferenceRelationship(
3546 DeclLoc,
3547 Conv->getConversionType().getNonReferenceType()
3548 .getUnqualifiedType(),
3549 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003550 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003551 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003552 continue;
3553 } else {
3554 // If the conversion function doesn't return a reference type,
3555 // it can't be considered for this conversion. An rvalue reference
3556 // is only acceptable if its referencee is a function type.
3557
3558 const ReferenceType *RefType =
3559 Conv->getConversionType()->getAs<ReferenceType>();
3560 if (!RefType ||
3561 (!RefType->isLValueReferenceType() &&
3562 !RefType->getPointeeType()->isFunctionType()))
3563 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003564 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003565
Douglas Gregor836a7e82010-08-11 02:15:33 +00003566 if (ConvTemplate)
3567 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003568 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003569 else
3570 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003571 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003572 }
3573
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003574 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3575
Sebastian Redld92badf2010-06-30 18:13:39 +00003576 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003577 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003578 case OR_Success:
3579 // C++ [over.ics.ref]p1:
3580 //
3581 // [...] If the parameter binds directly to the result of
3582 // applying a conversion function to the argument
3583 // expression, the implicit conversion sequence is a
3584 // user-defined conversion sequence (13.3.3.1.2), with the
3585 // second standard conversion sequence either an identity
3586 // conversion or, if the conversion function returns an
3587 // entity of a type that is a derived class of the parameter
3588 // type, a derived-to-base Conversion.
3589 if (!Best->FinalConversion.DirectBinding)
3590 return false;
3591
Chandler Carruth30141632011-02-25 19:41:05 +00003592 if (Best->Function)
3593 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003594 ICS.setUserDefined();
3595 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3596 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003597 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003598 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003599 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003600 ICS.UserDefined.EllipsisConversion = false;
3601 assert(ICS.UserDefined.After.ReferenceBinding &&
3602 ICS.UserDefined.After.DirectBinding &&
3603 "Expected a direct reference binding!");
3604 return true;
3605
3606 case OR_Ambiguous:
3607 ICS.setAmbiguous();
3608 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3609 Cand != CandidateSet.end(); ++Cand)
3610 if (Cand->Viable)
3611 ICS.Ambiguous.addConversion(Cand->Function);
3612 return true;
3613
3614 case OR_No_Viable_Function:
3615 case OR_Deleted:
3616 // There was no suitable conversion, or we found a deleted
3617 // conversion; continue with other checks.
3618 return false;
3619 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003620
Eric Christopheraba9fb22010-06-30 18:36:32 +00003621 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003622}
3623
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003624/// \brief Compute an implicit conversion sequence for reference
3625/// initialization.
3626static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003627TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003628 SourceLocation DeclLoc,
3629 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003630 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003631 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3632
3633 // Most paths end in a failed conversion.
3634 ImplicitConversionSequence ICS;
3635 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3636
3637 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3638 QualType T2 = Init->getType();
3639
3640 // If the initializer is the address of an overloaded function, try
3641 // to resolve the overloaded function. If all goes well, T2 is the
3642 // type of the resulting function.
3643 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3644 DeclAccessPair Found;
3645 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3646 false, Found))
3647 T2 = Fn->getType();
3648 }
3649
3650 // Compute some basic properties of the types and the initializer.
3651 bool isRValRef = DeclType->isRValueReferenceType();
3652 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003653 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003654 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003655 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003656 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003657 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003658 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003659
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003660
Sebastian Redld92badf2010-06-30 18:13:39 +00003661 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003662 // A reference to type "cv1 T1" is initialized by an expression
3663 // of type "cv2 T2" as follows:
3664
Sebastian Redld92badf2010-06-30 18:13:39 +00003665 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003666 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003667 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3668 // reference-compatible with "cv2 T2," or
3669 //
3670 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3671 if (InitCategory.isLValue() &&
3672 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003673 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003674 // When a parameter of reference type binds directly (8.5.3)
3675 // to an argument expression, the implicit conversion sequence
3676 // is the identity conversion, unless the argument expression
3677 // has a type that is a derived class of the parameter type,
3678 // in which case the implicit conversion sequence is a
3679 // derived-to-base Conversion (13.3.3.1).
3680 ICS.setStandard();
3681 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003682 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3683 : ObjCConversion? ICK_Compatible_Conversion
3684 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003685 ICS.Standard.Third = ICK_Identity;
3686 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3687 ICS.Standard.setToType(0, T2);
3688 ICS.Standard.setToType(1, T1);
3689 ICS.Standard.setToType(2, T1);
3690 ICS.Standard.ReferenceBinding = true;
3691 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003692 ICS.Standard.IsLvalueReference = !isRValRef;
3693 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3694 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003695 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003696 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003697 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003698
Sebastian Redld92badf2010-06-30 18:13:39 +00003699 // Nothing more to do: the inaccessibility/ambiguity check for
3700 // derived-to-base conversions is suppressed when we're
3701 // computing the implicit conversion sequence (C++
3702 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003703 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003704 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003705
Sebastian Redld92badf2010-06-30 18:13:39 +00003706 // -- has a class type (i.e., T2 is a class type), where T1 is
3707 // not reference-related to T2, and can be implicitly
3708 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3709 // is reference-compatible with "cv3 T3" 92) (this
3710 // conversion is selected by enumerating the applicable
3711 // conversion functions (13.3.1.6) and choosing the best
3712 // one through overload resolution (13.3)),
3713 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003714 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003715 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003716 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3717 Init, T2, /*AllowRvalues=*/false,
3718 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003719 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003720 }
3721 }
3722
Sebastian Redld92badf2010-06-30 18:13:39 +00003723 // -- Otherwise, the reference shall be an lvalue reference to a
3724 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003725 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003727 // We actually handle one oddity of C++ [over.ics.ref] at this
3728 // point, which is that, due to p2 (which short-circuits reference
3729 // binding by only attempting a simple conversion for non-direct
3730 // bindings) and p3's strange wording, we allow a const volatile
3731 // reference to bind to an rvalue. Hence the check for the presence
3732 // of "const" rather than checking for "const" being the only
3733 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003734 // This is also the point where rvalue references and lvalue inits no longer
3735 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003736 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003737 return ICS;
3738
Douglas Gregorf143cd52011-01-24 16:14:37 +00003739 // -- If the initializer expression
3740 //
3741 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003742 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003743 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3744 (InitCategory.isXValue() ||
3745 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3746 (InitCategory.isLValue() && T2->isFunctionType()))) {
3747 ICS.setStandard();
3748 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003750 : ObjCConversion? ICK_Compatible_Conversion
3751 : ICK_Identity;
3752 ICS.Standard.Third = ICK_Identity;
3753 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3754 ICS.Standard.setToType(0, T2);
3755 ICS.Standard.setToType(1, T1);
3756 ICS.Standard.setToType(2, T1);
3757 ICS.Standard.ReferenceBinding = true;
3758 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3759 // binding unless we're binding to a class prvalue.
3760 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3761 // allow the use of rvalue references in C++98/03 for the benefit of
3762 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763 ICS.Standard.DirectBinding =
3764 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003765 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003766 ICS.Standard.IsLvalueReference = !isRValRef;
3767 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003769 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003770 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003771 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774
Douglas Gregorf143cd52011-01-24 16:14:37 +00003775 // -- has a class type (i.e., T2 is a class type), where T1 is not
3776 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777 // an xvalue, class prvalue, or function lvalue of type
3778 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003779 // "cv3 T3",
3780 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003781 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003782 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003783 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003784 // class subobject).
3785 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003787 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3788 Init, T2, /*AllowRvalues=*/true,
3789 AllowExplicit)) {
3790 // In the second case, if the reference is an rvalue reference
3791 // and the second standard conversion sequence of the
3792 // user-defined conversion sequence includes an lvalue-to-rvalue
3793 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003795 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3796 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3797
Douglas Gregor95273c32011-01-21 16:36:05 +00003798 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003800
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003801 // -- Otherwise, a temporary of type "cv1 T1" is created and
3802 // initialized from the initializer expression using the
3803 // rules for a non-reference copy initialization (8.5). The
3804 // reference is then bound to the temporary. If T1 is
3805 // reference-related to T2, cv1 must be the same
3806 // cv-qualification as, or greater cv-qualification than,
3807 // cv2; otherwise, the program is ill-formed.
3808 if (RefRelationship == Sema::Ref_Related) {
3809 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3810 // we would be reference-compatible or reference-compatible with
3811 // added qualification. But that wasn't the case, so the reference
3812 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003813 //
3814 // Note that we only want to check address spaces and cvr-qualifiers here.
3815 // ObjC GC and lifetime qualifiers aren't important.
3816 Qualifiers T1Quals = T1.getQualifiers();
3817 Qualifiers T2Quals = T2.getQualifiers();
3818 T1Quals.removeObjCGCAttr();
3819 T1Quals.removeObjCLifetime();
3820 T2Quals.removeObjCGCAttr();
3821 T2Quals.removeObjCLifetime();
3822 if (!T1Quals.compatiblyIncludes(T2Quals))
3823 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003824 }
3825
3826 // If at least one of the types is a class type, the types are not
3827 // related, and we aren't allowed any user conversions, the
3828 // reference binding fails. This case is important for breaking
3829 // recursion, since TryImplicitConversion below will attempt to
3830 // create a temporary through the use of a copy constructor.
3831 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3832 (T1->isRecordType() || T2->isRecordType()))
3833 return ICS;
3834
Douglas Gregorcba72b12011-01-21 05:18:22 +00003835 // If T1 is reference-related to T2 and the reference is an rvalue
3836 // reference, the initializer expression shall not be an lvalue.
3837 if (RefRelationship >= Sema::Ref_Related &&
3838 isRValRef && Init->Classify(S.Context).isLValue())
3839 return ICS;
3840
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003841 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003842 // When a parameter of reference type is not bound directly to
3843 // an argument expression, the conversion sequence is the one
3844 // required to convert the argument expression to the
3845 // underlying type of the reference according to
3846 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3847 // to copy-initializing a temporary of the underlying type with
3848 // the argument expression. Any difference in top-level
3849 // cv-qualification is subsumed by the initialization itself
3850 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003851 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3852 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003853 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003854 /*CStyle=*/false,
3855 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003856
3857 // Of course, that's still a reference binding.
3858 if (ICS.isStandard()) {
3859 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003860 ICS.Standard.IsLvalueReference = !isRValRef;
3861 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3862 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003863 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003864 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003865 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003866 // Don't allow rvalue references to bind to lvalues.
3867 if (DeclType->isRValueReferenceType()) {
3868 if (const ReferenceType *RefType
3869 = ICS.UserDefined.ConversionFunction->getResultType()
3870 ->getAs<LValueReferenceType>()) {
3871 if (!RefType->getPointeeType()->isFunctionType()) {
3872 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3873 DeclType);
3874 return ICS;
3875 }
3876 }
3877 }
3878
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003879 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003880 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3881 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3882 ICS.UserDefined.After.BindsToRvalue = true;
3883 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3884 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003885 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003886
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003887 return ICS;
3888}
3889
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003890static ImplicitConversionSequence
3891TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3892 bool SuppressUserConversions,
3893 bool InOverloadResolution,
3894 bool AllowObjCWritebackConversion);
3895
3896/// TryListConversion - Try to copy-initialize a value of type ToType from the
3897/// initializer list From.
3898static ImplicitConversionSequence
3899TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3900 bool SuppressUserConversions,
3901 bool InOverloadResolution,
3902 bool AllowObjCWritebackConversion) {
3903 // C++11 [over.ics.list]p1:
3904 // When an argument is an initializer list, it is not an expression and
3905 // special rules apply for converting it to a parameter type.
3906
3907 ImplicitConversionSequence Result;
3908 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003909 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003910
3911 // C++11 [over.ics.list]p2:
3912 // If the parameter type is std::initializer_list<X> or "array of X" and
3913 // all the elements can be implicitly converted to X, the implicit
3914 // conversion sequence is the worst conversion necessary to convert an
3915 // element of the list to X.
3916 // FIXME: Recognize std::initializer_list.
3917 // FIXME: Arrays don't make sense until we can deal with references.
3918 if (ToType->isArrayType())
3919 return Result;
3920
3921 // C++11 [over.ics.list]p3:
3922 // Otherwise, if the parameter is a non-aggregate class X and overload
3923 // resolution chooses a single best constructor [...] the implicit
3924 // conversion sequence is a user-defined conversion sequence. If multiple
3925 // constructors are viable but none is better than the others, the
3926 // implicit conversion sequence is a user-defined conversion sequence.
3927 // FIXME: Implement this.
3928 if (ToType->isRecordType() && !ToType->isAggregateType())
3929 return Result;
3930
3931 // C++11 [over.ics.list]p4:
3932 // Otherwise, if the parameter has an aggregate type which can be
3933 // initialized from the initializer list [...] the implicit conversion
3934 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003935 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003936 // Type is an aggregate, argument is an init list. At this point it comes
3937 // down to checking whether the initialization works.
3938 // FIXME: Find out whether this parameter is consumed or not.
3939 InitializedEntity Entity =
3940 InitializedEntity::InitializeParameter(S.Context, ToType,
3941 /*Consumed=*/false);
3942 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3943 Result.setUserDefined();
3944 Result.UserDefined.Before.setAsIdentityConversion();
3945 // Initializer lists don't have a type.
3946 Result.UserDefined.Before.setFromType(QualType());
3947 Result.UserDefined.Before.setAllToTypes(QualType());
3948
3949 Result.UserDefined.After.setAsIdentityConversion();
3950 Result.UserDefined.After.setFromType(ToType);
3951 Result.UserDefined.After.setAllToTypes(ToType);
3952 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003953 return Result;
3954 }
3955
3956 // C++11 [over.ics.list]p5:
3957 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00003958 if (ToType->isReferenceType()) {
3959 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
3960 // mention initializer lists in any way. So we go by what list-
3961 // initialization would do and try to extrapolate from that.
3962
3963 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
3964
3965 // If the initializer list has a single element that is reference-related
3966 // to the parameter type, we initialize the reference from that.
3967 if (From->getNumInits() == 1) {
3968 Expr *Init = From->getInit(0);
3969
3970 QualType T2 = Init->getType();
3971
3972 // If the initializer is the address of an overloaded function, try
3973 // to resolve the overloaded function. If all goes well, T2 is the
3974 // type of the resulting function.
3975 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3976 DeclAccessPair Found;
3977 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
3978 Init, ToType, false, Found))
3979 T2 = Fn->getType();
3980 }
3981
3982 // Compute some basic properties of the types and the initializer.
3983 bool dummy1 = false;
3984 bool dummy2 = false;
3985 bool dummy3 = false;
3986 Sema::ReferenceCompareResult RefRelationship
3987 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
3988 dummy2, dummy3);
3989
3990 if (RefRelationship >= Sema::Ref_Related)
3991 return TryReferenceInit(S, Init, ToType,
3992 /*FIXME:*/From->getLocStart(),
3993 SuppressUserConversions,
3994 /*AllowExplicit=*/false);
3995 }
3996
3997 // Otherwise, we bind the reference to a temporary created from the
3998 // initializer list.
3999 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4000 InOverloadResolution,
4001 AllowObjCWritebackConversion);
4002 if (Result.isFailure())
4003 return Result;
4004 assert(!Result.isEllipsis() &&
4005 "Sub-initialization cannot result in ellipsis conversion.");
4006
4007 // Can we even bind to a temporary?
4008 if (ToType->isRValueReferenceType() ||
4009 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4010 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4011 Result.UserDefined.After;
4012 SCS.ReferenceBinding = true;
4013 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4014 SCS.BindsToRvalue = true;
4015 SCS.BindsToFunctionLvalue = false;
4016 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4017 SCS.ObjCLifetimeConversionBinding = false;
4018 } else
4019 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4020 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004021 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004022 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004023
4024 // C++11 [over.ics.list]p6:
4025 // Otherwise, if the parameter type is not a class:
4026 if (!ToType->isRecordType()) {
4027 // - if the initializer list has one element, the implicit conversion
4028 // sequence is the one required to convert the element to the
4029 // parameter type.
4030 // FIXME: Catch narrowing here?
4031 unsigned NumInits = From->getNumInits();
4032 if (NumInits == 1)
4033 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4034 SuppressUserConversions,
4035 InOverloadResolution,
4036 AllowObjCWritebackConversion);
4037 // - if the initializer list has no elements, the implicit conversion
4038 // sequence is the identity conversion.
4039 else if (NumInits == 0) {
4040 Result.setStandard();
4041 Result.Standard.setAsIdentityConversion();
4042 }
4043 return Result;
4044 }
4045
4046 // C++11 [over.ics.list]p7:
4047 // In all cases other than those enumerated above, no conversion is possible
4048 return Result;
4049}
4050
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004051/// TryCopyInitialization - Try to copy-initialize a value of type
4052/// ToType from the expression From. Return the implicit conversion
4053/// sequence required to pass this argument, which may be a bad
4054/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004055/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004056/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004057static ImplicitConversionSequence
4058TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004059 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004060 bool InOverloadResolution,
4061 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004062 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4063 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4064 InOverloadResolution,AllowObjCWritebackConversion);
4065
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004066 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004067 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004068 /*FIXME:*/From->getLocStart(),
4069 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004070 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004071
John McCall5c32be02010-08-24 20:38:10 +00004072 return TryImplicitConversion(S, From, ToType,
4073 SuppressUserConversions,
4074 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004075 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004076 /*CStyle=*/false,
4077 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004078}
4079
Anna Zaks1b068122011-07-28 19:46:48 +00004080static bool TryCopyInitialization(const CanQualType FromQTy,
4081 const CanQualType ToQTy,
4082 Sema &S,
4083 SourceLocation Loc,
4084 ExprValueKind FromVK) {
4085 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4086 ImplicitConversionSequence ICS =
4087 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4088
4089 return !ICS.isBad();
4090}
4091
Douglas Gregor436424c2008-11-18 23:14:02 +00004092/// TryObjectArgumentInitialization - Try to initialize the object
4093/// parameter of the given member function (@c Method) from the
4094/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004095static ImplicitConversionSequence
4096TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004097 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004098 CXXMethodDecl *Method,
4099 CXXRecordDecl *ActingContext) {
4100 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004101 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4102 // const volatile object.
4103 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4104 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004105 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004106
4107 // Set up the conversion sequence as a "bad" conversion, to allow us
4108 // to exit early.
4109 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004110
4111 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004112 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004113 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004114 FromType = PT->getPointeeType();
4115
Douglas Gregor02824322011-01-26 19:30:28 +00004116 // When we had a pointer, it's implicitly dereferenced, so we
4117 // better have an lvalue.
4118 assert(FromClassification.isLValue());
4119 }
4120
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004121 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004122
Douglas Gregor02824322011-01-26 19:30:28 +00004123 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004124 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004125 // parameter is
4126 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004127 // - "lvalue reference to cv X" for functions declared without a
4128 // ref-qualifier or with the & ref-qualifier
4129 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004130 // ref-qualifier
4131 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004133 // cv-qualification on the member function declaration.
4134 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004135 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004136 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004137 // (C++ [over.match.funcs]p5). We perform a simplified version of
4138 // reference binding here, that allows class rvalues to bind to
4139 // non-constant references.
4140
Douglas Gregor02824322011-01-26 19:30:28 +00004141 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004142 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004144 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004145 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004146 ICS.setBad(BadConversionSequence::bad_qualifiers,
4147 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004148 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004149 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004150
4151 // Check that we have either the same type or a derived type. It
4152 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004153 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004154 ImplicitConversionKind SecondKind;
4155 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4156 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004157 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004158 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004159 else {
John McCall65eb8792010-02-25 01:37:24 +00004160 ICS.setBad(BadConversionSequence::unrelated_class,
4161 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004162 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004163 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004164
Douglas Gregor02824322011-01-26 19:30:28 +00004165 // Check the ref-qualifier.
4166 switch (Method->getRefQualifier()) {
4167 case RQ_None:
4168 // Do nothing; we don't care about lvalueness or rvalueness.
4169 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
Douglas Gregor02824322011-01-26 19:30:28 +00004171 case RQ_LValue:
4172 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4173 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004174 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004175 ImplicitParamType);
4176 return ICS;
4177 }
4178 break;
4179
4180 case RQ_RValue:
4181 if (!FromClassification.isRValue()) {
4182 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004184 ImplicitParamType);
4185 return ICS;
4186 }
4187 break;
4188 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189
Douglas Gregor436424c2008-11-18 23:14:02 +00004190 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004191 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004192 ICS.Standard.setAsIdentityConversion();
4193 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004194 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004195 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004196 ICS.Standard.ReferenceBinding = true;
4197 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004198 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004199 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004200 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4201 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4202 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004203 return ICS;
4204}
4205
4206/// PerformObjectArgumentInitialization - Perform initialization of
4207/// the implicit object parameter for the given Method with the given
4208/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004209ExprResult
4210Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004212 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004213 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004214 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004215 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004216 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004217
Douglas Gregor02824322011-01-26 19:30:28 +00004218 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004219 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004220 FromRecordType = PT->getPointeeType();
4221 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004222 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004223 } else {
4224 FromRecordType = From->getType();
4225 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004226 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004227 }
4228
John McCall6e9f8f62009-12-03 04:06:58 +00004229 // Note that we always use the true parent context when performing
4230 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004231 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004232 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4233 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004234 if (ICS.isBad()) {
4235 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4236 Qualifiers FromQs = FromRecordType.getQualifiers();
4237 Qualifiers ToQs = DestType.getQualifiers();
4238 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4239 if (CVR) {
4240 Diag(From->getSourceRange().getBegin(),
4241 diag::err_member_function_call_bad_cvr)
4242 << Method->getDeclName() << FromRecordType << (CVR - 1)
4243 << From->getSourceRange();
4244 Diag(Method->getLocation(), diag::note_previous_decl)
4245 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004246 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004247 }
4248 }
4249
Douglas Gregor436424c2008-11-18 23:14:02 +00004250 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004251 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004252 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004253 }
Mike Stump11289f42009-09-09 15:08:12 +00004254
John Wiegley01296292011-04-08 18:41:53 +00004255 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4256 ExprResult FromRes =
4257 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4258 if (FromRes.isInvalid())
4259 return ExprError();
4260 From = FromRes.take();
4261 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004262
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004263 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004264 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004265 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004266 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004267}
4268
Douglas Gregor5fb53972009-01-14 15:45:31 +00004269/// TryContextuallyConvertToBool - Attempt to contextually convert the
4270/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004271static ImplicitConversionSequence
4272TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004273 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004274 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004275 // FIXME: Are these flags correct?
4276 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004277 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004278 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004279 /*CStyle=*/false,
4280 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004281}
4282
4283/// PerformContextuallyConvertToBool - Perform a contextual conversion
4284/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004285ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004286 if (checkPlaceholderForOverload(*this, From))
4287 return ExprError();
4288
John McCall5c32be02010-08-24 20:38:10 +00004289 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004290 if (!ICS.isBad())
4291 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292
Fariborz Jahanian76197412009-11-18 18:26:29 +00004293 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004294 return Diag(From->getSourceRange().getBegin(),
4295 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004296 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004297 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004298}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299
John McCallfec112d2011-09-09 06:11:02 +00004300/// dropPointerConversions - If the given standard conversion sequence
4301/// involves any pointer conversions, remove them. This may change
4302/// the result type of the conversion sequence.
4303static void dropPointerConversion(StandardConversionSequence &SCS) {
4304 if (SCS.Second == ICK_Pointer_Conversion) {
4305 SCS.Second = ICK_Identity;
4306 SCS.Third = ICK_Identity;
4307 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4308 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004309}
John McCall5c32be02010-08-24 20:38:10 +00004310
John McCallfec112d2011-09-09 06:11:02 +00004311/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4312/// convert the expression From to an Objective-C pointer type.
4313static ImplicitConversionSequence
4314TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4315 // Do an implicit conversion to 'id'.
4316 QualType Ty = S.Context.getObjCIdType();
4317 ImplicitConversionSequence ICS
4318 = TryImplicitConversion(S, From, Ty,
4319 // FIXME: Are these flags correct?
4320 /*SuppressUserConversions=*/false,
4321 /*AllowExplicit=*/true,
4322 /*InOverloadResolution=*/false,
4323 /*CStyle=*/false,
4324 /*AllowObjCWritebackConversion=*/false);
4325
4326 // Strip off any final conversions to 'id'.
4327 switch (ICS.getKind()) {
4328 case ImplicitConversionSequence::BadConversion:
4329 case ImplicitConversionSequence::AmbiguousConversion:
4330 case ImplicitConversionSequence::EllipsisConversion:
4331 break;
4332
4333 case ImplicitConversionSequence::UserDefinedConversion:
4334 dropPointerConversion(ICS.UserDefined.After);
4335 break;
4336
4337 case ImplicitConversionSequence::StandardConversion:
4338 dropPointerConversion(ICS.Standard);
4339 break;
4340 }
4341
4342 return ICS;
4343}
4344
4345/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4346/// conversion of the expression From to an Objective-C pointer type.
4347ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004348 if (checkPlaceholderForOverload(*this, From))
4349 return ExprError();
4350
John McCall8b07ec22010-05-15 11:32:37 +00004351 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004352 ImplicitConversionSequence ICS =
4353 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004354 if (!ICS.isBad())
4355 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004356 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004357}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004358
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004359/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004360/// enumeration type.
4361///
4362/// This routine will attempt to convert an expression of class type to an
4363/// integral or enumeration type, if that class type only has a single
4364/// conversion to an integral or enumeration type.
4365///
Douglas Gregor4799d032010-06-30 00:20:43 +00004366/// \param Loc The source location of the construct that requires the
4367/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004368///
Douglas Gregor4799d032010-06-30 00:20:43 +00004369/// \param FromE The expression we're converting from.
4370///
4371/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4372/// have integral or enumeration type.
4373///
4374/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4375/// incomplete class type.
4376///
4377/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4378/// explicit conversion function (because no implicit conversion functions
4379/// were available). This is a recovery mode.
4380///
4381/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4382/// showing which conversion was picked.
4383///
4384/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4385/// conversion function that could convert to integral or enumeration type.
4386///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004387/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004388/// usable conversion function.
4389///
4390/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4391/// function, which may be an extension in this case.
4392///
4393/// \returns The expression, converted to an integral or enumeration type if
4394/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004395ExprResult
John McCallb268a282010-08-23 23:25:46 +00004396Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004397 const PartialDiagnostic &NotIntDiag,
4398 const PartialDiagnostic &IncompleteDiag,
4399 const PartialDiagnostic &ExplicitConvDiag,
4400 const PartialDiagnostic &ExplicitConvNote,
4401 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004402 const PartialDiagnostic &AmbigNote,
4403 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004404 // We can't perform any more checking for type-dependent expressions.
4405 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004406 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004408 // If the expression already has integral or enumeration type, we're golden.
4409 QualType T = From->getType();
4410 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004411 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004412
4413 // FIXME: Check for missing '()' if T is a function type?
4414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004415 // 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 +00004416 // expression of integral or enumeration type.
4417 const RecordType *RecordTy = T->getAs<RecordType>();
4418 if (!RecordTy || !getLangOptions().CPlusPlus) {
4419 Diag(Loc, NotIntDiag)
4420 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004421 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004424 // We must have a complete class type.
4425 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004426 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004427
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004428 // Look for a conversion to an integral or enumeration type.
4429 UnresolvedSet<4> ViableConversions;
4430 UnresolvedSet<4> ExplicitConversions;
4431 const UnresolvedSetImpl *Conversions
4432 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004433
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004434 bool HadMultipleCandidates = (Conversions->size() > 1);
4435
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004436 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004437 E = Conversions->end();
4438 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004439 ++I) {
4440 if (CXXConversionDecl *Conversion
4441 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4442 if (Conversion->getConversionType().getNonReferenceType()
4443 ->isIntegralOrEnumerationType()) {
4444 if (Conversion->isExplicit())
4445 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4446 else
4447 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4448 }
4449 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004451 switch (ViableConversions.size()) {
4452 case 0:
4453 if (ExplicitConversions.size() == 1) {
4454 DeclAccessPair Found = ExplicitConversions[0];
4455 CXXConversionDecl *Conversion
4456 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004458 // The user probably meant to invoke the given explicit
4459 // conversion; use it.
4460 QualType ConvTy
4461 = Conversion->getConversionType().getNonReferenceType();
4462 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004463 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004465 Diag(Loc, ExplicitConvDiag)
4466 << T << ConvTy
4467 << FixItHint::CreateInsertion(From->getLocStart(),
4468 "static_cast<" + TypeStr + ">(")
4469 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4470 ")");
4471 Diag(Conversion->getLocation(), ExplicitConvNote)
4472 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473
4474 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004475 // explicit conversion function.
4476 if (isSFINAEContext())
4477 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004478
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004479 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004480 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4481 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004482 if (Result.isInvalid())
4483 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004484 // Record usage of conversion in an implicit cast.
4485 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4486 CK_UserDefinedConversion,
4487 Result.get(), 0,
4488 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004490
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004491 // We'll complain below about a non-integral condition type.
4492 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004494 case 1: {
4495 // Apply this conversion.
4496 DeclAccessPair Found = ViableConversions[0];
4497 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498
Douglas Gregor4799d032010-06-30 00:20:43 +00004499 CXXConversionDecl *Conversion
4500 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4501 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004502 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004503 if (ConvDiag.getDiagID()) {
4504 if (isSFINAEContext())
4505 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Douglas Gregor4799d032010-06-30 00:20:43 +00004507 Diag(Loc, ConvDiag)
4508 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004510
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004511 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4512 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004513 if (Result.isInvalid())
4514 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004515 // Record usage of conversion in an implicit cast.
4516 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4517 CK_UserDefinedConversion,
4518 Result.get(), 0,
4519 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004520 break;
4521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004523 default:
4524 Diag(Loc, AmbigDiag)
4525 << T << From->getSourceRange();
4526 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4527 CXXConversionDecl *Conv
4528 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4529 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4530 Diag(Conv->getLocation(), AmbigNote)
4531 << ConvTy->isEnumeralType() << ConvTy;
4532 }
John McCallb268a282010-08-23 23:25:46 +00004533 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004535
Douglas Gregor5823da32010-06-29 23:25:20 +00004536 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004537 Diag(Loc, NotIntDiag)
4538 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004539
John McCallb268a282010-08-23 23:25:46 +00004540 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004541}
4542
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004543/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004544/// candidate functions, using the given function call arguments. If
4545/// @p SuppressUserConversions, then don't allow user-defined
4546/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004547///
4548/// \para PartialOverloading true if we are performing "partial" overloading
4549/// based on an incomplete set of function arguments. This feature is used by
4550/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004551void
4552Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004553 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004554 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004555 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004556 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004557 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004558 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004559 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004560 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004561 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004562 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004563
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004564 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004565 if (!isa<CXXConstructorDecl>(Method)) {
4566 // If we get here, it's because we're calling a member function
4567 // that is named without a member access expression (e.g.,
4568 // "this->f") that was either written explicitly or created
4569 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004570 // function, e.g., X::f(). We use an empty type for the implied
4571 // object argument (C++ [over.call.func]p3), and the acting context
4572 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004573 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004575 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004576 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004577 return;
4578 }
4579 // We treat a constructor like a non-member function, since its object
4580 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004581 }
4582
Douglas Gregorff7028a2009-11-13 23:59:09 +00004583 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004584 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004585
Douglas Gregor27381f32009-11-23 12:27:39 +00004586 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004587 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004588
Douglas Gregorffe14e32009-11-14 01:20:54 +00004589 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4590 // C++ [class.copy]p3:
4591 // A member function template is never instantiated to perform the copy
4592 // of a class object to an object of its class type.
4593 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004595 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004596 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4597 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004598 return;
4599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004600
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004601 // Add this candidate
4602 CandidateSet.push_back(OverloadCandidate());
4603 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004604 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004605 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004606 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004607 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004608 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004609 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004610
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004611 unsigned NumArgsInProto = Proto->getNumArgs();
4612
4613 // (C++ 13.3.2p2): A candidate function having fewer than m
4614 // parameters is viable only if it has an ellipsis in its parameter
4615 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004616 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004617 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004618 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004619 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004620 return;
4621 }
4622
4623 // (C++ 13.3.2p2): A candidate function having more than m parameters
4624 // is viable only if the (m+1)st parameter has a default argument
4625 // (8.3.6). For the purposes of overload resolution, the
4626 // parameter list is truncated on the right, so that there are
4627 // exactly m parameters.
4628 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004629 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004630 // Not enough arguments.
4631 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004632 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004633 return;
4634 }
4635
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004636 // (CUDA B.1): Check for invalid calls between targets.
4637 if (getLangOptions().CUDA)
4638 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4639 if (CheckCUDATarget(Caller, Function)) {
4640 Candidate.Viable = false;
4641 Candidate.FailureKind = ovl_fail_bad_target;
4642 return;
4643 }
4644
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004645 // Determine the implicit conversion sequences for each of the
4646 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004647 Candidate.Conversions.resize(NumArgs);
4648 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4649 if (ArgIdx < NumArgsInProto) {
4650 // (C++ 13.3.2p3): for F to be a viable function, there shall
4651 // exist for each argument an implicit conversion sequence
4652 // (13.3.3.1) that converts that argument to the corresponding
4653 // parameter of F.
4654 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004655 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004656 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004658 /*InOverloadResolution=*/true,
4659 /*AllowObjCWritebackConversion=*/
4660 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004661 if (Candidate.Conversions[ArgIdx].isBad()) {
4662 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004663 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004664 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004665 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004666 } else {
4667 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4668 // argument for which there is no corresponding parameter is
4669 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004670 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004671 }
4672 }
4673}
4674
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004675/// \brief Add all of the function declarations in the given function set to
4676/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004677void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004678 Expr **Args, unsigned NumArgs,
4679 OverloadCandidateSet& CandidateSet,
4680 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004681 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004682 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4683 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004684 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004685 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004686 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004687 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004689 CandidateSet, SuppressUserConversions);
4690 else
John McCalla0296f72010-03-19 07:35:19 +00004691 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004692 SuppressUserConversions);
4693 } else {
John McCalla0296f72010-03-19 07:35:19 +00004694 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004695 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4696 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004697 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004698 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004699 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004701 Args[0]->Classify(Context),
4702 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004703 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004704 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004705 else
John McCalla0296f72010-03-19 07:35:19 +00004706 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004707 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004708 Args, NumArgs, CandidateSet,
4709 SuppressUserConversions);
4710 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004711 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004712}
4713
John McCallf0f1cf02009-11-17 07:50:12 +00004714/// AddMethodCandidate - Adds a named decl (which is some kind of
4715/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004716void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004717 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004718 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004719 Expr **Args, unsigned NumArgs,
4720 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004721 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004722 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004723 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004724
4725 if (isa<UsingShadowDecl>(Decl))
4726 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004727
John McCallf0f1cf02009-11-17 07:50:12 +00004728 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4729 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4730 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004731 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4732 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004733 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004734 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004735 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004736 } else {
John McCalla0296f72010-03-19 07:35:19 +00004737 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004738 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004739 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004740 }
4741}
4742
Douglas Gregor436424c2008-11-18 23:14:02 +00004743/// AddMethodCandidate - Adds the given C++ member function to the set
4744/// of candidate functions, using the given function call arguments
4745/// and the object argument (@c Object). For example, in a call
4746/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4747/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4748/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004749/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004750void
John McCalla0296f72010-03-19 07:35:19 +00004751Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004752 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004753 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004754 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004755 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004756 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004757 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004758 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004759 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004760 assert(!isa<CXXConstructorDecl>(Method) &&
4761 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004762
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004763 if (!CandidateSet.isNewCandidate(Method))
4764 return;
4765
Douglas Gregor27381f32009-11-23 12:27:39 +00004766 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004767 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004768
Douglas Gregor436424c2008-11-18 23:14:02 +00004769 // Add this candidate
4770 CandidateSet.push_back(OverloadCandidate());
4771 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004772 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004773 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004774 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004775 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004776 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004777
4778 unsigned NumArgsInProto = Proto->getNumArgs();
4779
4780 // (C++ 13.3.2p2): A candidate function having fewer than m
4781 // parameters is viable only if it has an ellipsis in its parameter
4782 // list (8.3.5).
4783 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4784 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004785 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004786 return;
4787 }
4788
4789 // (C++ 13.3.2p2): A candidate function having more than m parameters
4790 // is viable only if the (m+1)st parameter has a default argument
4791 // (8.3.6). For the purposes of overload resolution, the
4792 // parameter list is truncated on the right, so that there are
4793 // exactly m parameters.
4794 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4795 if (NumArgs < MinRequiredArgs) {
4796 // Not enough arguments.
4797 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004798 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004799 return;
4800 }
4801
4802 Candidate.Viable = true;
4803 Candidate.Conversions.resize(NumArgs + 1);
4804
John McCall6e9f8f62009-12-03 04:06:58 +00004805 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004806 // The implicit object argument is ignored.
4807 Candidate.IgnoreObjectArgument = true;
4808 else {
4809 // Determine the implicit conversion sequence for the object
4810 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004811 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004812 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4813 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004814 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004815 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004816 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004817 return;
4818 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004819 }
4820
4821 // Determine the implicit conversion sequences for each of the
4822 // arguments.
4823 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4824 if (ArgIdx < NumArgsInProto) {
4825 // (C++ 13.3.2p3): for F to be a viable function, there shall
4826 // exist for each argument an implicit conversion sequence
4827 // (13.3.3.1) that converts that argument to the corresponding
4828 // parameter of F.
4829 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004830 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004831 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004833 /*InOverloadResolution=*/true,
4834 /*AllowObjCWritebackConversion=*/
4835 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004836 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004837 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004838 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004839 break;
4840 }
4841 } else {
4842 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4843 // argument for which there is no corresponding parameter is
4844 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004845 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004846 }
4847 }
4848}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004849
Douglas Gregor97628d62009-08-21 00:16:32 +00004850/// \brief Add a C++ member function template as a candidate to the candidate
4851/// set, using template argument deduction to produce an appropriate member
4852/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004853void
Douglas Gregor97628d62009-08-21 00:16:32 +00004854Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004855 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004856 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004857 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004858 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004859 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004860 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004861 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004862 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004863 if (!CandidateSet.isNewCandidate(MethodTmpl))
4864 return;
4865
Douglas Gregor97628d62009-08-21 00:16:32 +00004866 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004867 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004868 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004869 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004870 // candidate functions in the usual way.113) A given name can refer to one
4871 // or more function templates and also to a set of overloaded non-template
4872 // functions. In such a case, the candidate functions generated from each
4873 // function template are combined with the set of non-template candidate
4874 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004875 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004876 FunctionDecl *Specialization = 0;
4877 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004878 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004879 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004880 CandidateSet.push_back(OverloadCandidate());
4881 OverloadCandidate &Candidate = CandidateSet.back();
4882 Candidate.FoundDecl = FoundDecl;
4883 Candidate.Function = MethodTmpl->getTemplatedDecl();
4884 Candidate.Viable = false;
4885 Candidate.FailureKind = ovl_fail_bad_deduction;
4886 Candidate.IsSurrogate = false;
4887 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004888 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004890 Info);
4891 return;
4892 }
Mike Stump11289f42009-09-09 15:08:12 +00004893
Douglas Gregor97628d62009-08-21 00:16:32 +00004894 // Add the function template specialization produced by template argument
4895 // deduction as a candidate.
4896 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004897 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004898 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004899 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004900 ActingContext, ObjectType, ObjectClassification,
4901 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004902}
4903
Douglas Gregor05155d82009-08-21 23:19:43 +00004904/// \brief Add a C++ function template specialization as a candidate
4905/// in the candidate set, using template argument deduction to produce
4906/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004907void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004908Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004909 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004910 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004911 Expr **Args, unsigned NumArgs,
4912 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004913 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004914 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4915 return;
4916
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004917 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004918 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004919 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004920 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004921 // candidate functions in the usual way.113) A given name can refer to one
4922 // or more function templates and also to a set of overloaded non-template
4923 // functions. In such a case, the candidate functions generated from each
4924 // function template are combined with the set of non-template candidate
4925 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004926 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004927 FunctionDecl *Specialization = 0;
4928 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004929 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004930 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004931 CandidateSet.push_back(OverloadCandidate());
4932 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004933 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004934 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4935 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004936 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004937 Candidate.IsSurrogate = false;
4938 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004939 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004940 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004941 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004942 return;
4943 }
Mike Stump11289f42009-09-09 15:08:12 +00004944
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004945 // Add the function template specialization produced by template argument
4946 // deduction as a candidate.
4947 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004948 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004949 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004950}
Mike Stump11289f42009-09-09 15:08:12 +00004951
Douglas Gregora1f013e2008-11-07 22:36:19 +00004952/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004953/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004954/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004955/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004956/// (which may or may not be the same type as the type that the
4957/// conversion function produces).
4958void
4959Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004960 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004961 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004962 Expr *From, QualType ToType,
4963 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004964 assert(!Conversion->getDescribedFunctionTemplate() &&
4965 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004966 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004967 if (!CandidateSet.isNewCandidate(Conversion))
4968 return;
4969
Douglas Gregor27381f32009-11-23 12:27:39 +00004970 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004971 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004972
Douglas Gregora1f013e2008-11-07 22:36:19 +00004973 // Add this candidate
4974 CandidateSet.push_back(OverloadCandidate());
4975 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004976 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004977 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004978 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004979 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004980 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004981 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004982 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004983 Candidate.Viable = true;
4984 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004985 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004986
Douglas Gregor6affc782010-08-19 15:37:02 +00004987 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988 // For conversion functions, the function is considered to be a member of
4989 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004990 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004991 //
4992 // Determine the implicit conversion sequence for the implicit
4993 // object parameter.
4994 QualType ImplicitParamType = From->getType();
4995 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4996 ImplicitParamType = FromPtrType->getPointeeType();
4997 CXXRecordDecl *ConversionContext
4998 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005000 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005001 = TryObjectArgumentInitialization(*this, From->getType(),
5002 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005003 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005004
John McCall0d1da222010-01-12 00:44:57 +00005005 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005006 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005007 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005008 return;
5009 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005010
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005012 // derived to base as such conversions are given Conversion Rank. They only
5013 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5014 QualType FromCanon
5015 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5016 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5017 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5018 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005019 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005020 return;
5021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005022
Douglas Gregora1f013e2008-11-07 22:36:19 +00005023 // To determine what the conversion from the result of calling the
5024 // conversion function to the type we're eventually trying to
5025 // convert to (ToType), we need to synthesize a call to the
5026 // conversion function and attempt copy initialization from it. This
5027 // makes sure that we get the right semantics with respect to
5028 // lvalues/rvalues and the type. Fortunately, we can allocate this
5029 // call on the stack and we don't need its arguments to be
5030 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005031 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005032 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005033 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5034 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005035 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005036 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005037
Richard Smith48d24642011-07-13 22:53:21 +00005038 QualType ConversionType = Conversion->getConversionType();
5039 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005040 Candidate.Viable = false;
5041 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5042 return;
5043 }
5044
Richard Smith48d24642011-07-13 22:53:21 +00005045 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005046
Mike Stump11289f42009-09-09 15:08:12 +00005047 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005048 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5049 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005050 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005051 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005052 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005053 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005054 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005055 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005056 /*InOverloadResolution=*/false,
5057 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005058
John McCall0d1da222010-01-12 00:44:57 +00005059 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005060 case ImplicitConversionSequence::StandardConversion:
5061 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005063 // C++ [over.ics.user]p3:
5064 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005065 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005066 // shall have exact match rank.
5067 if (Conversion->getPrimaryTemplate() &&
5068 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5069 Candidate.Viable = false;
5070 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5071 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005072
Douglas Gregorcba72b12011-01-21 05:18:22 +00005073 // C++0x [dcl.init.ref]p5:
5074 // In the second case, if the reference is an rvalue reference and
5075 // the second standard conversion sequence of the user-defined
5076 // conversion sequence includes an lvalue-to-rvalue conversion, the
5077 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005078 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005079 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5080 Candidate.Viable = false;
5081 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5082 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005083 break;
5084
5085 case ImplicitConversionSequence::BadConversion:
5086 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005087 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005088 break;
5089
5090 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005091 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005092 "Can only end up with a standard conversion sequence or failure");
5093 }
5094}
5095
Douglas Gregor05155d82009-08-21 23:19:43 +00005096/// \brief Adds a conversion function template specialization
5097/// candidate to the overload set, using template argument deduction
5098/// to deduce the template arguments of the conversion function
5099/// template from the type that we are converting to (C++
5100/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005101void
Douglas Gregor05155d82009-08-21 23:19:43 +00005102Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005103 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005104 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005105 Expr *From, QualType ToType,
5106 OverloadCandidateSet &CandidateSet) {
5107 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5108 "Only conversion function templates permitted here");
5109
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005110 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5111 return;
5112
John McCallbc077cf2010-02-08 23:07:23 +00005113 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005114 CXXConversionDecl *Specialization = 0;
5115 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005116 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005117 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005118 CandidateSet.push_back(OverloadCandidate());
5119 OverloadCandidate &Candidate = CandidateSet.back();
5120 Candidate.FoundDecl = FoundDecl;
5121 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5122 Candidate.Viable = false;
5123 Candidate.FailureKind = ovl_fail_bad_deduction;
5124 Candidate.IsSurrogate = false;
5125 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005126 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005127 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005128 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005129 return;
5130 }
Mike Stump11289f42009-09-09 15:08:12 +00005131
Douglas Gregor05155d82009-08-21 23:19:43 +00005132 // Add the conversion function template specialization produced by
5133 // template argument deduction as a candidate.
5134 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005135 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005136 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005137}
5138
Douglas Gregorab7897a2008-11-19 22:57:39 +00005139/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5140/// converts the given @c Object to a function pointer via the
5141/// conversion function @c Conversion, and then attempts to call it
5142/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5143/// the type of function that we'll eventually be calling.
5144void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005145 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005146 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005147 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005148 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005149 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005150 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005151 if (!CandidateSet.isNewCandidate(Conversion))
5152 return;
5153
Douglas Gregor27381f32009-11-23 12:27:39 +00005154 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005155 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005156
Douglas Gregorab7897a2008-11-19 22:57:39 +00005157 CandidateSet.push_back(OverloadCandidate());
5158 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005159 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005160 Candidate.Function = 0;
5161 Candidate.Surrogate = Conversion;
5162 Candidate.Viable = true;
5163 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005164 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005165 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005166 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005167
5168 // Determine the implicit conversion sequence for the implicit
5169 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005170 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005172 Object->Classify(Context),
5173 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005174 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005175 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005176 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005177 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005178 return;
5179 }
5180
5181 // The first conversion is actually a user-defined conversion whose
5182 // first conversion is ObjectInit's standard conversion (which is
5183 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005184 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005185 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005186 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005187 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005188 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005189 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005190 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005191 = Candidate.Conversions[0].UserDefined.Before;
5192 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5193
Mike Stump11289f42009-09-09 15:08:12 +00005194 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005195 unsigned NumArgsInProto = Proto->getNumArgs();
5196
5197 // (C++ 13.3.2p2): A candidate function having fewer than m
5198 // parameters is viable only if it has an ellipsis in its parameter
5199 // list (8.3.5).
5200 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5201 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005202 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005203 return;
5204 }
5205
5206 // Function types don't have any default arguments, so just check if
5207 // we have enough arguments.
5208 if (NumArgs < NumArgsInProto) {
5209 // Not enough arguments.
5210 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005211 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005212 return;
5213 }
5214
5215 // Determine the implicit conversion sequences for each of the
5216 // arguments.
5217 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5218 if (ArgIdx < NumArgsInProto) {
5219 // (C++ 13.3.2p3): for F to be a viable function, there shall
5220 // exist for each argument an implicit conversion sequence
5221 // (13.3.3.1) that converts that argument to the corresponding
5222 // parameter of F.
5223 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005224 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005225 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005226 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005227 /*InOverloadResolution=*/false,
5228 /*AllowObjCWritebackConversion=*/
5229 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005230 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005231 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005232 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005233 break;
5234 }
5235 } else {
5236 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5237 // argument for which there is no corresponding parameter is
5238 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005239 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005240 }
5241 }
5242}
5243
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005244/// \brief Add overload candidates for overloaded operators that are
5245/// member functions.
5246///
5247/// Add the overloaded operator candidates that are member functions
5248/// for the operator Op that was used in an operator expression such
5249/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5250/// CandidateSet will store the added overload candidates. (C++
5251/// [over.match.oper]).
5252void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5253 SourceLocation OpLoc,
5254 Expr **Args, unsigned NumArgs,
5255 OverloadCandidateSet& CandidateSet,
5256 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005257 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5258
5259 // C++ [over.match.oper]p3:
5260 // For a unary operator @ with an operand of a type whose
5261 // cv-unqualified version is T1, and for a binary operator @ with
5262 // a left operand of a type whose cv-unqualified version is T1 and
5263 // a right operand of a type whose cv-unqualified version is T2,
5264 // three sets of candidate functions, designated member
5265 // candidates, non-member candidates and built-in candidates, are
5266 // constructed as follows:
5267 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005268
5269 // -- If T1 is a class type, the set of member candidates is the
5270 // result of the qualified lookup of T1::operator@
5271 // (13.3.1.1.1); otherwise, the set of member candidates is
5272 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005273 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005274 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005275 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005276 return;
Mike Stump11289f42009-09-09 15:08:12 +00005277
John McCall27b18f82009-11-17 02:14:36 +00005278 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5279 LookupQualifiedName(Operators, T1Rec->getDecl());
5280 Operators.suppressDiagnostics();
5281
Mike Stump11289f42009-09-09 15:08:12 +00005282 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005283 OperEnd = Operators.end();
5284 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005285 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005286 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005287 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005288 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005289 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005290 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005291}
5292
Douglas Gregora11693b2008-11-12 17:17:38 +00005293/// AddBuiltinCandidate - Add a candidate for a built-in
5294/// operator. ResultTy and ParamTys are the result and parameter types
5295/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005296/// arguments being passed to the candidate. IsAssignmentOperator
5297/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005298/// operator. NumContextualBoolArguments is the number of arguments
5299/// (at the beginning of the argument list) that will be contextually
5300/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005301void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005302 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005303 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005304 bool IsAssignmentOperator,
5305 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005306 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005307 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005308
Douglas Gregora11693b2008-11-12 17:17:38 +00005309 // Add this candidate
5310 CandidateSet.push_back(OverloadCandidate());
5311 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005312 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005313 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005314 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005315 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005316 Candidate.BuiltinTypes.ResultTy = ResultTy;
5317 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5318 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5319
5320 // Determine the implicit conversion sequences for each of the
5321 // arguments.
5322 Candidate.Viable = true;
5323 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005324 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005325 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005326 // C++ [over.match.oper]p4:
5327 // For the built-in assignment operators, conversions of the
5328 // left operand are restricted as follows:
5329 // -- no temporaries are introduced to hold the left operand, and
5330 // -- no user-defined conversions are applied to the left
5331 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005332 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005333 //
5334 // We block these conversions by turning off user-defined
5335 // conversions, since that is the only way that initialization of
5336 // a reference to a non-class type can occur from something that
5337 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005338 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005339 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005340 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005341 Candidate.Conversions[ArgIdx]
5342 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005343 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005344 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005345 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005346 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005347 /*InOverloadResolution=*/false,
5348 /*AllowObjCWritebackConversion=*/
5349 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005350 }
John McCall0d1da222010-01-12 00:44:57 +00005351 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005352 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005353 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005354 break;
5355 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005356 }
5357}
5358
5359/// BuiltinCandidateTypeSet - A set of types that will be used for the
5360/// candidate operator functions for built-in operators (C++
5361/// [over.built]). The types are separated into pointer types and
5362/// enumeration types.
5363class BuiltinCandidateTypeSet {
5364 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005365 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005366
5367 /// PointerTypes - The set of pointer types that will be used in the
5368 /// built-in candidates.
5369 TypeSet PointerTypes;
5370
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005371 /// MemberPointerTypes - The set of member pointer types that will be
5372 /// used in the built-in candidates.
5373 TypeSet MemberPointerTypes;
5374
Douglas Gregora11693b2008-11-12 17:17:38 +00005375 /// EnumerationTypes - The set of enumeration types that will be
5376 /// used in the built-in candidates.
5377 TypeSet EnumerationTypes;
5378
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005379 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005380 /// candidates.
5381 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005382
5383 /// \brief A flag indicating non-record types are viable candidates
5384 bool HasNonRecordTypes;
5385
5386 /// \brief A flag indicating whether either arithmetic or enumeration types
5387 /// were present in the candidate set.
5388 bool HasArithmeticOrEnumeralTypes;
5389
Douglas Gregor80af3132011-05-21 23:15:46 +00005390 /// \brief A flag indicating whether the nullptr type was present in the
5391 /// candidate set.
5392 bool HasNullPtrType;
5393
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005394 /// Sema - The semantic analysis instance where we are building the
5395 /// candidate type set.
5396 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005397
Douglas Gregora11693b2008-11-12 17:17:38 +00005398 /// Context - The AST context in which we will build the type sets.
5399 ASTContext &Context;
5400
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005401 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5402 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005403 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005404
5405public:
5406 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005407 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005408
Mike Stump11289f42009-09-09 15:08:12 +00005409 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005410 : HasNonRecordTypes(false),
5411 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005412 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005413 SemaRef(SemaRef),
5414 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005415
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005416 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005417 SourceLocation Loc,
5418 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005419 bool AllowExplicitConversions,
5420 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005421
5422 /// pointer_begin - First pointer type found;
5423 iterator pointer_begin() { return PointerTypes.begin(); }
5424
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005425 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005426 iterator pointer_end() { return PointerTypes.end(); }
5427
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005428 /// member_pointer_begin - First member pointer type found;
5429 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5430
5431 /// member_pointer_end - Past the last member pointer type found;
5432 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5433
Douglas Gregora11693b2008-11-12 17:17:38 +00005434 /// enumeration_begin - First enumeration type found;
5435 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5436
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005437 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005438 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005439
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005440 iterator vector_begin() { return VectorTypes.begin(); }
5441 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005442
5443 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5444 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005445 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005446};
5447
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005448/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005449/// the set of pointer types along with any more-qualified variants of
5450/// that type. For example, if @p Ty is "int const *", this routine
5451/// will add "int const *", "int const volatile *", "int const
5452/// restrict *", and "int const volatile restrict *" to the set of
5453/// pointer types. Returns true if the add of @p Ty itself succeeded,
5454/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005455///
5456/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005457bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005458BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5459 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005460
Douglas Gregora11693b2008-11-12 17:17:38 +00005461 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005462 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005463 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005464
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005465 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005466 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005467 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005468 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005469 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005470 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005471 buildObjCPtr = true;
5472 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005473 else
David Blaikie83d382b2011-09-23 05:06:16 +00005474 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005475 }
5476 else
5477 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005478
Sebastian Redl4990a632009-11-18 20:39:26 +00005479 // Don't add qualified variants of arrays. For one, they're not allowed
5480 // (the qualifier would sink to the element type), and for another, the
5481 // only overload situation where it matters is subscript or pointer +- int,
5482 // and those shouldn't have qualifier variants anyway.
5483 if (PointeeTy->isArrayType())
5484 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005485 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005486 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005487 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005488 bool hasVolatile = VisibleQuals.hasVolatile();
5489 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005490
John McCall8ccfcb52009-09-24 19:53:00 +00005491 // Iterate through all strict supersets of BaseCVR.
5492 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5493 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005494 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5495 // in the types.
5496 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5497 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005498 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005499 if (!buildObjCPtr)
5500 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5501 else
5502 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005503 }
5504
5505 return true;
5506}
5507
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005508/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5509/// to the set of pointer types along with any more-qualified variants of
5510/// that type. For example, if @p Ty is "int const *", this routine
5511/// will add "int const *", "int const volatile *", "int const
5512/// restrict *", and "int const volatile restrict *" to the set of
5513/// pointer types. Returns true if the add of @p Ty itself succeeded,
5514/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005515///
5516/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005517bool
5518BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5519 QualType Ty) {
5520 // Insert this type.
5521 if (!MemberPointerTypes.insert(Ty))
5522 return false;
5523
John McCall8ccfcb52009-09-24 19:53:00 +00005524 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5525 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005526
John McCall8ccfcb52009-09-24 19:53:00 +00005527 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005528 // Don't add qualified variants of arrays. For one, they're not allowed
5529 // (the qualifier would sink to the element type), and for another, the
5530 // only overload situation where it matters is subscript or pointer +- int,
5531 // and those shouldn't have qualifier variants anyway.
5532 if (PointeeTy->isArrayType())
5533 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005534 const Type *ClassTy = PointerTy->getClass();
5535
5536 // Iterate through all strict supersets of the pointee type's CVR
5537 // qualifiers.
5538 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5539 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5540 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005541
John McCall8ccfcb52009-09-24 19:53:00 +00005542 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005543 MemberPointerTypes.insert(
5544 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005545 }
5546
5547 return true;
5548}
5549
Douglas Gregora11693b2008-11-12 17:17:38 +00005550/// AddTypesConvertedFrom - Add each of the types to which the type @p
5551/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005552/// primarily interested in pointer types and enumeration types. We also
5553/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005554/// AllowUserConversions is true if we should look at the conversion
5555/// functions of a class type, and AllowExplicitConversions if we
5556/// should also include the explicit conversion functions of a class
5557/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005558void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005559BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005560 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005561 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005562 bool AllowExplicitConversions,
5563 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005564 // Only deal with canonical types.
5565 Ty = Context.getCanonicalType(Ty);
5566
5567 // Look through reference types; they aren't part of the type of an
5568 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005569 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005570 Ty = RefTy->getPointeeType();
5571
John McCall33ddac02011-01-19 10:06:00 +00005572 // If we're dealing with an array type, decay to the pointer.
5573 if (Ty->isArrayType())
5574 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5575
5576 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005577 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005578
Chandler Carruth00a38332010-12-13 01:44:01 +00005579 // Flag if we ever add a non-record type.
5580 const RecordType *TyRec = Ty->getAs<RecordType>();
5581 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5582
Chandler Carruth00a38332010-12-13 01:44:01 +00005583 // Flag if we encounter an arithmetic type.
5584 HasArithmeticOrEnumeralTypes =
5585 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5586
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005587 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5588 PointerTypes.insert(Ty);
5589 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005590 // Insert our type, and its more-qualified variants, into the set
5591 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005592 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005593 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005594 } else if (Ty->isMemberPointerType()) {
5595 // Member pointers are far easier, since the pointee can't be converted.
5596 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5597 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005598 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005599 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005600 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005601 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005602 // We treat vector types as arithmetic types in many contexts as an
5603 // extension.
5604 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005605 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005606 } else if (Ty->isNullPtrType()) {
5607 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005608 } else if (AllowUserConversions && TyRec) {
5609 // No conversion functions in incomplete types.
5610 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5611 return;
Mike Stump11289f42009-09-09 15:08:12 +00005612
Chandler Carruth00a38332010-12-13 01:44:01 +00005613 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5614 const UnresolvedSetImpl *Conversions
5615 = ClassDecl->getVisibleConversionFunctions();
5616 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5617 E = Conversions->end(); I != E; ++I) {
5618 NamedDecl *D = I.getDecl();
5619 if (isa<UsingShadowDecl>(D))
5620 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005621
Chandler Carruth00a38332010-12-13 01:44:01 +00005622 // Skip conversion function templates; they don't tell us anything
5623 // about which builtin types we can convert to.
5624 if (isa<FunctionTemplateDecl>(D))
5625 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005626
Chandler Carruth00a38332010-12-13 01:44:01 +00005627 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5628 if (AllowExplicitConversions || !Conv->isExplicit()) {
5629 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5630 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005631 }
5632 }
5633 }
5634}
5635
Douglas Gregor84605ae2009-08-24 13:43:27 +00005636/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5637/// the volatile- and non-volatile-qualified assignment operators for the
5638/// given type to the candidate set.
5639static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5640 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005641 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005642 unsigned NumArgs,
5643 OverloadCandidateSet &CandidateSet) {
5644 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005645
Douglas Gregor84605ae2009-08-24 13:43:27 +00005646 // T& operator=(T&, T)
5647 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5648 ParamTypes[1] = T;
5649 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5650 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005651
Douglas Gregor84605ae2009-08-24 13:43:27 +00005652 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5653 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005654 ParamTypes[0]
5655 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005656 ParamTypes[1] = T;
5657 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005658 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005659 }
5660}
Mike Stump11289f42009-09-09 15:08:12 +00005661
Sebastian Redl1054fae2009-10-25 17:03:50 +00005662/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5663/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005664static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5665 Qualifiers VRQuals;
5666 const RecordType *TyRec;
5667 if (const MemberPointerType *RHSMPType =
5668 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005669 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005670 else
5671 TyRec = ArgExpr->getType()->getAs<RecordType>();
5672 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005673 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005674 VRQuals.addVolatile();
5675 VRQuals.addRestrict();
5676 return VRQuals;
5677 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005678
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005679 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005680 if (!ClassDecl->hasDefinition())
5681 return VRQuals;
5682
John McCallad371252010-01-20 00:46:10 +00005683 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005684 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005685
John McCallad371252010-01-20 00:46:10 +00005686 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005687 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005688 NamedDecl *D = I.getDecl();
5689 if (isa<UsingShadowDecl>(D))
5690 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5691 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005692 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5693 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5694 CanTy = ResTypeRef->getPointeeType();
5695 // Need to go down the pointer/mempointer chain and add qualifiers
5696 // as see them.
5697 bool done = false;
5698 while (!done) {
5699 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5700 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005701 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005702 CanTy->getAs<MemberPointerType>())
5703 CanTy = ResTypeMPtr->getPointeeType();
5704 else
5705 done = true;
5706 if (CanTy.isVolatileQualified())
5707 VRQuals.addVolatile();
5708 if (CanTy.isRestrictQualified())
5709 VRQuals.addRestrict();
5710 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5711 return VRQuals;
5712 }
5713 }
5714 }
5715 return VRQuals;
5716}
John McCall52872982010-11-13 05:51:15 +00005717
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005718namespace {
John McCall52872982010-11-13 05:51:15 +00005719
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005720/// \brief Helper class to manage the addition of builtin operator overload
5721/// candidates. It provides shared state and utility methods used throughout
5722/// the process, as well as a helper method to add each group of builtin
5723/// operator overloads from the standard to a candidate set.
5724class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005725 // Common instance state available to all overload candidate addition methods.
5726 Sema &S;
5727 Expr **Args;
5728 unsigned NumArgs;
5729 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005730 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005731 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005732 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005733
Chandler Carruthc6586e52010-12-12 10:35:00 +00005734 // Define some constants used to index and iterate over the arithemetic types
5735 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005736 // The "promoted arithmetic types" are the arithmetic
5737 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005738 static const unsigned FirstIntegralType = 3;
5739 static const unsigned LastIntegralType = 18;
5740 static const unsigned FirstPromotedIntegralType = 3,
5741 LastPromotedIntegralType = 9;
5742 static const unsigned FirstPromotedArithmeticType = 0,
5743 LastPromotedArithmeticType = 9;
5744 static const unsigned NumArithmeticTypes = 18;
5745
Chandler Carruthc6586e52010-12-12 10:35:00 +00005746 /// \brief Get the canonical type for a given arithmetic type index.
5747 CanQualType getArithmeticType(unsigned index) {
5748 assert(index < NumArithmeticTypes);
5749 static CanQualType ASTContext::* const
5750 ArithmeticTypes[NumArithmeticTypes] = {
5751 // Start of promoted types.
5752 &ASTContext::FloatTy,
5753 &ASTContext::DoubleTy,
5754 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005755
Chandler Carruthc6586e52010-12-12 10:35:00 +00005756 // Start of integral types.
5757 &ASTContext::IntTy,
5758 &ASTContext::LongTy,
5759 &ASTContext::LongLongTy,
5760 &ASTContext::UnsignedIntTy,
5761 &ASTContext::UnsignedLongTy,
5762 &ASTContext::UnsignedLongLongTy,
5763 // End of promoted types.
5764
5765 &ASTContext::BoolTy,
5766 &ASTContext::CharTy,
5767 &ASTContext::WCharTy,
5768 &ASTContext::Char16Ty,
5769 &ASTContext::Char32Ty,
5770 &ASTContext::SignedCharTy,
5771 &ASTContext::ShortTy,
5772 &ASTContext::UnsignedCharTy,
5773 &ASTContext::UnsignedShortTy,
5774 // End of integral types.
5775 // FIXME: What about complex?
5776 };
5777 return S.Context.*ArithmeticTypes[index];
5778 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005779
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005780 /// \brief Gets the canonical type resulting from the usual arithemetic
5781 /// converions for the given arithmetic types.
5782 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5783 // Accelerator table for performing the usual arithmetic conversions.
5784 // The rules are basically:
5785 // - if either is floating-point, use the wider floating-point
5786 // - if same signedness, use the higher rank
5787 // - if same size, use unsigned of the higher rank
5788 // - use the larger type
5789 // These rules, together with the axiom that higher ranks are
5790 // never smaller, are sufficient to precompute all of these results
5791 // *except* when dealing with signed types of higher rank.
5792 // (we could precompute SLL x UI for all known platforms, but it's
5793 // better not to make any assumptions).
5794 enum PromotedType {
5795 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5796 };
5797 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5798 [LastPromotedArithmeticType] = {
5799 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5800 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5801 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5802 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5803 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5804 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5805 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5806 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5807 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5808 };
5809
5810 assert(L < LastPromotedArithmeticType);
5811 assert(R < LastPromotedArithmeticType);
5812 int Idx = ConversionsTable[L][R];
5813
5814 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005815 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005816
5817 // Slow path: we need to compare widths.
5818 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005819 CanQualType LT = getArithmeticType(L),
5820 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005821 unsigned LW = S.Context.getIntWidth(LT),
5822 RW = S.Context.getIntWidth(RT);
5823
5824 // If they're different widths, use the signed type.
5825 if (LW > RW) return LT;
5826 else if (LW < RW) return RT;
5827
5828 // Otherwise, use the unsigned type of the signed type's rank.
5829 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5830 assert(L == SLL || R == SLL);
5831 return S.Context.UnsignedLongLongTy;
5832 }
5833
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005834 /// \brief Helper method to factor out the common pattern of adding overloads
5835 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005836 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5837 bool HasVolatile) {
5838 QualType ParamTypes[2] = {
5839 S.Context.getLValueReferenceType(CandidateTy),
5840 S.Context.IntTy
5841 };
5842
5843 // Non-volatile version.
5844 if (NumArgs == 1)
5845 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5846 else
5847 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5848
5849 // Use a heuristic to reduce number of builtin candidates in the set:
5850 // add volatile version only if there are conversions to a volatile type.
5851 if (HasVolatile) {
5852 ParamTypes[0] =
5853 S.Context.getLValueReferenceType(
5854 S.Context.getVolatileType(CandidateTy));
5855 if (NumArgs == 1)
5856 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5857 else
5858 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5859 }
5860 }
5861
5862public:
5863 BuiltinOperatorOverloadBuilder(
5864 Sema &S, Expr **Args, unsigned NumArgs,
5865 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005866 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005867 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005868 OverloadCandidateSet &CandidateSet)
5869 : S(S), Args(Args), NumArgs(NumArgs),
5870 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005871 HasArithmeticOrEnumeralCandidateType(
5872 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005873 CandidateTypes(CandidateTypes),
5874 CandidateSet(CandidateSet) {
5875 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005876 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005877 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005878 assert(getArithmeticType(LastPromotedIntegralType - 1)
5879 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005880 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005881 assert(getArithmeticType(FirstPromotedArithmeticType)
5882 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005883 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005884 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5885 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005886 "Invalid last promoted arithmetic type");
5887 }
5888
5889 // C++ [over.built]p3:
5890 //
5891 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5892 // is either volatile or empty, there exist candidate operator
5893 // functions of the form
5894 //
5895 // VQ T& operator++(VQ T&);
5896 // T operator++(VQ T&, int);
5897 //
5898 // C++ [over.built]p4:
5899 //
5900 // For every pair (T, VQ), where T is an arithmetic type other
5901 // than bool, and VQ is either volatile or empty, there exist
5902 // candidate operator functions of the form
5903 //
5904 // VQ T& operator--(VQ T&);
5905 // T operator--(VQ T&, int);
5906 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005907 if (!HasArithmeticOrEnumeralCandidateType)
5908 return;
5909
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005910 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5911 Arith < NumArithmeticTypes; ++Arith) {
5912 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005913 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005914 VisibleTypeConversionsQuals.hasVolatile());
5915 }
5916 }
5917
5918 // C++ [over.built]p5:
5919 //
5920 // For every pair (T, VQ), where T is a cv-qualified or
5921 // cv-unqualified object type, and VQ is either volatile or
5922 // empty, there exist candidate operator functions of the form
5923 //
5924 // T*VQ& operator++(T*VQ&);
5925 // T*VQ& operator--(T*VQ&);
5926 // T* operator++(T*VQ&, int);
5927 // T* operator--(T*VQ&, int);
5928 void addPlusPlusMinusMinusPointerOverloads() {
5929 for (BuiltinCandidateTypeSet::iterator
5930 Ptr = CandidateTypes[0].pointer_begin(),
5931 PtrEnd = CandidateTypes[0].pointer_end();
5932 Ptr != PtrEnd; ++Ptr) {
5933 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005934 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005935 continue;
5936
5937 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5938 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5939 VisibleTypeConversionsQuals.hasVolatile()));
5940 }
5941 }
5942
5943 // C++ [over.built]p6:
5944 // For every cv-qualified or cv-unqualified object type T, there
5945 // exist candidate operator functions of the form
5946 //
5947 // T& operator*(T*);
5948 //
5949 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005950 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005951 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005952 // T& operator*(T*);
5953 void addUnaryStarPointerOverloads() {
5954 for (BuiltinCandidateTypeSet::iterator
5955 Ptr = CandidateTypes[0].pointer_begin(),
5956 PtrEnd = CandidateTypes[0].pointer_end();
5957 Ptr != PtrEnd; ++Ptr) {
5958 QualType ParamTy = *Ptr;
5959 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005960 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5961 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005962
Douglas Gregor02824322011-01-26 19:30:28 +00005963 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5964 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5965 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005966
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005967 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5968 &ParamTy, Args, 1, CandidateSet);
5969 }
5970 }
5971
5972 // C++ [over.built]p9:
5973 // For every promoted arithmetic type T, there exist candidate
5974 // operator functions of the form
5975 //
5976 // T operator+(T);
5977 // T operator-(T);
5978 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005979 if (!HasArithmeticOrEnumeralCandidateType)
5980 return;
5981
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005982 for (unsigned Arith = FirstPromotedArithmeticType;
5983 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005984 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005985 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5986 }
5987
5988 // Extension: We also add these operators for vector types.
5989 for (BuiltinCandidateTypeSet::iterator
5990 Vec = CandidateTypes[0].vector_begin(),
5991 VecEnd = CandidateTypes[0].vector_end();
5992 Vec != VecEnd; ++Vec) {
5993 QualType VecTy = *Vec;
5994 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5995 }
5996 }
5997
5998 // C++ [over.built]p8:
5999 // For every type T, there exist candidate operator functions of
6000 // the form
6001 //
6002 // T* operator+(T*);
6003 void addUnaryPlusPointerOverloads() {
6004 for (BuiltinCandidateTypeSet::iterator
6005 Ptr = CandidateTypes[0].pointer_begin(),
6006 PtrEnd = CandidateTypes[0].pointer_end();
6007 Ptr != PtrEnd; ++Ptr) {
6008 QualType ParamTy = *Ptr;
6009 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6010 }
6011 }
6012
6013 // C++ [over.built]p10:
6014 // For every promoted integral type T, there exist candidate
6015 // operator functions of the form
6016 //
6017 // T operator~(T);
6018 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006019 if (!HasArithmeticOrEnumeralCandidateType)
6020 return;
6021
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006022 for (unsigned Int = FirstPromotedIntegralType;
6023 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006024 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006025 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6026 }
6027
6028 // Extension: We also add this operator for vector types.
6029 for (BuiltinCandidateTypeSet::iterator
6030 Vec = CandidateTypes[0].vector_begin(),
6031 VecEnd = CandidateTypes[0].vector_end();
6032 Vec != VecEnd; ++Vec) {
6033 QualType VecTy = *Vec;
6034 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6035 }
6036 }
6037
6038 // C++ [over.match.oper]p16:
6039 // For every pointer to member type T, there exist candidate operator
6040 // functions of the form
6041 //
6042 // bool operator==(T,T);
6043 // bool operator!=(T,T);
6044 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6045 /// Set of (canonical) types that we've already handled.
6046 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6047
6048 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6049 for (BuiltinCandidateTypeSet::iterator
6050 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6051 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6052 MemPtr != MemPtrEnd;
6053 ++MemPtr) {
6054 // Don't add the same builtin candidate twice.
6055 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6056 continue;
6057
6058 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6059 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6060 CandidateSet);
6061 }
6062 }
6063 }
6064
6065 // C++ [over.built]p15:
6066 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006067 // For every T, where T is an enumeration type, a pointer type, or
6068 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006069 //
6070 // bool operator<(T, T);
6071 // bool operator>(T, T);
6072 // bool operator<=(T, T);
6073 // bool operator>=(T, T);
6074 // bool operator==(T, T);
6075 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006076 void addRelationalPointerOrEnumeralOverloads() {
6077 // C++ [over.built]p1:
6078 // If there is a user-written candidate with the same name and parameter
6079 // types as a built-in candidate operator function, the built-in operator
6080 // function is hidden and is not included in the set of candidate
6081 // functions.
6082 //
6083 // The text is actually in a note, but if we don't implement it then we end
6084 // up with ambiguities when the user provides an overloaded operator for
6085 // an enumeration type. Note that only enumeration types have this problem,
6086 // so we track which enumeration types we've seen operators for. Also, the
6087 // only other overloaded operator with enumeration argumenst, operator=,
6088 // cannot be overloaded for enumeration types, so this is the only place
6089 // where we must suppress candidates like this.
6090 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6091 UserDefinedBinaryOperators;
6092
6093 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6094 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6095 CandidateTypes[ArgIdx].enumeration_end()) {
6096 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6097 CEnd = CandidateSet.end();
6098 C != CEnd; ++C) {
6099 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6100 continue;
6101
6102 QualType FirstParamType =
6103 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6104 QualType SecondParamType =
6105 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6106
6107 // Skip if either parameter isn't of enumeral type.
6108 if (!FirstParamType->isEnumeralType() ||
6109 !SecondParamType->isEnumeralType())
6110 continue;
6111
6112 // Add this operator to the set of known user-defined operators.
6113 UserDefinedBinaryOperators.insert(
6114 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6115 S.Context.getCanonicalType(SecondParamType)));
6116 }
6117 }
6118 }
6119
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006120 /// Set of (canonical) types that we've already handled.
6121 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6122
6123 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6124 for (BuiltinCandidateTypeSet::iterator
6125 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6126 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6127 Ptr != PtrEnd; ++Ptr) {
6128 // Don't add the same builtin candidate twice.
6129 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6130 continue;
6131
6132 QualType ParamTypes[2] = { *Ptr, *Ptr };
6133 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6134 CandidateSet);
6135 }
6136 for (BuiltinCandidateTypeSet::iterator
6137 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6138 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6139 Enum != EnumEnd; ++Enum) {
6140 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6141
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006142 // Don't add the same builtin candidate twice, or if a user defined
6143 // candidate exists.
6144 if (!AddedTypes.insert(CanonType) ||
6145 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6146 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006147 continue;
6148
6149 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006150 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6151 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006152 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006153
6154 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6155 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6156 if (AddedTypes.insert(NullPtrTy) &&
6157 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6158 NullPtrTy))) {
6159 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6160 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6161 CandidateSet);
6162 }
6163 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006164 }
6165 }
6166
6167 // C++ [over.built]p13:
6168 //
6169 // For every cv-qualified or cv-unqualified object type T
6170 // there exist candidate operator functions of the form
6171 //
6172 // T* operator+(T*, ptrdiff_t);
6173 // T& operator[](T*, ptrdiff_t); [BELOW]
6174 // T* operator-(T*, ptrdiff_t);
6175 // T* operator+(ptrdiff_t, T*);
6176 // T& operator[](ptrdiff_t, T*); [BELOW]
6177 //
6178 // C++ [over.built]p14:
6179 //
6180 // For every T, where T is a pointer to object type, there
6181 // exist candidate operator functions of the form
6182 //
6183 // ptrdiff_t operator-(T, T);
6184 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6185 /// Set of (canonical) types that we've already handled.
6186 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6187
6188 for (int Arg = 0; Arg < 2; ++Arg) {
6189 QualType AsymetricParamTypes[2] = {
6190 S.Context.getPointerDiffType(),
6191 S.Context.getPointerDiffType(),
6192 };
6193 for (BuiltinCandidateTypeSet::iterator
6194 Ptr = CandidateTypes[Arg].pointer_begin(),
6195 PtrEnd = CandidateTypes[Arg].pointer_end();
6196 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006197 QualType PointeeTy = (*Ptr)->getPointeeType();
6198 if (!PointeeTy->isObjectType())
6199 continue;
6200
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006201 AsymetricParamTypes[Arg] = *Ptr;
6202 if (Arg == 0 || Op == OO_Plus) {
6203 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6204 // T* operator+(ptrdiff_t, T*);
6205 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6206 CandidateSet);
6207 }
6208 if (Op == OO_Minus) {
6209 // ptrdiff_t operator-(T, T);
6210 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6211 continue;
6212
6213 QualType ParamTypes[2] = { *Ptr, *Ptr };
6214 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6215 Args, 2, CandidateSet);
6216 }
6217 }
6218 }
6219 }
6220
6221 // C++ [over.built]p12:
6222 //
6223 // For every pair of promoted arithmetic types L and R, there
6224 // exist candidate operator functions of the form
6225 //
6226 // LR operator*(L, R);
6227 // LR operator/(L, R);
6228 // LR operator+(L, R);
6229 // LR operator-(L, R);
6230 // bool operator<(L, R);
6231 // bool operator>(L, R);
6232 // bool operator<=(L, R);
6233 // bool operator>=(L, R);
6234 // bool operator==(L, R);
6235 // bool operator!=(L, R);
6236 //
6237 // where LR is the result of the usual arithmetic conversions
6238 // between types L and R.
6239 //
6240 // C++ [over.built]p24:
6241 //
6242 // For every pair of promoted arithmetic types L and R, there exist
6243 // candidate operator functions of the form
6244 //
6245 // LR operator?(bool, L, R);
6246 //
6247 // where LR is the result of the usual arithmetic conversions
6248 // between types L and R.
6249 // Our candidates ignore the first parameter.
6250 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006251 if (!HasArithmeticOrEnumeralCandidateType)
6252 return;
6253
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006254 for (unsigned Left = FirstPromotedArithmeticType;
6255 Left < LastPromotedArithmeticType; ++Left) {
6256 for (unsigned Right = FirstPromotedArithmeticType;
6257 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006258 QualType LandR[2] = { getArithmeticType(Left),
6259 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006260 QualType Result =
6261 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006262 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006263 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6264 }
6265 }
6266
6267 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6268 // conditional operator for vector types.
6269 for (BuiltinCandidateTypeSet::iterator
6270 Vec1 = CandidateTypes[0].vector_begin(),
6271 Vec1End = CandidateTypes[0].vector_end();
6272 Vec1 != Vec1End; ++Vec1) {
6273 for (BuiltinCandidateTypeSet::iterator
6274 Vec2 = CandidateTypes[1].vector_begin(),
6275 Vec2End = CandidateTypes[1].vector_end();
6276 Vec2 != Vec2End; ++Vec2) {
6277 QualType LandR[2] = { *Vec1, *Vec2 };
6278 QualType Result = S.Context.BoolTy;
6279 if (!isComparison) {
6280 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6281 Result = *Vec1;
6282 else
6283 Result = *Vec2;
6284 }
6285
6286 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6287 }
6288 }
6289 }
6290
6291 // C++ [over.built]p17:
6292 //
6293 // For every pair of promoted integral types L and R, there
6294 // exist candidate operator functions of the form
6295 //
6296 // LR operator%(L, R);
6297 // LR operator&(L, R);
6298 // LR operator^(L, R);
6299 // LR operator|(L, R);
6300 // L operator<<(L, R);
6301 // L operator>>(L, R);
6302 //
6303 // where LR is the result of the usual arithmetic conversions
6304 // between types L and R.
6305 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006306 if (!HasArithmeticOrEnumeralCandidateType)
6307 return;
6308
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006309 for (unsigned Left = FirstPromotedIntegralType;
6310 Left < LastPromotedIntegralType; ++Left) {
6311 for (unsigned Right = FirstPromotedIntegralType;
6312 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006313 QualType LandR[2] = { getArithmeticType(Left),
6314 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006315 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6316 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006317 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006318 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6319 }
6320 }
6321 }
6322
6323 // C++ [over.built]p20:
6324 //
6325 // For every pair (T, VQ), where T is an enumeration or
6326 // pointer to member type and VQ is either volatile or
6327 // empty, there exist candidate operator functions of the form
6328 //
6329 // VQ T& operator=(VQ T&, T);
6330 void addAssignmentMemberPointerOrEnumeralOverloads() {
6331 /// Set of (canonical) types that we've already handled.
6332 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6333
6334 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6335 for (BuiltinCandidateTypeSet::iterator
6336 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6337 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6338 Enum != EnumEnd; ++Enum) {
6339 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6340 continue;
6341
6342 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6343 CandidateSet);
6344 }
6345
6346 for (BuiltinCandidateTypeSet::iterator
6347 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6348 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6349 MemPtr != MemPtrEnd; ++MemPtr) {
6350 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6351 continue;
6352
6353 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6354 CandidateSet);
6355 }
6356 }
6357 }
6358
6359 // C++ [over.built]p19:
6360 //
6361 // For every pair (T, VQ), where T is any type and VQ is either
6362 // volatile or empty, there exist candidate operator functions
6363 // of the form
6364 //
6365 // T*VQ& operator=(T*VQ&, T*);
6366 //
6367 // C++ [over.built]p21:
6368 //
6369 // For every pair (T, VQ), where T is a cv-qualified or
6370 // cv-unqualified object type and VQ is either volatile or
6371 // empty, there exist candidate operator functions of the form
6372 //
6373 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6374 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6375 void addAssignmentPointerOverloads(bool isEqualOp) {
6376 /// Set of (canonical) types that we've already handled.
6377 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6378
6379 for (BuiltinCandidateTypeSet::iterator
6380 Ptr = CandidateTypes[0].pointer_begin(),
6381 PtrEnd = CandidateTypes[0].pointer_end();
6382 Ptr != PtrEnd; ++Ptr) {
6383 // If this is operator=, keep track of the builtin candidates we added.
6384 if (isEqualOp)
6385 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006386 else if (!(*Ptr)->getPointeeType()->isObjectType())
6387 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006388
6389 // non-volatile version
6390 QualType ParamTypes[2] = {
6391 S.Context.getLValueReferenceType(*Ptr),
6392 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6393 };
6394 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6395 /*IsAssigmentOperator=*/ isEqualOp);
6396
6397 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6398 VisibleTypeConversionsQuals.hasVolatile()) {
6399 // volatile version
6400 ParamTypes[0] =
6401 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6402 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6403 /*IsAssigmentOperator=*/isEqualOp);
6404 }
6405 }
6406
6407 if (isEqualOp) {
6408 for (BuiltinCandidateTypeSet::iterator
6409 Ptr = CandidateTypes[1].pointer_begin(),
6410 PtrEnd = CandidateTypes[1].pointer_end();
6411 Ptr != PtrEnd; ++Ptr) {
6412 // Make sure we don't add the same candidate twice.
6413 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6414 continue;
6415
Chandler Carruth8e543b32010-12-12 08:17:55 +00006416 QualType ParamTypes[2] = {
6417 S.Context.getLValueReferenceType(*Ptr),
6418 *Ptr,
6419 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006420
6421 // non-volatile version
6422 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6423 /*IsAssigmentOperator=*/true);
6424
6425 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6426 VisibleTypeConversionsQuals.hasVolatile()) {
6427 // volatile version
6428 ParamTypes[0] =
6429 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006430 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6431 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006432 }
6433 }
6434 }
6435 }
6436
6437 // C++ [over.built]p18:
6438 //
6439 // For every triple (L, VQ, R), where L is an arithmetic type,
6440 // VQ is either volatile or empty, and R is a promoted
6441 // arithmetic type, there exist candidate operator functions of
6442 // the form
6443 //
6444 // VQ L& operator=(VQ L&, R);
6445 // VQ L& operator*=(VQ L&, R);
6446 // VQ L& operator/=(VQ L&, R);
6447 // VQ L& operator+=(VQ L&, R);
6448 // VQ L& operator-=(VQ L&, R);
6449 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006450 if (!HasArithmeticOrEnumeralCandidateType)
6451 return;
6452
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006453 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6454 for (unsigned Right = FirstPromotedArithmeticType;
6455 Right < LastPromotedArithmeticType; ++Right) {
6456 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006457 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006458
6459 // Add this built-in operator as a candidate (VQ is empty).
6460 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006461 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006462 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6463 /*IsAssigmentOperator=*/isEqualOp);
6464
6465 // Add this built-in operator as a candidate (VQ is 'volatile').
6466 if (VisibleTypeConversionsQuals.hasVolatile()) {
6467 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006468 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006469 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006470 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6471 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006472 /*IsAssigmentOperator=*/isEqualOp);
6473 }
6474 }
6475 }
6476
6477 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6478 for (BuiltinCandidateTypeSet::iterator
6479 Vec1 = CandidateTypes[0].vector_begin(),
6480 Vec1End = CandidateTypes[0].vector_end();
6481 Vec1 != Vec1End; ++Vec1) {
6482 for (BuiltinCandidateTypeSet::iterator
6483 Vec2 = CandidateTypes[1].vector_begin(),
6484 Vec2End = CandidateTypes[1].vector_end();
6485 Vec2 != Vec2End; ++Vec2) {
6486 QualType ParamTypes[2];
6487 ParamTypes[1] = *Vec2;
6488 // Add this built-in operator as a candidate (VQ is empty).
6489 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6490 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6491 /*IsAssigmentOperator=*/isEqualOp);
6492
6493 // Add this built-in operator as a candidate (VQ is 'volatile').
6494 if (VisibleTypeConversionsQuals.hasVolatile()) {
6495 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6496 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006497 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6498 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006499 /*IsAssigmentOperator=*/isEqualOp);
6500 }
6501 }
6502 }
6503 }
6504
6505 // C++ [over.built]p22:
6506 //
6507 // For every triple (L, VQ, R), where L is an integral type, VQ
6508 // is either volatile or empty, and R is a promoted integral
6509 // type, there exist candidate operator functions of the form
6510 //
6511 // VQ L& operator%=(VQ L&, R);
6512 // VQ L& operator<<=(VQ L&, R);
6513 // VQ L& operator>>=(VQ L&, R);
6514 // VQ L& operator&=(VQ L&, R);
6515 // VQ L& operator^=(VQ L&, R);
6516 // VQ L& operator|=(VQ L&, R);
6517 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006518 if (!HasArithmeticOrEnumeralCandidateType)
6519 return;
6520
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006521 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6522 for (unsigned Right = FirstPromotedIntegralType;
6523 Right < LastPromotedIntegralType; ++Right) {
6524 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006525 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006526
6527 // Add this built-in operator as a candidate (VQ is empty).
6528 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006529 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006530 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6531 if (VisibleTypeConversionsQuals.hasVolatile()) {
6532 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006533 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006534 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6535 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6536 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6537 CandidateSet);
6538 }
6539 }
6540 }
6541 }
6542
6543 // C++ [over.operator]p23:
6544 //
6545 // There also exist candidate operator functions of the form
6546 //
6547 // bool operator!(bool);
6548 // bool operator&&(bool, bool);
6549 // bool operator||(bool, bool);
6550 void addExclaimOverload() {
6551 QualType ParamTy = S.Context.BoolTy;
6552 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6553 /*IsAssignmentOperator=*/false,
6554 /*NumContextualBoolArguments=*/1);
6555 }
6556 void addAmpAmpOrPipePipeOverload() {
6557 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6558 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6559 /*IsAssignmentOperator=*/false,
6560 /*NumContextualBoolArguments=*/2);
6561 }
6562
6563 // C++ [over.built]p13:
6564 //
6565 // For every cv-qualified or cv-unqualified object type T there
6566 // exist candidate operator functions of the form
6567 //
6568 // T* operator+(T*, ptrdiff_t); [ABOVE]
6569 // T& operator[](T*, ptrdiff_t);
6570 // T* operator-(T*, ptrdiff_t); [ABOVE]
6571 // T* operator+(ptrdiff_t, T*); [ABOVE]
6572 // T& operator[](ptrdiff_t, T*);
6573 void addSubscriptOverloads() {
6574 for (BuiltinCandidateTypeSet::iterator
6575 Ptr = CandidateTypes[0].pointer_begin(),
6576 PtrEnd = CandidateTypes[0].pointer_end();
6577 Ptr != PtrEnd; ++Ptr) {
6578 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6579 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006580 if (!PointeeType->isObjectType())
6581 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006582
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006583 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6584
6585 // T& operator[](T*, ptrdiff_t)
6586 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6587 }
6588
6589 for (BuiltinCandidateTypeSet::iterator
6590 Ptr = CandidateTypes[1].pointer_begin(),
6591 PtrEnd = CandidateTypes[1].pointer_end();
6592 Ptr != PtrEnd; ++Ptr) {
6593 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6594 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006595 if (!PointeeType->isObjectType())
6596 continue;
6597
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006598 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6599
6600 // T& operator[](ptrdiff_t, T*)
6601 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6602 }
6603 }
6604
6605 // C++ [over.built]p11:
6606 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6607 // C1 is the same type as C2 or is a derived class of C2, T is an object
6608 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6609 // there exist candidate operator functions of the form
6610 //
6611 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6612 //
6613 // where CV12 is the union of CV1 and CV2.
6614 void addArrowStarOverloads() {
6615 for (BuiltinCandidateTypeSet::iterator
6616 Ptr = CandidateTypes[0].pointer_begin(),
6617 PtrEnd = CandidateTypes[0].pointer_end();
6618 Ptr != PtrEnd; ++Ptr) {
6619 QualType C1Ty = (*Ptr);
6620 QualType C1;
6621 QualifierCollector Q1;
6622 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6623 if (!isa<RecordType>(C1))
6624 continue;
6625 // heuristic to reduce number of builtin candidates in the set.
6626 // Add volatile/restrict version only if there are conversions to a
6627 // volatile/restrict type.
6628 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6629 continue;
6630 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6631 continue;
6632 for (BuiltinCandidateTypeSet::iterator
6633 MemPtr = CandidateTypes[1].member_pointer_begin(),
6634 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6635 MemPtr != MemPtrEnd; ++MemPtr) {
6636 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6637 QualType C2 = QualType(mptr->getClass(), 0);
6638 C2 = C2.getUnqualifiedType();
6639 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6640 break;
6641 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6642 // build CV12 T&
6643 QualType T = mptr->getPointeeType();
6644 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6645 T.isVolatileQualified())
6646 continue;
6647 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6648 T.isRestrictQualified())
6649 continue;
6650 T = Q1.apply(S.Context, T);
6651 QualType ResultTy = S.Context.getLValueReferenceType(T);
6652 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6653 }
6654 }
6655 }
6656
6657 // Note that we don't consider the first argument, since it has been
6658 // contextually converted to bool long ago. The candidates below are
6659 // therefore added as binary.
6660 //
6661 // C++ [over.built]p25:
6662 // For every type T, where T is a pointer, pointer-to-member, or scoped
6663 // enumeration type, there exist candidate operator functions of the form
6664 //
6665 // T operator?(bool, T, T);
6666 //
6667 void addConditionalOperatorOverloads() {
6668 /// Set of (canonical) types that we've already handled.
6669 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6670
6671 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6672 for (BuiltinCandidateTypeSet::iterator
6673 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6674 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6675 Ptr != PtrEnd; ++Ptr) {
6676 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6677 continue;
6678
6679 QualType ParamTypes[2] = { *Ptr, *Ptr };
6680 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6681 }
6682
6683 for (BuiltinCandidateTypeSet::iterator
6684 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6685 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6686 MemPtr != MemPtrEnd; ++MemPtr) {
6687 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6688 continue;
6689
6690 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6691 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6692 }
6693
6694 if (S.getLangOptions().CPlusPlus0x) {
6695 for (BuiltinCandidateTypeSet::iterator
6696 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6697 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6698 Enum != EnumEnd; ++Enum) {
6699 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6700 continue;
6701
6702 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6703 continue;
6704
6705 QualType ParamTypes[2] = { *Enum, *Enum };
6706 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6707 }
6708 }
6709 }
6710 }
6711};
6712
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006713} // end anonymous namespace
6714
6715/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6716/// operator overloads to the candidate set (C++ [over.built]), based
6717/// on the operator @p Op and the arguments given. For example, if the
6718/// operator is a binary '+', this routine might add "int
6719/// operator+(int, int)" to cover integer addition.
6720void
6721Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6722 SourceLocation OpLoc,
6723 Expr **Args, unsigned NumArgs,
6724 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006725 // Find all of the types that the arguments can convert to, but only
6726 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006727 // that make use of these types. Also record whether we encounter non-record
6728 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006729 Qualifiers VisibleTypeConversionsQuals;
6730 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006731 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6732 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006733
6734 bool HasNonRecordCandidateType = false;
6735 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006736 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006737 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6738 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6739 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6740 OpLoc,
6741 true,
6742 (Op == OO_Exclaim ||
6743 Op == OO_AmpAmp ||
6744 Op == OO_PipePipe),
6745 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006746 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6747 CandidateTypes[ArgIdx].hasNonRecordTypes();
6748 HasArithmeticOrEnumeralCandidateType =
6749 HasArithmeticOrEnumeralCandidateType ||
6750 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006751 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006752
Chandler Carruth00a38332010-12-13 01:44:01 +00006753 // Exit early when no non-record types have been added to the candidate set
6754 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006755 //
6756 // We can't exit early for !, ||, or &&, since there we have always have
6757 // 'bool' overloads.
6758 if (!HasNonRecordCandidateType &&
6759 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006760 return;
6761
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006762 // Setup an object to manage the common state for building overloads.
6763 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6764 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006765 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006766 CandidateTypes, CandidateSet);
6767
6768 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006769 switch (Op) {
6770 case OO_None:
6771 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006772 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006773
Chandler Carruth5184de02010-12-12 08:51:33 +00006774 case OO_New:
6775 case OO_Delete:
6776 case OO_Array_New:
6777 case OO_Array_Delete:
6778 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006779 llvm_unreachable(
6780 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006781
6782 case OO_Comma:
6783 case OO_Arrow:
6784 // C++ [over.match.oper]p3:
6785 // -- For the operator ',', the unary operator '&', or the
6786 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006787 break;
6788
6789 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006790 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006791 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006792 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006793
6794 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006795 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006796 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006797 } else {
6798 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6799 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6800 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006801 break;
6802
Chandler Carruth5184de02010-12-12 08:51:33 +00006803 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006804 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006805 OpBuilder.addUnaryStarPointerOverloads();
6806 else
6807 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6808 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006809
Chandler Carruth5184de02010-12-12 08:51:33 +00006810 case OO_Slash:
6811 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006812 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006813
6814 case OO_PlusPlus:
6815 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006816 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6817 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006818 break;
6819
Douglas Gregor84605ae2009-08-24 13:43:27 +00006820 case OO_EqualEqual:
6821 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006822 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006823 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006824
Douglas Gregora11693b2008-11-12 17:17:38 +00006825 case OO_Less:
6826 case OO_Greater:
6827 case OO_LessEqual:
6828 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006829 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006830 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6831 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006832
Douglas Gregora11693b2008-11-12 17:17:38 +00006833 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006834 case OO_Caret:
6835 case OO_Pipe:
6836 case OO_LessLess:
6837 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006838 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006839 break;
6840
Chandler Carruth5184de02010-12-12 08:51:33 +00006841 case OO_Amp: // '&' is either unary or binary
6842 if (NumArgs == 1)
6843 // C++ [over.match.oper]p3:
6844 // -- For the operator ',', the unary operator '&', or the
6845 // operator '->', the built-in candidates set is empty.
6846 break;
6847
6848 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6849 break;
6850
6851 case OO_Tilde:
6852 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6853 break;
6854
Douglas Gregora11693b2008-11-12 17:17:38 +00006855 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006856 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006857 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006858
6859 case OO_PlusEqual:
6860 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006861 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006862 // Fall through.
6863
6864 case OO_StarEqual:
6865 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006866 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006867 break;
6868
6869 case OO_PercentEqual:
6870 case OO_LessLessEqual:
6871 case OO_GreaterGreaterEqual:
6872 case OO_AmpEqual:
6873 case OO_CaretEqual:
6874 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006875 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006876 break;
6877
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006878 case OO_Exclaim:
6879 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006880 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006881
Douglas Gregora11693b2008-11-12 17:17:38 +00006882 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006883 case OO_PipePipe:
6884 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006885 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006886
6887 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006888 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006889 break;
6890
6891 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006892 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006893 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006894
6895 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006896 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006897 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6898 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006899 }
6900}
6901
Douglas Gregore254f902009-02-04 00:32:51 +00006902/// \brief Add function candidates found via argument-dependent lookup
6903/// to the set of overloading candidates.
6904///
6905/// This routine performs argument-dependent name lookup based on the
6906/// given function name (which may also be an operator name) and adds
6907/// all of the overload candidates found by ADL to the overload
6908/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006909void
Douglas Gregore254f902009-02-04 00:32:51 +00006910Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006911 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006912 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006913 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006914 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006915 bool PartialOverloading,
6916 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006917 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006918
John McCall91f61fc2010-01-26 06:04:06 +00006919 // FIXME: This approach for uniquing ADL results (and removing
6920 // redundant candidates from the set) relies on pointer-equality,
6921 // which means we need to key off the canonical decl. However,
6922 // always going back to the canonical decl might not get us the
6923 // right set of default arguments. What default arguments are
6924 // we supposed to consider on ADL candidates, anyway?
6925
Douglas Gregorcabea402009-09-22 15:41:20 +00006926 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006927 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6928 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006929
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006930 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006931 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6932 CandEnd = CandidateSet.end();
6933 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006934 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006935 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006936 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006937 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006938 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006939
6940 // For each of the ADL candidates we found, add it to the overload
6941 // set.
John McCall8fe68082010-01-26 07:16:45 +00006942 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006943 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006944 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006945 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006946 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006947
John McCalla0296f72010-03-19 07:35:19 +00006948 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006949 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006950 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006951 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006952 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006953 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006954 }
Douglas Gregore254f902009-02-04 00:32:51 +00006955}
6956
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006957/// isBetterOverloadCandidate - Determines whether the first overload
6958/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006959bool
John McCall5c32be02010-08-24 20:38:10 +00006960isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006961 const OverloadCandidate &Cand1,
6962 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006963 SourceLocation Loc,
6964 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006965 // Define viable functions to be better candidates than non-viable
6966 // functions.
6967 if (!Cand2.Viable)
6968 return Cand1.Viable;
6969 else if (!Cand1.Viable)
6970 return false;
6971
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006972 // C++ [over.match.best]p1:
6973 //
6974 // -- if F is a static member function, ICS1(F) is defined such
6975 // that ICS1(F) is neither better nor worse than ICS1(G) for
6976 // any function G, and, symmetrically, ICS1(G) is neither
6977 // better nor worse than ICS1(F).
6978 unsigned StartArg = 0;
6979 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6980 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006981
Douglas Gregord3cb3562009-07-07 23:38:56 +00006982 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006983 // A viable function F1 is defined to be a better function than another
6984 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006985 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006986 unsigned NumArgs = Cand1.Conversions.size();
6987 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6988 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006989 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006990 switch (CompareImplicitConversionSequences(S,
6991 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006992 Cand2.Conversions[ArgIdx])) {
6993 case ImplicitConversionSequence::Better:
6994 // Cand1 has a better conversion sequence.
6995 HasBetterConversion = true;
6996 break;
6997
6998 case ImplicitConversionSequence::Worse:
6999 // Cand1 can't be better than Cand2.
7000 return false;
7001
7002 case ImplicitConversionSequence::Indistinguishable:
7003 // Do nothing.
7004 break;
7005 }
7006 }
7007
Mike Stump11289f42009-09-09 15:08:12 +00007008 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007009 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007010 if (HasBetterConversion)
7011 return true;
7012
Mike Stump11289f42009-09-09 15:08:12 +00007013 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007014 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007015 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007016 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7017 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007018
7019 // -- F1 and F2 are function template specializations, and the function
7020 // template for F1 is more specialized than the template for F2
7021 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007022 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007023 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007024 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007025 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007026 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7027 Cand2.Function->getPrimaryTemplate(),
7028 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007030 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007031 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007032 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007033 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007034
Douglas Gregora1f013e2008-11-07 22:36:19 +00007035 // -- the context is an initialization by user-defined conversion
7036 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7037 // from the return type of F1 to the destination type (i.e.,
7038 // the type of the entity being initialized) is a better
7039 // conversion sequence than the standard conversion sequence
7040 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007041 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007042 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007043 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00007044 switch (CompareStandardConversionSequences(S,
7045 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007046 Cand2.FinalConversion)) {
7047 case ImplicitConversionSequence::Better:
7048 // Cand1 has a better conversion sequence.
7049 return true;
7050
7051 case ImplicitConversionSequence::Worse:
7052 // Cand1 can't be better than Cand2.
7053 return false;
7054
7055 case ImplicitConversionSequence::Indistinguishable:
7056 // Do nothing
7057 break;
7058 }
7059 }
7060
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007061 return false;
7062}
7063
Mike Stump11289f42009-09-09 15:08:12 +00007064/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007065/// within an overload candidate set.
7066///
7067/// \param CandidateSet the set of candidate functions.
7068///
7069/// \param Loc the location of the function name (or operator symbol) for
7070/// which overload resolution occurs.
7071///
Mike Stump11289f42009-09-09 15:08:12 +00007072/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007073/// function, Best points to the candidate function found.
7074///
7075/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007076OverloadingResult
7077OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007078 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007079 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007080 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007081 Best = end();
7082 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7083 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007084 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007085 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007086 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007087 }
7088
7089 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007090 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007091 return OR_No_Viable_Function;
7092
7093 // Make sure that this function is better than every other viable
7094 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007095 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007096 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007097 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007099 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007100 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007101 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007102 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007103 }
Mike Stump11289f42009-09-09 15:08:12 +00007104
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007105 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007106 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007107 (Best->Function->isDeleted() ||
7108 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007109 return OR_Deleted;
7110
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007111 return OR_Success;
7112}
7113
John McCall53262c92010-01-12 02:15:36 +00007114namespace {
7115
7116enum OverloadCandidateKind {
7117 oc_function,
7118 oc_method,
7119 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007120 oc_function_template,
7121 oc_method_template,
7122 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007123 oc_implicit_default_constructor,
7124 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007125 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007126 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007127 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007128 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007129};
7130
John McCalle1ac8d12010-01-13 00:25:19 +00007131OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7132 FunctionDecl *Fn,
7133 std::string &Description) {
7134 bool isTemplate = false;
7135
7136 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7137 isTemplate = true;
7138 Description = S.getTemplateArgumentBindingsText(
7139 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7140 }
John McCallfd0b2f82010-01-06 09:43:14 +00007141
7142 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007143 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007144 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007145
Sebastian Redl08905022011-02-05 19:23:19 +00007146 if (Ctor->getInheritedConstructor())
7147 return oc_implicit_inherited_constructor;
7148
Alexis Hunt119c10e2011-05-25 23:16:36 +00007149 if (Ctor->isDefaultConstructor())
7150 return oc_implicit_default_constructor;
7151
7152 if (Ctor->isMoveConstructor())
7153 return oc_implicit_move_constructor;
7154
7155 assert(Ctor->isCopyConstructor() &&
7156 "unexpected sort of implicit constructor");
7157 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007158 }
7159
7160 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7161 // This actually gets spelled 'candidate function' for now, but
7162 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007163 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007164 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007165
Alexis Hunt119c10e2011-05-25 23:16:36 +00007166 if (Meth->isMoveAssignmentOperator())
7167 return oc_implicit_move_assignment;
7168
Douglas Gregorec3bec02010-09-27 22:37:28 +00007169 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007170 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007171 return oc_implicit_copy_assignment;
7172 }
7173
John McCalle1ac8d12010-01-13 00:25:19 +00007174 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007175}
7176
Sebastian Redl08905022011-02-05 19:23:19 +00007177void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7178 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7179 if (!Ctor) return;
7180
7181 Ctor = Ctor->getInheritedConstructor();
7182 if (!Ctor) return;
7183
7184 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7185}
7186
John McCall53262c92010-01-12 02:15:36 +00007187} // end anonymous namespace
7188
7189// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007190void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007191 std::string FnDesc;
7192 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007193 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7194 << (unsigned) K << FnDesc;
7195 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7196 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007197 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007198}
7199
Douglas Gregorb491ed32011-02-19 21:32:49 +00007200//Notes the location of all overload candidates designated through
7201// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007202void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007203 assert(OverloadedExpr->getType() == Context.OverloadTy);
7204
7205 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7206 OverloadExpr *OvlExpr = Ovl.Expression;
7207
7208 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7209 IEnd = OvlExpr->decls_end();
7210 I != IEnd; ++I) {
7211 if (FunctionTemplateDecl *FunTmpl =
7212 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007213 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007214 } else if (FunctionDecl *Fun
7215 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007216 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007217 }
7218 }
7219}
7220
John McCall0d1da222010-01-12 00:44:57 +00007221/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7222/// "lead" diagnostic; it will be given two arguments, the source and
7223/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007224void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7225 Sema &S,
7226 SourceLocation CaretLoc,
7227 const PartialDiagnostic &PDiag) const {
7228 S.Diag(CaretLoc, PDiag)
7229 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007230 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007231 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7232 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007233 }
John McCall12f97bc2010-01-08 04:41:39 +00007234}
7235
John McCall0d1da222010-01-12 00:44:57 +00007236namespace {
7237
John McCall6a61b522010-01-13 09:16:55 +00007238void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7239 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7240 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007241 assert(Cand->Function && "for now, candidate must be a function");
7242 FunctionDecl *Fn = Cand->Function;
7243
7244 // There's a conversion slot for the object argument if this is a
7245 // non-constructor method. Note that 'I' corresponds the
7246 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007247 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007248 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007249 if (I == 0)
7250 isObjectArgument = true;
7251 else
7252 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007253 }
7254
John McCalle1ac8d12010-01-13 00:25:19 +00007255 std::string FnDesc;
7256 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7257
John McCall6a61b522010-01-13 09:16:55 +00007258 Expr *FromExpr = Conv.Bad.FromExpr;
7259 QualType FromTy = Conv.Bad.getFromType();
7260 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007261
John McCallfb7ad0f2010-02-02 02:42:52 +00007262 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007263 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007264 Expr *E = FromExpr->IgnoreParens();
7265 if (isa<UnaryOperator>(E))
7266 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007267 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007268
7269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7270 << (unsigned) FnKind << FnDesc
7271 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7272 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007273 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007274 return;
7275 }
7276
John McCall6d174642010-01-23 08:10:49 +00007277 // Do some hand-waving analysis to see if the non-viability is due
7278 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007279 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7280 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7281 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7282 CToTy = RT->getPointeeType();
7283 else {
7284 // TODO: detect and diagnose the full richness of const mismatches.
7285 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7286 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7287 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7288 }
7289
7290 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7291 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7292 // It is dumb that we have to do this here.
7293 while (isa<ArrayType>(CFromTy))
7294 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7295 while (isa<ArrayType>(CToTy))
7296 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7297
7298 Qualifiers FromQs = CFromTy.getQualifiers();
7299 Qualifiers ToQs = CToTy.getQualifiers();
7300
7301 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7302 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7303 << (unsigned) FnKind << FnDesc
7304 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7305 << FromTy
7306 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7307 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007308 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007309 return;
7310 }
7311
John McCall31168b02011-06-15 23:02:42 +00007312 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007313 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007314 << (unsigned) FnKind << FnDesc
7315 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7316 << FromTy
7317 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7318 << (unsigned) isObjectArgument << I+1;
7319 MaybeEmitInheritedConstructorNote(S, Fn);
7320 return;
7321 }
7322
Douglas Gregoraec25842011-04-26 23:16:46 +00007323 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7324 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7325 << (unsigned) FnKind << FnDesc
7326 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7327 << FromTy
7328 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7329 << (unsigned) isObjectArgument << I+1;
7330 MaybeEmitInheritedConstructorNote(S, Fn);
7331 return;
7332 }
7333
John McCall47000992010-01-14 03:28:57 +00007334 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7335 assert(CVR && "unexpected qualifiers mismatch");
7336
7337 if (isObjectArgument) {
7338 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7339 << (unsigned) FnKind << FnDesc
7340 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7341 << FromTy << (CVR - 1);
7342 } else {
7343 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7344 << (unsigned) FnKind << FnDesc
7345 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7346 << FromTy << (CVR - 1) << I+1;
7347 }
Sebastian Redl08905022011-02-05 19:23:19 +00007348 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007349 return;
7350 }
7351
Sebastian Redla72462c2011-09-24 17:48:32 +00007352 // Special diagnostic for failure to convert an initializer list, since
7353 // telling the user that it has type void is not useful.
7354 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7355 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7356 << (unsigned) FnKind << FnDesc
7357 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7358 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7359 MaybeEmitInheritedConstructorNote(S, Fn);
7360 return;
7361 }
7362
John McCall6d174642010-01-23 08:10:49 +00007363 // Diagnose references or pointers to incomplete types differently,
7364 // since it's far from impossible that the incompleteness triggered
7365 // the failure.
7366 QualType TempFromTy = FromTy.getNonReferenceType();
7367 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7368 TempFromTy = PTy->getPointeeType();
7369 if (TempFromTy->isIncompleteType()) {
7370 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7371 << (unsigned) FnKind << FnDesc
7372 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7373 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007374 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007375 return;
7376 }
7377
Douglas Gregor56f2e342010-06-30 23:01:39 +00007378 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007379 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007380 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7381 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7382 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7383 FromPtrTy->getPointeeType()) &&
7384 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7385 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007386 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007387 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007388 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007389 }
7390 } else if (const ObjCObjectPointerType *FromPtrTy
7391 = FromTy->getAs<ObjCObjectPointerType>()) {
7392 if (const ObjCObjectPointerType *ToPtrTy
7393 = ToTy->getAs<ObjCObjectPointerType>())
7394 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7395 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7396 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7397 FromPtrTy->getPointeeType()) &&
7398 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007399 BaseToDerivedConversion = 2;
7400 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7401 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7402 !FromTy->isIncompleteType() &&
7403 !ToRefTy->getPointeeType()->isIncompleteType() &&
7404 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7405 BaseToDerivedConversion = 3;
7406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007407
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007408 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007409 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007410 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007411 << (unsigned) FnKind << FnDesc
7412 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007413 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007414 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007415 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007416 return;
7417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007418
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007419 if (isa<ObjCObjectPointerType>(CFromTy) &&
7420 isa<PointerType>(CToTy)) {
7421 Qualifiers FromQs = CFromTy.getQualifiers();
7422 Qualifiers ToQs = CToTy.getQualifiers();
7423 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7425 << (unsigned) FnKind << FnDesc
7426 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7427 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7428 MaybeEmitInheritedConstructorNote(S, Fn);
7429 return;
7430 }
7431 }
7432
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007433 // Emit the generic diagnostic and, optionally, add the hints to it.
7434 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7435 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007436 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007437 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7438 << (unsigned) (Cand->Fix.Kind);
7439
7440 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007441 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007442 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7443 HI != HE; ++HI)
7444 FDiag << *HI;
7445 S.Diag(Fn->getLocation(), FDiag);
7446
Sebastian Redl08905022011-02-05 19:23:19 +00007447 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007448}
7449
7450void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7451 unsigned NumFormalArgs) {
7452 // TODO: treat calls to a missing default constructor as a special case
7453
7454 FunctionDecl *Fn = Cand->Function;
7455 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7456
7457 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007458
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007459 // With invalid overloaded operators, it's possible that we think we
7460 // have an arity mismatch when it fact it looks like we have the
7461 // right number of arguments, because only overloaded operators have
7462 // the weird behavior of overloading member and non-member functions.
7463 // Just don't report anything.
7464 if (Fn->isInvalidDecl() &&
7465 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7466 return;
7467
John McCall6a61b522010-01-13 09:16:55 +00007468 // at least / at most / exactly
7469 unsigned mode, modeCount;
7470 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007471 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7472 (Cand->FailureKind == ovl_fail_bad_deduction &&
7473 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007475 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007476 mode = 0; // "at least"
7477 else
7478 mode = 2; // "exactly"
7479 modeCount = MinParams;
7480 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007481 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7482 (Cand->FailureKind == ovl_fail_bad_deduction &&
7483 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007484 if (MinParams != FnTy->getNumArgs())
7485 mode = 1; // "at most"
7486 else
7487 mode = 2; // "exactly"
7488 modeCount = FnTy->getNumArgs();
7489 }
7490
7491 std::string Description;
7492 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7493
7494 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007495 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007496 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007497 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007498}
7499
John McCall8b9ed552010-02-01 18:53:26 +00007500/// Diagnose a failed template-argument deduction.
7501void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7502 Expr **Args, unsigned NumArgs) {
7503 FunctionDecl *Fn = Cand->Function; // pattern
7504
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007505 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007506 NamedDecl *ParamD;
7507 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7508 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7509 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007510 switch (Cand->DeductionFailure.Result) {
7511 case Sema::TDK_Success:
7512 llvm_unreachable("TDK_success while diagnosing bad deduction");
7513
7514 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007515 assert(ParamD && "no parameter found for incomplete deduction result");
7516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7517 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007518 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007519 return;
7520 }
7521
John McCall42d7d192010-08-05 09:05:08 +00007522 case Sema::TDK_Underqualified: {
7523 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7524 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7525
7526 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7527
7528 // Param will have been canonicalized, but it should just be a
7529 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007530 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007531 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007532 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007533 assert(S.Context.hasSameType(Param, NonCanonParam));
7534
7535 // Arg has also been canonicalized, but there's nothing we can do
7536 // about that. It also doesn't matter as much, because it won't
7537 // have any template parameters in it (because deduction isn't
7538 // done on dependent types).
7539 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7540
7541 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7542 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007543 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007544 return;
7545 }
7546
7547 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007548 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007549 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007550 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007551 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007552 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007553 which = 1;
7554 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007555 which = 2;
7556 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007557
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007558 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007559 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007560 << *Cand->DeductionFailure.getFirstArg()
7561 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007562 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007563 return;
7564 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007565
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007566 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007567 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007568 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007570 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7571 << ParamD->getDeclName();
7572 else {
7573 int index = 0;
7574 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7575 index = TTP->getIndex();
7576 else if (NonTypeTemplateParmDecl *NTTP
7577 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7578 index = NTTP->getIndex();
7579 else
7580 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007581 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007582 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7583 << (index + 1);
7584 }
Sebastian Redl08905022011-02-05 19:23:19 +00007585 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007586 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007587
Douglas Gregor02eb4832010-05-08 18:13:28 +00007588 case Sema::TDK_TooManyArguments:
7589 case Sema::TDK_TooFewArguments:
7590 DiagnoseArityMismatch(S, Cand, NumArgs);
7591 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007592
7593 case Sema::TDK_InstantiationDepth:
7594 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007595 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007596 return;
7597
7598 case Sema::TDK_SubstitutionFailure: {
7599 std::string ArgString;
7600 if (TemplateArgumentList *Args
7601 = Cand->DeductionFailure.getTemplateArgumentList())
7602 ArgString = S.getTemplateArgumentBindingsText(
7603 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7604 *Args);
7605 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7606 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007607 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007608 return;
7609 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007610
John McCall8b9ed552010-02-01 18:53:26 +00007611 // TODO: diagnose these individually, then kill off
7612 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007613 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007614 case Sema::TDK_FailedOverloadResolution:
7615 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007616 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007617 return;
7618 }
7619}
7620
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007621/// CUDA: diagnose an invalid call across targets.
7622void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7623 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7624 FunctionDecl *Callee = Cand->Function;
7625
7626 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7627 CalleeTarget = S.IdentifyCUDATarget(Callee);
7628
7629 std::string FnDesc;
7630 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7631
7632 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7633 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7634}
7635
John McCall8b9ed552010-02-01 18:53:26 +00007636/// Generates a 'note' diagnostic for an overload candidate. We've
7637/// already generated a primary error at the call site.
7638///
7639/// It really does need to be a single diagnostic with its caret
7640/// pointed at the candidate declaration. Yes, this creates some
7641/// major challenges of technical writing. Yes, this makes pointing
7642/// out problems with specific arguments quite awkward. It's still
7643/// better than generating twenty screens of text for every failed
7644/// overload.
7645///
7646/// It would be great to be able to express per-candidate problems
7647/// more richly for those diagnostic clients that cared, but we'd
7648/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007649void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7650 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007651 FunctionDecl *Fn = Cand->Function;
7652
John McCall12f97bc2010-01-08 04:41:39 +00007653 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007654 if (Cand->Viable && (Fn->isDeleted() ||
7655 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007656 std::string FnDesc;
7657 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007658
7659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007660 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007661 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007662 return;
John McCall12f97bc2010-01-08 04:41:39 +00007663 }
7664
John McCalle1ac8d12010-01-13 00:25:19 +00007665 // We don't really have anything else to say about viable candidates.
7666 if (Cand->Viable) {
7667 S.NoteOverloadCandidate(Fn);
7668 return;
7669 }
John McCall0d1da222010-01-12 00:44:57 +00007670
John McCall6a61b522010-01-13 09:16:55 +00007671 switch (Cand->FailureKind) {
7672 case ovl_fail_too_many_arguments:
7673 case ovl_fail_too_few_arguments:
7674 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007675
John McCall6a61b522010-01-13 09:16:55 +00007676 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007677 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7678
John McCallfe796dd2010-01-23 05:17:32 +00007679 case ovl_fail_trivial_conversion:
7680 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007681 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007682 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007683
John McCall65eb8792010-02-25 01:37:24 +00007684 case ovl_fail_bad_conversion: {
7685 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7686 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007687 if (Cand->Conversions[I].isBad())
7688 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007689
John McCall6a61b522010-01-13 09:16:55 +00007690 // FIXME: this currently happens when we're called from SemaInit
7691 // when user-conversion overload fails. Figure out how to handle
7692 // those conditions and diagnose them well.
7693 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007694 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007695
7696 case ovl_fail_bad_target:
7697 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007698 }
John McCalld3224162010-01-08 00:58:21 +00007699}
7700
7701void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7702 // Desugar the type of the surrogate down to a function type,
7703 // retaining as many typedefs as possible while still showing
7704 // the function type (and, therefore, its parameter types).
7705 QualType FnType = Cand->Surrogate->getConversionType();
7706 bool isLValueReference = false;
7707 bool isRValueReference = false;
7708 bool isPointer = false;
7709 if (const LValueReferenceType *FnTypeRef =
7710 FnType->getAs<LValueReferenceType>()) {
7711 FnType = FnTypeRef->getPointeeType();
7712 isLValueReference = true;
7713 } else if (const RValueReferenceType *FnTypeRef =
7714 FnType->getAs<RValueReferenceType>()) {
7715 FnType = FnTypeRef->getPointeeType();
7716 isRValueReference = true;
7717 }
7718 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7719 FnType = FnTypePtr->getPointeeType();
7720 isPointer = true;
7721 }
7722 // Desugar down to a function type.
7723 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7724 // Reconstruct the pointer/reference as appropriate.
7725 if (isPointer) FnType = S.Context.getPointerType(FnType);
7726 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7727 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7728
7729 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7730 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007731 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007732}
7733
7734void NoteBuiltinOperatorCandidate(Sema &S,
7735 const char *Opc,
7736 SourceLocation OpLoc,
7737 OverloadCandidate *Cand) {
7738 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7739 std::string TypeStr("operator");
7740 TypeStr += Opc;
7741 TypeStr += "(";
7742 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7743 if (Cand->Conversions.size() == 1) {
7744 TypeStr += ")";
7745 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7746 } else {
7747 TypeStr += ", ";
7748 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7749 TypeStr += ")";
7750 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7751 }
7752}
7753
7754void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7755 OverloadCandidate *Cand) {
7756 unsigned NoOperands = Cand->Conversions.size();
7757 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7758 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007759 if (ICS.isBad()) break; // all meaningless after first invalid
7760 if (!ICS.isAmbiguous()) continue;
7761
John McCall5c32be02010-08-24 20:38:10 +00007762 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007763 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007764 }
7765}
7766
John McCall3712d9e2010-01-15 23:32:50 +00007767SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7768 if (Cand->Function)
7769 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007770 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007771 return Cand->Surrogate->getLocation();
7772 return SourceLocation();
7773}
7774
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007775static unsigned
7776RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007777 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007778 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007779 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007780
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007781 case Sema::TDK_Incomplete:
7782 return 1;
7783
7784 case Sema::TDK_Underqualified:
7785 case Sema::TDK_Inconsistent:
7786 return 2;
7787
7788 case Sema::TDK_SubstitutionFailure:
7789 case Sema::TDK_NonDeducedMismatch:
7790 return 3;
7791
7792 case Sema::TDK_InstantiationDepth:
7793 case Sema::TDK_FailedOverloadResolution:
7794 return 4;
7795
7796 case Sema::TDK_InvalidExplicitArguments:
7797 return 5;
7798
7799 case Sema::TDK_TooManyArguments:
7800 case Sema::TDK_TooFewArguments:
7801 return 6;
7802 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007803 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007804}
7805
John McCallad2587a2010-01-12 00:48:53 +00007806struct CompareOverloadCandidatesForDisplay {
7807 Sema &S;
7808 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007809
7810 bool operator()(const OverloadCandidate *L,
7811 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007812 // Fast-path this check.
7813 if (L == R) return false;
7814
John McCall12f97bc2010-01-08 04:41:39 +00007815 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007816 if (L->Viable) {
7817 if (!R->Viable) return true;
7818
7819 // TODO: introduce a tri-valued comparison for overload
7820 // candidates. Would be more worthwhile if we had a sort
7821 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007822 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7823 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007824 } else if (R->Viable)
7825 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007826
John McCall3712d9e2010-01-15 23:32:50 +00007827 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007828
John McCall3712d9e2010-01-15 23:32:50 +00007829 // Criteria by which we can sort non-viable candidates:
7830 if (!L->Viable) {
7831 // 1. Arity mismatches come after other candidates.
7832 if (L->FailureKind == ovl_fail_too_many_arguments ||
7833 L->FailureKind == ovl_fail_too_few_arguments)
7834 return false;
7835 if (R->FailureKind == ovl_fail_too_many_arguments ||
7836 R->FailureKind == ovl_fail_too_few_arguments)
7837 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007838
John McCallfe796dd2010-01-23 05:17:32 +00007839 // 2. Bad conversions come first and are ordered by the number
7840 // of bad conversions and quality of good conversions.
7841 if (L->FailureKind == ovl_fail_bad_conversion) {
7842 if (R->FailureKind != ovl_fail_bad_conversion)
7843 return true;
7844
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007845 // The conversion that can be fixed with a smaller number of changes,
7846 // comes first.
7847 unsigned numLFixes = L->Fix.NumConversionsFixed;
7848 unsigned numRFixes = R->Fix.NumConversionsFixed;
7849 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7850 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007851 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007852 if (numLFixes < numRFixes)
7853 return true;
7854 else
7855 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007856 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007857
John McCallfe796dd2010-01-23 05:17:32 +00007858 // If there's any ordering between the defined conversions...
7859 // FIXME: this might not be transitive.
7860 assert(L->Conversions.size() == R->Conversions.size());
7861
7862 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007863 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7864 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007865 switch (CompareImplicitConversionSequences(S,
7866 L->Conversions[I],
7867 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007868 case ImplicitConversionSequence::Better:
7869 leftBetter++;
7870 break;
7871
7872 case ImplicitConversionSequence::Worse:
7873 leftBetter--;
7874 break;
7875
7876 case ImplicitConversionSequence::Indistinguishable:
7877 break;
7878 }
7879 }
7880 if (leftBetter > 0) return true;
7881 if (leftBetter < 0) return false;
7882
7883 } else if (R->FailureKind == ovl_fail_bad_conversion)
7884 return false;
7885
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007886 if (L->FailureKind == ovl_fail_bad_deduction) {
7887 if (R->FailureKind != ovl_fail_bad_deduction)
7888 return true;
7889
7890 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7891 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007892 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007893 } else if (R->FailureKind == ovl_fail_bad_deduction)
7894 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007895
John McCall3712d9e2010-01-15 23:32:50 +00007896 // TODO: others?
7897 }
7898
7899 // Sort everything else by location.
7900 SourceLocation LLoc = GetLocationForCandidate(L);
7901 SourceLocation RLoc = GetLocationForCandidate(R);
7902
7903 // Put candidates without locations (e.g. builtins) at the end.
7904 if (LLoc.isInvalid()) return false;
7905 if (RLoc.isInvalid()) return true;
7906
7907 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007908 }
7909};
7910
John McCallfe796dd2010-01-23 05:17:32 +00007911/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007912/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007913void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7914 Expr **Args, unsigned NumArgs) {
7915 assert(!Cand->Viable);
7916
7917 // Don't do anything on failures other than bad conversion.
7918 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7919
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007920 // We only want the FixIts if all the arguments can be corrected.
7921 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007922 // Use a implicit copy initialization to check conversion fixes.
7923 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007924
John McCallfe796dd2010-01-23 05:17:32 +00007925 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007926 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007927 unsigned ConvCount = Cand->Conversions.size();
7928 while (true) {
7929 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7930 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007931 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007932 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007933 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007934 }
John McCallfe796dd2010-01-23 05:17:32 +00007935 }
7936
7937 if (ConvIdx == ConvCount)
7938 return;
7939
John McCall65eb8792010-02-25 01:37:24 +00007940 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7941 "remaining conversion is initialized?");
7942
Douglas Gregoradc7a702010-04-16 17:45:54 +00007943 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007944 // operation somehow.
7945 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007946
7947 const FunctionProtoType* Proto;
7948 unsigned ArgIdx = ConvIdx;
7949
7950 if (Cand->IsSurrogate) {
7951 QualType ConvType
7952 = Cand->Surrogate->getConversionType().getNonReferenceType();
7953 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7954 ConvType = ConvPtrType->getPointeeType();
7955 Proto = ConvType->getAs<FunctionProtoType>();
7956 ArgIdx--;
7957 } else if (Cand->Function) {
7958 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7959 if (isa<CXXMethodDecl>(Cand->Function) &&
7960 !isa<CXXConstructorDecl>(Cand->Function))
7961 ArgIdx--;
7962 } else {
7963 // Builtin binary operator with a bad first conversion.
7964 assert(ConvCount <= 3);
7965 for (; ConvIdx != ConvCount; ++ConvIdx)
7966 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007967 = TryCopyInitialization(S, Args[ConvIdx],
7968 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007969 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007970 /*InOverloadResolution*/ true,
7971 /*AllowObjCWritebackConversion=*/
7972 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007973 return;
7974 }
7975
7976 // Fill in the rest of the conversions.
7977 unsigned NumArgsInProto = Proto->getNumArgs();
7978 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007979 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007980 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007981 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007982 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007983 /*InOverloadResolution=*/true,
7984 /*AllowObjCWritebackConversion=*/
7985 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007986 // Store the FixIt in the candidate if it exists.
7987 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007988 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007989 }
John McCallfe796dd2010-01-23 05:17:32 +00007990 else
7991 Cand->Conversions[ConvIdx].setEllipsis();
7992 }
7993}
7994
John McCalld3224162010-01-08 00:58:21 +00007995} // end anonymous namespace
7996
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007997/// PrintOverloadCandidates - When overload resolution fails, prints
7998/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007999/// set.
John McCall5c32be02010-08-24 20:38:10 +00008000void OverloadCandidateSet::NoteCandidates(Sema &S,
8001 OverloadCandidateDisplayKind OCD,
8002 Expr **Args, unsigned NumArgs,
8003 const char *Opc,
8004 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008005 // Sort the candidates by viability and position. Sorting directly would
8006 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008007 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008008 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8009 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008010 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008011 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008012 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008013 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008014 if (Cand->Function || Cand->IsSurrogate)
8015 Cands.push_back(Cand);
8016 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8017 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008018 }
8019 }
8020
John McCallad2587a2010-01-12 00:48:53 +00008021 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008022 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008023
John McCall0d1da222010-01-12 00:44:57 +00008024 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008025
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008026 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008027 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8028 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008029 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008030 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8031 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008032
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008033 // Set an arbitrary limit on the number of candidate functions we'll spam
8034 // the user with. FIXME: This limit should depend on details of the
8035 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008036 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008037 break;
8038 }
8039 ++CandsShown;
8040
John McCalld3224162010-01-08 00:58:21 +00008041 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008042 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008043 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008044 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008045 else {
8046 assert(Cand->Viable &&
8047 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008048 // Generally we only see ambiguities including viable builtin
8049 // operators if overload resolution got screwed up by an
8050 // ambiguous user-defined conversion.
8051 //
8052 // FIXME: It's quite possible for different conversions to see
8053 // different ambiguities, though.
8054 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008055 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008056 ReportedAmbiguousConversions = true;
8057 }
John McCalld3224162010-01-08 00:58:21 +00008058
John McCall0d1da222010-01-12 00:44:57 +00008059 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008060 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008061 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008062 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008063
8064 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008065 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008066}
8067
Douglas Gregorb491ed32011-02-19 21:32:49 +00008068// [PossiblyAFunctionType] --> [Return]
8069// NonFunctionType --> NonFunctionType
8070// R (A) --> R(A)
8071// R (*)(A) --> R (A)
8072// R (&)(A) --> R (A)
8073// R (S::*)(A) --> R (A)
8074QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8075 QualType Ret = PossiblyAFunctionType;
8076 if (const PointerType *ToTypePtr =
8077 PossiblyAFunctionType->getAs<PointerType>())
8078 Ret = ToTypePtr->getPointeeType();
8079 else if (const ReferenceType *ToTypeRef =
8080 PossiblyAFunctionType->getAs<ReferenceType>())
8081 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008082 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008083 PossiblyAFunctionType->getAs<MemberPointerType>())
8084 Ret = MemTypePtr->getPointeeType();
8085 Ret =
8086 Context.getCanonicalType(Ret).getUnqualifiedType();
8087 return Ret;
8088}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008089
Douglas Gregorb491ed32011-02-19 21:32:49 +00008090// A helper class to help with address of function resolution
8091// - allows us to avoid passing around all those ugly parameters
8092class AddressOfFunctionResolver
8093{
8094 Sema& S;
8095 Expr* SourceExpr;
8096 const QualType& TargetType;
8097 QualType TargetFunctionType; // Extracted function type from target type
8098
8099 bool Complain;
8100 //DeclAccessPair& ResultFunctionAccessPair;
8101 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008102
Douglas Gregorb491ed32011-02-19 21:32:49 +00008103 bool TargetTypeIsNonStaticMemberFunction;
8104 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008105
Douglas Gregorb491ed32011-02-19 21:32:49 +00008106 OverloadExpr::FindResult OvlExprInfo;
8107 OverloadExpr *OvlExpr;
8108 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008109 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008110
Douglas Gregorb491ed32011-02-19 21:32:49 +00008111public:
8112 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8113 const QualType& TargetType, bool Complain)
8114 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8115 Complain(Complain), Context(S.getASTContext()),
8116 TargetTypeIsNonStaticMemberFunction(
8117 !!TargetType->getAs<MemberPointerType>()),
8118 FoundNonTemplateFunction(false),
8119 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8120 OvlExpr(OvlExprInfo.Expression)
8121 {
8122 ExtractUnqualifiedFunctionTypeFromTargetType();
8123
8124 if (!TargetFunctionType->isFunctionType()) {
8125 if (OvlExpr->hasExplicitTemplateArgs()) {
8126 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008127 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008128 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008129
8130 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8131 if (!Method->isStatic()) {
8132 // If the target type is a non-function type and the function
8133 // found is a non-static member function, pretend as if that was
8134 // the target, it's the only possible type to end up with.
8135 TargetTypeIsNonStaticMemberFunction = true;
8136
8137 // And skip adding the function if its not in the proper form.
8138 // We'll diagnose this due to an empty set of functions.
8139 if (!OvlExprInfo.HasFormOfMemberPointer)
8140 return;
8141 }
8142 }
8143
Douglas Gregorb491ed32011-02-19 21:32:49 +00008144 Matches.push_back(std::make_pair(dap,Fn));
8145 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008146 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008147 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008148 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008149
8150 if (OvlExpr->hasExplicitTemplateArgs())
8151 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008152
Douglas Gregorb491ed32011-02-19 21:32:49 +00008153 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8154 // C++ [over.over]p4:
8155 // If more than one function is selected, [...]
8156 if (Matches.size() > 1) {
8157 if (FoundNonTemplateFunction)
8158 EliminateAllTemplateMatches();
8159 else
8160 EliminateAllExceptMostSpecializedTemplate();
8161 }
8162 }
8163 }
8164
8165private:
8166 bool isTargetTypeAFunction() const {
8167 return TargetFunctionType->isFunctionType();
8168 }
8169
8170 // [ToType] [Return]
8171
8172 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8173 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8174 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8175 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8176 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8177 }
8178
8179 // return true if any matching specializations were found
8180 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8181 const DeclAccessPair& CurAccessFunPair) {
8182 if (CXXMethodDecl *Method
8183 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8184 // Skip non-static function templates when converting to pointer, and
8185 // static when converting to member pointer.
8186 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8187 return false;
8188 }
8189 else if (TargetTypeIsNonStaticMemberFunction)
8190 return false;
8191
8192 // C++ [over.over]p2:
8193 // If the name is a function template, template argument deduction is
8194 // done (14.8.2.2), and if the argument deduction succeeds, the
8195 // resulting template argument list is used to generate a single
8196 // function template specialization, which is added to the set of
8197 // overloaded functions considered.
8198 FunctionDecl *Specialization = 0;
8199 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8200 if (Sema::TemplateDeductionResult Result
8201 = S.DeduceTemplateArguments(FunctionTemplate,
8202 &OvlExplicitTemplateArgs,
8203 TargetFunctionType, Specialization,
8204 Info)) {
8205 // FIXME: make a note of the failed deduction for diagnostics.
8206 (void)Result;
8207 return false;
8208 }
8209
8210 // Template argument deduction ensures that we have an exact match.
8211 // This function template specicalization works.
8212 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8213 assert(TargetFunctionType
8214 == Context.getCanonicalType(Specialization->getType()));
8215 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8216 return true;
8217 }
8218
8219 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8220 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008221 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008222 // Skip non-static functions when converting to pointer, and static
8223 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008224 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8225 return false;
8226 }
8227 else if (TargetTypeIsNonStaticMemberFunction)
8228 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008229
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008230 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008231 if (S.getLangOptions().CUDA)
8232 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8233 if (S.CheckCUDATarget(Caller, FunDecl))
8234 return false;
8235
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008236 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008237 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8238 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008239 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8240 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008241 Matches.push_back(std::make_pair(CurAccessFunPair,
8242 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008243 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008244 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008245 }
Mike Stump11289f42009-09-09 15:08:12 +00008246 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008247
8248 return false;
8249 }
8250
8251 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8252 bool Ret = false;
8253
8254 // If the overload expression doesn't have the form of a pointer to
8255 // member, don't try to convert it to a pointer-to-member type.
8256 if (IsInvalidFormOfPointerToMemberFunction())
8257 return false;
8258
8259 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8260 E = OvlExpr->decls_end();
8261 I != E; ++I) {
8262 // Look through any using declarations to find the underlying function.
8263 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8264
8265 // C++ [over.over]p3:
8266 // Non-member functions and static member functions match
8267 // targets of type "pointer-to-function" or "reference-to-function."
8268 // Nonstatic member functions match targets of
8269 // type "pointer-to-member-function."
8270 // Note that according to DR 247, the containing class does not matter.
8271 if (FunctionTemplateDecl *FunctionTemplate
8272 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8273 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8274 Ret = true;
8275 }
8276 // If we have explicit template arguments supplied, skip non-templates.
8277 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8278 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8279 Ret = true;
8280 }
8281 assert(Ret || Matches.empty());
8282 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008283 }
8284
Douglas Gregorb491ed32011-02-19 21:32:49 +00008285 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008286 // [...] and any given function template specialization F1 is
8287 // eliminated if the set contains a second function template
8288 // specialization whose function template is more specialized
8289 // than the function template of F1 according to the partial
8290 // ordering rules of 14.5.5.2.
8291
8292 // The algorithm specified above is quadratic. We instead use a
8293 // two-pass algorithm (similar to the one used to identify the
8294 // best viable function in an overload set) that identifies the
8295 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008296
8297 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8298 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8299 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008300
John McCall58cc69d2010-01-27 01:50:18 +00008301 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008302 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8303 TPOC_Other, 0, SourceExpr->getLocStart(),
8304 S.PDiag(),
8305 S.PDiag(diag::err_addr_ovl_ambiguous)
8306 << Matches[0].second->getDeclName(),
8307 S.PDiag(diag::note_ovl_candidate)
8308 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008309 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008310
Douglas Gregorb491ed32011-02-19 21:32:49 +00008311 if (Result != MatchesCopy.end()) {
8312 // Make it the first and only element
8313 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8314 Matches[0].second = cast<FunctionDecl>(*Result);
8315 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008316 }
8317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008318
Douglas Gregorb491ed32011-02-19 21:32:49 +00008319 void EliminateAllTemplateMatches() {
8320 // [...] any function template specializations in the set are
8321 // eliminated if the set also contains a non-template function, [...]
8322 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8323 if (Matches[I].second->getPrimaryTemplate() == 0)
8324 ++I;
8325 else {
8326 Matches[I] = Matches[--N];
8327 Matches.set_size(N);
8328 }
8329 }
8330 }
8331
8332public:
8333 void ComplainNoMatchesFound() const {
8334 assert(Matches.empty());
8335 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8336 << OvlExpr->getName() << TargetFunctionType
8337 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008338 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008339 }
8340
8341 bool IsInvalidFormOfPointerToMemberFunction() const {
8342 return TargetTypeIsNonStaticMemberFunction &&
8343 !OvlExprInfo.HasFormOfMemberPointer;
8344 }
8345
8346 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8347 // TODO: Should we condition this on whether any functions might
8348 // have matched, or is it more appropriate to do that in callers?
8349 // TODO: a fixit wouldn't hurt.
8350 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8351 << TargetType << OvlExpr->getSourceRange();
8352 }
8353
8354 void ComplainOfInvalidConversion() const {
8355 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8356 << OvlExpr->getName() << TargetType;
8357 }
8358
8359 void ComplainMultipleMatchesFound() const {
8360 assert(Matches.size() > 1);
8361 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8362 << OvlExpr->getName()
8363 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008364 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008365 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008366
8367 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8368
Douglas Gregorb491ed32011-02-19 21:32:49 +00008369 int getNumMatches() const { return Matches.size(); }
8370
8371 FunctionDecl* getMatchingFunctionDecl() const {
8372 if (Matches.size() != 1) return 0;
8373 return Matches[0].second;
8374 }
8375
8376 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8377 if (Matches.size() != 1) return 0;
8378 return &Matches[0].first;
8379 }
8380};
8381
8382/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8383/// an overloaded function (C++ [over.over]), where @p From is an
8384/// expression with overloaded function type and @p ToType is the type
8385/// we're trying to resolve to. For example:
8386///
8387/// @code
8388/// int f(double);
8389/// int f(int);
8390///
8391/// int (*pfd)(double) = f; // selects f(double)
8392/// @endcode
8393///
8394/// This routine returns the resulting FunctionDecl if it could be
8395/// resolved, and NULL otherwise. When @p Complain is true, this
8396/// routine will emit diagnostics if there is an error.
8397FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008398Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8399 QualType TargetType,
8400 bool Complain,
8401 DeclAccessPair &FoundResult,
8402 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008403 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008404
8405 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8406 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008407 int NumMatches = Resolver.getNumMatches();
8408 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008409 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008410 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8411 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8412 else
8413 Resolver.ComplainNoMatchesFound();
8414 }
8415 else if (NumMatches > 1 && Complain)
8416 Resolver.ComplainMultipleMatchesFound();
8417 else if (NumMatches == 1) {
8418 Fn = Resolver.getMatchingFunctionDecl();
8419 assert(Fn);
8420 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8421 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008422 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008423 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008424 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008425
8426 if (pHadMultipleCandidates)
8427 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008428 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008429}
8430
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008431/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008432/// resolve that overloaded function expression down to a single function.
8433///
8434/// This routine can only resolve template-ids that refer to a single function
8435/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008436/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008437/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008438FunctionDecl *
8439Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8440 bool Complain,
8441 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008442 // C++ [over.over]p1:
8443 // [...] [Note: any redundant set of parentheses surrounding the
8444 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008445 // C++ [over.over]p1:
8446 // [...] The overloaded function name can be preceded by the &
8447 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008448
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008449 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008450 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008451 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008452
8453 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008454 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008455
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008456 // Look through all of the overloaded functions, searching for one
8457 // whose type matches exactly.
8458 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008459 for (UnresolvedSetIterator I = ovl->decls_begin(),
8460 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008461 // C++0x [temp.arg.explicit]p3:
8462 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008463 // where deduction is not done, if a template argument list is
8464 // specified and it, along with any default template arguments,
8465 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008466 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008467 FunctionTemplateDecl *FunctionTemplate
8468 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008469
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008470 // C++ [over.over]p2:
8471 // If the name is a function template, template argument deduction is
8472 // done (14.8.2.2), and if the argument deduction succeeds, the
8473 // resulting template argument list is used to generate a single
8474 // function template specialization, which is added to the set of
8475 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008476 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008477 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008478 if (TemplateDeductionResult Result
8479 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8480 Specialization, Info)) {
8481 // FIXME: make a note of the failed deduction for diagnostics.
8482 (void)Result;
8483 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008484 }
8485
John McCall0009fcc2011-04-26 20:42:42 +00008486 assert(Specialization && "no specialization and no error?");
8487
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008488 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008489 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008490 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008491 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8492 << ovl->getName();
8493 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008494 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008495 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008496 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008497
John McCall0009fcc2011-04-26 20:42:42 +00008498 Matched = Specialization;
8499 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008500 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008501
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008502 return Matched;
8503}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008504
Douglas Gregor1beec452011-03-12 01:48:56 +00008505
8506
8507
John McCall50a2c2c2011-10-11 23:14:30 +00008508// Resolve and fix an overloaded expression that can be resolved
8509// because it identifies a single function template specialization.
8510//
Douglas Gregor1beec452011-03-12 01:48:56 +00008511// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008512//
8513// Return true if it was logically possible to so resolve the
8514// expression, regardless of whether or not it succeeded. Always
8515// returns true if 'complain' is set.
8516bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8517 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8518 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008519 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008520 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008521 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008522
John McCall50a2c2c2011-10-11 23:14:30 +00008523 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008524
John McCall0009fcc2011-04-26 20:42:42 +00008525 DeclAccessPair found;
8526 ExprResult SingleFunctionExpression;
8527 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8528 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008529 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8530 SrcExpr = ExprError();
8531 return true;
8532 }
John McCall0009fcc2011-04-26 20:42:42 +00008533
8534 // It is only correct to resolve to an instance method if we're
8535 // resolving a form that's permitted to be a pointer to member.
8536 // Otherwise we'll end up making a bound member expression, which
8537 // is illegal in all the contexts we resolve like this.
8538 if (!ovl.HasFormOfMemberPointer &&
8539 isa<CXXMethodDecl>(fn) &&
8540 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008541 if (!complain) return false;
8542
8543 Diag(ovl.Expression->getExprLoc(),
8544 diag::err_bound_member_function)
8545 << 0 << ovl.Expression->getSourceRange();
8546
8547 // TODO: I believe we only end up here if there's a mix of
8548 // static and non-static candidates (otherwise the expression
8549 // would have 'bound member' type, not 'overload' type).
8550 // Ideally we would note which candidate was chosen and why
8551 // the static candidates were rejected.
8552 SrcExpr = ExprError();
8553 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008554 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008555
John McCall0009fcc2011-04-26 20:42:42 +00008556 // Fix the expresion to refer to 'fn'.
8557 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008558 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008559
8560 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008561 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008562 SingleFunctionExpression =
8563 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008564 if (SingleFunctionExpression.isInvalid()) {
8565 SrcExpr = ExprError();
8566 return true;
8567 }
8568 }
John McCall0009fcc2011-04-26 20:42:42 +00008569 }
8570
8571 if (!SingleFunctionExpression.isUsable()) {
8572 if (complain) {
8573 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8574 << ovl.Expression->getName()
8575 << DestTypeForComplaining
8576 << OpRangeForComplaining
8577 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008578 NoteAllOverloadCandidates(SrcExpr.get());
8579
8580 SrcExpr = ExprError();
8581 return true;
8582 }
8583
8584 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008585 }
8586
John McCall50a2c2c2011-10-11 23:14:30 +00008587 SrcExpr = SingleFunctionExpression;
8588 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008589}
8590
Douglas Gregorcabea402009-09-22 15:41:20 +00008591/// \brief Add a single candidate to the overload set.
8592static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008593 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008594 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008595 Expr **Args, unsigned NumArgs,
8596 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008597 bool PartialOverloading,
8598 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008599 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008600 if (isa<UsingShadowDecl>(Callee))
8601 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8602
Douglas Gregorcabea402009-09-22 15:41:20 +00008603 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008604 if (ExplicitTemplateArgs) {
8605 assert(!KnownValid && "Explicit template arguments?");
8606 return;
8607 }
John McCalla0296f72010-03-19 07:35:19 +00008608 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008609 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008610 return;
John McCalld14a8642009-11-21 08:51:07 +00008611 }
8612
8613 if (FunctionTemplateDecl *FuncTemplate
8614 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008615 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8616 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008617 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008618 return;
8619 }
8620
Richard Smith95ce4f62011-06-26 22:19:54 +00008621 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008622}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008623
Douglas Gregorcabea402009-09-22 15:41:20 +00008624/// \brief Add the overload candidates named by callee and/or found by argument
8625/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008626void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008627 Expr **Args, unsigned NumArgs,
8628 OverloadCandidateSet &CandidateSet,
8629 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008630
8631#ifndef NDEBUG
8632 // Verify that ArgumentDependentLookup is consistent with the rules
8633 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008634 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008635 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8636 // and let Y be the lookup set produced by argument dependent
8637 // lookup (defined as follows). If X contains
8638 //
8639 // -- a declaration of a class member, or
8640 //
8641 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008642 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008643 //
8644 // -- a declaration that is neither a function or a function
8645 // template
8646 //
8647 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008648
John McCall57500772009-12-16 12:17:52 +00008649 if (ULE->requiresADL()) {
8650 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8651 E = ULE->decls_end(); I != E; ++I) {
8652 assert(!(*I)->getDeclContext()->isRecord());
8653 assert(isa<UsingShadowDecl>(*I) ||
8654 !(*I)->getDeclContext()->isFunctionOrMethod());
8655 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008656 }
8657 }
8658#endif
8659
John McCall57500772009-12-16 12:17:52 +00008660 // It would be nice to avoid this copy.
8661 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008662 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008663 if (ULE->hasExplicitTemplateArgs()) {
8664 ULE->copyTemplateArgumentsInto(TABuffer);
8665 ExplicitTemplateArgs = &TABuffer;
8666 }
8667
8668 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8669 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008670 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008671 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008672 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008673
John McCall57500772009-12-16 12:17:52 +00008674 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008675 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8676 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008677 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008678 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008679 PartialOverloading,
8680 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008681}
John McCalld681c392009-12-16 08:11:27 +00008682
Richard Smith998a5912011-06-05 22:42:48 +00008683/// Attempt to recover from an ill-formed use of a non-dependent name in a
8684/// template, where the non-dependent name was declared after the template
8685/// was defined. This is common in code written for a compilers which do not
8686/// correctly implement two-stage name lookup.
8687///
8688/// Returns true if a viable candidate was found and a diagnostic was issued.
8689static bool
8690DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8691 const CXXScopeSpec &SS, LookupResult &R,
8692 TemplateArgumentListInfo *ExplicitTemplateArgs,
8693 Expr **Args, unsigned NumArgs) {
8694 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8695 return false;
8696
8697 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8698 SemaRef.LookupQualifiedName(R, DC);
8699
8700 if (!R.empty()) {
8701 R.suppressDiagnostics();
8702
8703 if (isa<CXXRecordDecl>(DC)) {
8704 // Don't diagnose names we find in classes; we get much better
8705 // diagnostics for these from DiagnoseEmptyLookup.
8706 R.clear();
8707 return false;
8708 }
8709
8710 OverloadCandidateSet Candidates(FnLoc);
8711 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8712 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8713 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008714 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008715
8716 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008717 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008718 // No viable functions. Don't bother the user with notes for functions
8719 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008720 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008721 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008722 }
Richard Smith998a5912011-06-05 22:42:48 +00008723
8724 // Find the namespaces where ADL would have looked, and suggest
8725 // declaring the function there instead.
8726 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8727 Sema::AssociatedClassSet AssociatedClasses;
8728 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8729 AssociatedNamespaces,
8730 AssociatedClasses);
8731 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008732 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008733 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008734 for (Sema::AssociatedNamespaceSet::iterator
8735 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008736 end = AssociatedNamespaces.end(); it != end; ++it) {
8737 if (!Std->Encloses(*it))
8738 SuggestedNamespaces.insert(*it);
8739 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008740 } else {
8741 // Lacking the 'std::' namespace, use all of the associated namespaces.
8742 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008743 }
8744
8745 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8746 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008747 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008748 SemaRef.Diag(Best->Function->getLocation(),
8749 diag::note_not_found_by_two_phase_lookup)
8750 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008751 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008752 SemaRef.Diag(Best->Function->getLocation(),
8753 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008754 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008755 } else {
8756 // FIXME: It would be useful to list the associated namespaces here,
8757 // but the diagnostics infrastructure doesn't provide a way to produce
8758 // a localized representation of a list of items.
8759 SemaRef.Diag(Best->Function->getLocation(),
8760 diag::note_not_found_by_two_phase_lookup)
8761 << R.getLookupName() << 2;
8762 }
8763
8764 // Try to recover by calling this function.
8765 return true;
8766 }
8767
8768 R.clear();
8769 }
8770
8771 return false;
8772}
8773
8774/// Attempt to recover from ill-formed use of a non-dependent operator in a
8775/// template, where the non-dependent operator was declared after the template
8776/// was defined.
8777///
8778/// Returns true if a viable candidate was found and a diagnostic was issued.
8779static bool
8780DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8781 SourceLocation OpLoc,
8782 Expr **Args, unsigned NumArgs) {
8783 DeclarationName OpName =
8784 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8785 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8786 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8787 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8788}
8789
John McCalld681c392009-12-16 08:11:27 +00008790/// Attempts to recover from a call where no functions were found.
8791///
8792/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008793static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008794BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008795 UnresolvedLookupExpr *ULE,
8796 SourceLocation LParenLoc,
8797 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008798 SourceLocation RParenLoc,
8799 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008800
8801 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008802 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008803
John McCall57500772009-12-16 12:17:52 +00008804 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008805 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008806 if (ULE->hasExplicitTemplateArgs()) {
8807 ULE->copyTemplateArgumentsInto(TABuffer);
8808 ExplicitTemplateArgs = &TABuffer;
8809 }
8810
John McCalld681c392009-12-16 08:11:27 +00008811 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8812 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008813 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8814 ExplicitTemplateArgs, Args, NumArgs) &&
8815 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008816 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008817 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008818 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008819
John McCall57500772009-12-16 12:17:52 +00008820 assert(!R.empty() && "lookup results empty despite recovery");
8821
8822 // Build an implicit member call if appropriate. Just drop the
8823 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008824 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008825 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008826 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8827 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008828 else if (ExplicitTemplateArgs)
8829 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8830 else
8831 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8832
8833 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008834 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008835
8836 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008837 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008838 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008839 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008840 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008841}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008842
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008843/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008844/// (which eventually refers to the declaration Func) and the call
8845/// arguments Args/NumArgs, attempt to resolve the function call down
8846/// to a specific function. If overload resolution succeeds, returns
8847/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008848/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008849/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008850ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008851Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008852 SourceLocation LParenLoc,
8853 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008854 SourceLocation RParenLoc,
8855 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008856#ifndef NDEBUG
8857 if (ULE->requiresADL()) {
8858 // To do ADL, we must have found an unqualified name.
8859 assert(!ULE->getQualifier() && "qualified name with ADL");
8860
8861 // We don't perform ADL for implicit declarations of builtins.
8862 // Verify that this was correctly set up.
8863 FunctionDecl *F;
8864 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8865 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8866 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008867 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008868
John McCall57500772009-12-16 12:17:52 +00008869 // We don't perform ADL in C.
8870 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008871 } else
8872 assert(!ULE->isStdAssociatedNamespace() &&
8873 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008874#endif
8875
John McCall4124c492011-10-17 18:40:02 +00008876 UnbridgedCastsSet UnbridgedCasts;
8877 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8878 return ExprError();
8879
John McCallbc077cf2010-02-08 23:07:23 +00008880 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008881
John McCall57500772009-12-16 12:17:52 +00008882 // Add the functions denoted by the callee to the set of candidate
8883 // functions, including those from argument-dependent lookup.
8884 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008885
8886 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008887 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8888 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008889 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008890 // In Microsoft mode, if we are inside a template class member function then
8891 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008892 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008893 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00008894 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00008895 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008896 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8897 Context.DependentTy, VK_RValue,
8898 RParenLoc);
8899 CE->setTypeDependent(true);
8900 return Owned(CE);
8901 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008902 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008903 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008904 }
John McCalld681c392009-12-16 08:11:27 +00008905
John McCall4124c492011-10-17 18:40:02 +00008906 UnbridgedCasts.restore();
8907
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008908 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008909 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008910 case OR_Success: {
8911 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008912 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008913 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008914 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008915 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008916 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8917 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008918 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008919
Richard Smith998a5912011-06-05 22:42:48 +00008920 case OR_No_Viable_Function: {
8921 // Try to recover by looking for viable functions which the user might
8922 // have meant to call.
8923 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8924 Args, NumArgs, RParenLoc,
8925 /*EmptyLookup=*/false);
8926 if (!Recovery.isInvalid())
8927 return Recovery;
8928
Chris Lattner45d9d602009-02-17 07:29:20 +00008929 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008930 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008931 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008932 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008933 break;
Richard Smith998a5912011-06-05 22:42:48 +00008934 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008935
8936 case OR_Ambiguous:
8937 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008938 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008939 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008940 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008941
8942 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008943 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008944 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8945 << Best->Function->isDeleted()
8946 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008947 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008948 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008949 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00008950
8951 // We emitted an error for the unvailable/deleted function call but keep
8952 // the call in the AST.
8953 FunctionDecl *FDecl = Best->Function;
8954 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8955 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8956 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008957 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008958 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008959 }
8960
Douglas Gregorb412e172010-07-25 18:17:45 +00008961 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008962 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008963}
8964
John McCall4c4c1df2010-01-26 03:27:55 +00008965static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008966 return Functions.size() > 1 ||
8967 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8968}
8969
Douglas Gregor084d8552009-03-13 23:49:33 +00008970/// \brief Create a unary operation that may resolve to an overloaded
8971/// operator.
8972///
8973/// \param OpLoc The location of the operator itself (e.g., '*').
8974///
8975/// \param OpcIn The UnaryOperator::Opcode that describes this
8976/// operator.
8977///
8978/// \param Functions The set of non-member functions that will be
8979/// considered by overload resolution. The caller needs to build this
8980/// set based on the context using, e.g.,
8981/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8982/// set should not contain any member functions; those will be added
8983/// by CreateOverloadedUnaryOp().
8984///
8985/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008986ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008987Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8988 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008989 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008990 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008991
8992 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8993 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8994 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008995 // TODO: provide better source location info.
8996 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008997
John McCall4124c492011-10-17 18:40:02 +00008998 if (checkPlaceholderForOverload(*this, Input))
8999 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009000
Douglas Gregor084d8552009-03-13 23:49:33 +00009001 Expr *Args[2] = { Input, 0 };
9002 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009003
Douglas Gregor084d8552009-03-13 23:49:33 +00009004 // For post-increment and post-decrement, add the implicit '0' as
9005 // the second argument, so that we know this is a post-increment or
9006 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009007 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009008 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009009 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9010 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009011 NumArgs = 2;
9012 }
9013
9014 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009015 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009016 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009017 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009018 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009019 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009020 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009021
John McCall58cc69d2010-01-27 01:50:18 +00009022 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009023 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009024 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009025 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009026 /*ADL*/ true, IsOverloaded(Fns),
9027 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009028 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009029 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009030 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009031 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009032 OpLoc));
9033 }
9034
9035 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009036 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009037
9038 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009039 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009040
9041 // Add operator candidates that are member functions.
9042 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9043
John McCall4c4c1df2010-01-26 03:27:55 +00009044 // Add candidates from ADL.
9045 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009046 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009047 /*ExplicitTemplateArgs*/ 0,
9048 CandidateSet);
9049
Douglas Gregor084d8552009-03-13 23:49:33 +00009050 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009051 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009052
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009053 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9054
Douglas Gregor084d8552009-03-13 23:49:33 +00009055 // Perform overload resolution.
9056 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009057 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009058 case OR_Success: {
9059 // We found a built-in operator or an overloaded operator.
9060 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009061
Douglas Gregor084d8552009-03-13 23:49:33 +00009062 if (FnDecl) {
9063 // We matched an overloaded operator. Build a call to that
9064 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009065
Chandler Carruth30141632011-02-25 19:41:05 +00009066 MarkDeclarationReferenced(OpLoc, FnDecl);
9067
Douglas Gregor084d8552009-03-13 23:49:33 +00009068 // Convert the arguments.
9069 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009070 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009071
John Wiegley01296292011-04-08 18:41:53 +00009072 ExprResult InputRes =
9073 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9074 Best->FoundDecl, Method);
9075 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009076 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009077 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009078 } else {
9079 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009080 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009081 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009082 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009083 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009084 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009085 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009086 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009087 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009088 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009089 }
9090
John McCall4fa0d5f2010-05-06 18:15:07 +00009091 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9092
John McCall7decc9e2010-11-18 06:31:45 +00009093 // Determine the result type.
9094 QualType ResultTy = FnDecl->getResultType();
9095 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9096 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009097
Douglas Gregor084d8552009-03-13 23:49:33 +00009098 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009099 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9100 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009101 if (FnExpr.isInvalid())
9102 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009103
Eli Friedman030eee42009-11-18 03:58:17 +00009104 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009105 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009106 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009107 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009108
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009109 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009110 FnDecl))
9111 return ExprError();
9112
John McCallb268a282010-08-23 23:25:46 +00009113 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009114 } else {
9115 // We matched a built-in operator. Convert the arguments, then
9116 // break out so that we will build the appropriate built-in
9117 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009118 ExprResult InputRes =
9119 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9120 Best->Conversions[0], AA_Passing);
9121 if (InputRes.isInvalid())
9122 return ExprError();
9123 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009124 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009125 }
John Wiegley01296292011-04-08 18:41:53 +00009126 }
9127
9128 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009129 // This is an erroneous use of an operator which can be overloaded by
9130 // a non-member function. Check for non-member operators which were
9131 // defined too late to be candidates.
9132 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9133 // FIXME: Recover by calling the found function.
9134 return ExprError();
9135
John Wiegley01296292011-04-08 18:41:53 +00009136 // No viable function; fall through to handling this as a
9137 // built-in operator, which will produce an error message for us.
9138 break;
9139
9140 case OR_Ambiguous:
9141 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9142 << UnaryOperator::getOpcodeStr(Opc)
9143 << Input->getType()
9144 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009145 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009146 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9147 return ExprError();
9148
9149 case OR_Deleted:
9150 Diag(OpLoc, diag::err_ovl_deleted_oper)
9151 << Best->Function->isDeleted()
9152 << UnaryOperator::getOpcodeStr(Opc)
9153 << getDeletedOrUnavailableSuffix(Best->Function)
9154 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009155 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9156 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009157 return ExprError();
9158 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009159
9160 // Either we found no viable overloaded operator or we matched a
9161 // built-in operator. In either case, fall through to trying to
9162 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009163 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009164}
9165
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009166/// \brief Create a binary operation that may resolve to an overloaded
9167/// operator.
9168///
9169/// \param OpLoc The location of the operator itself (e.g., '+').
9170///
9171/// \param OpcIn The BinaryOperator::Opcode that describes this
9172/// operator.
9173///
9174/// \param Functions The set of non-member functions that will be
9175/// considered by overload resolution. The caller needs to build this
9176/// set based on the context using, e.g.,
9177/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9178/// set should not contain any member functions; those will be added
9179/// by CreateOverloadedBinOp().
9180///
9181/// \param LHS Left-hand argument.
9182/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009183ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009184Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009185 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009186 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009187 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009188 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009189 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009190
9191 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9192 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9193 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9194
9195 // If either side is type-dependent, create an appropriate dependent
9196 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009197 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009198 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009199 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009200 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009201 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009202 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009203 Context.DependentTy,
9204 VK_RValue, OK_Ordinary,
9205 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009206
Douglas Gregor5287f092009-11-05 00:51:44 +00009207 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9208 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009209 VK_LValue,
9210 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009211 Context.DependentTy,
9212 Context.DependentTy,
9213 OpLoc));
9214 }
John McCall4c4c1df2010-01-26 03:27:55 +00009215
9216 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009217 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009218 // TODO: provide better source location info in DNLoc component.
9219 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009220 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009221 = UnresolvedLookupExpr::Create(Context, NamingClass,
9222 NestedNameSpecifierLoc(), OpNameInfo,
9223 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009224 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009225 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009226 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009227 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009228 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009229 OpLoc));
9230 }
9231
John McCall4124c492011-10-17 18:40:02 +00009232 // Always do placeholder-like conversions on the RHS.
9233 if (checkPlaceholderForOverload(*this, Args[1]))
9234 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009235
John McCall526ab472011-10-25 17:37:35 +00009236 // Do placeholder-like conversion on the LHS; note that we should
9237 // not get here with a PseudoObject LHS.
9238 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009239 if (checkPlaceholderForOverload(*this, Args[0]))
9240 return ExprError();
9241
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009242 // If this is the assignment operator, we only perform overload resolution
9243 // if the left-hand side is a class or enumeration type. This is actually
9244 // a hack. The standard requires that we do overload resolution between the
9245 // various built-in candidates, but as DR507 points out, this can lead to
9246 // problems. So we do it this way, which pretty much follows what GCC does.
9247 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009248 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009249 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009250
John McCalle26a8722010-12-04 08:14:53 +00009251 // If this is the .* operator, which is not overloadable, just
9252 // create a built-in binary operator.
9253 if (Opc == BO_PtrMemD)
9254 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9255
Douglas Gregor084d8552009-03-13 23:49:33 +00009256 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009257 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009258
9259 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009260 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009261
9262 // Add operator candidates that are member functions.
9263 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9264
John McCall4c4c1df2010-01-26 03:27:55 +00009265 // Add candidates from ADL.
9266 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9267 Args, 2,
9268 /*ExplicitTemplateArgs*/ 0,
9269 CandidateSet);
9270
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009271 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009272 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009273
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009274 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9275
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009276 // Perform overload resolution.
9277 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009278 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009279 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009280 // We found a built-in operator or an overloaded operator.
9281 FunctionDecl *FnDecl = Best->Function;
9282
9283 if (FnDecl) {
9284 // We matched an overloaded operator. Build a call to that
9285 // operator.
9286
Chandler Carruth30141632011-02-25 19:41:05 +00009287 MarkDeclarationReferenced(OpLoc, FnDecl);
9288
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009289 // Convert the arguments.
9290 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009291 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009292 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009293
Chandler Carruth8e543b32010-12-12 08:17:55 +00009294 ExprResult Arg1 =
9295 PerformCopyInitialization(
9296 InitializedEntity::InitializeParameter(Context,
9297 FnDecl->getParamDecl(0)),
9298 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009299 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009300 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009301
John Wiegley01296292011-04-08 18:41:53 +00009302 ExprResult Arg0 =
9303 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9304 Best->FoundDecl, Method);
9305 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009306 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009307 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009308 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009309 } else {
9310 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009311 ExprResult Arg0 = PerformCopyInitialization(
9312 InitializedEntity::InitializeParameter(Context,
9313 FnDecl->getParamDecl(0)),
9314 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009315 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009316 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009317
Chandler Carruth8e543b32010-12-12 08:17:55 +00009318 ExprResult Arg1 =
9319 PerformCopyInitialization(
9320 InitializedEntity::InitializeParameter(Context,
9321 FnDecl->getParamDecl(1)),
9322 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009323 if (Arg1.isInvalid())
9324 return ExprError();
9325 Args[0] = LHS = Arg0.takeAs<Expr>();
9326 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009327 }
9328
John McCall4fa0d5f2010-05-06 18:15:07 +00009329 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9330
John McCall7decc9e2010-11-18 06:31:45 +00009331 // Determine the result type.
9332 QualType ResultTy = FnDecl->getResultType();
9333 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9334 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009335
9336 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009337 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9338 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009339 if (FnExpr.isInvalid())
9340 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009341
John McCallb268a282010-08-23 23:25:46 +00009342 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009343 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009344 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009345
9346 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009347 FnDecl))
9348 return ExprError();
9349
John McCallb268a282010-08-23 23:25:46 +00009350 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009351 } else {
9352 // We matched a built-in operator. Convert the arguments, then
9353 // break out so that we will build the appropriate built-in
9354 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009355 ExprResult ArgsRes0 =
9356 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9357 Best->Conversions[0], AA_Passing);
9358 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009359 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009360 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009361
John Wiegley01296292011-04-08 18:41:53 +00009362 ExprResult ArgsRes1 =
9363 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9364 Best->Conversions[1], AA_Passing);
9365 if (ArgsRes1.isInvalid())
9366 return ExprError();
9367 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009368 break;
9369 }
9370 }
9371
Douglas Gregor66950a32009-09-30 21:46:01 +00009372 case OR_No_Viable_Function: {
9373 // C++ [over.match.oper]p9:
9374 // If the operator is the operator , [...] and there are no
9375 // viable functions, then the operator is assumed to be the
9376 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009377 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009378 break;
9379
Chandler Carruth8e543b32010-12-12 08:17:55 +00009380 // For class as left operand for assignment or compound assigment
9381 // operator do not fall through to handling in built-in, but report that
9382 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009383 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009384 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009385 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009386 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9387 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009388 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009389 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009390 // This is an erroneous use of an operator which can be overloaded by
9391 // a non-member function. Check for non-member operators which were
9392 // defined too late to be candidates.
9393 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9394 // FIXME: Recover by calling the found function.
9395 return ExprError();
9396
Douglas Gregor66950a32009-09-30 21:46:01 +00009397 // No viable function; try to create a built-in operation, which will
9398 // produce an error. Then, show the non-viable candidates.
9399 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009401 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009402 "C++ binary operator overloading is missing candidates!");
9403 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009404 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9405 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009406 return move(Result);
9407 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009408
9409 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009410 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009411 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009412 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009413 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009414 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9415 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009416 return ExprError();
9417
9418 case OR_Deleted:
9419 Diag(OpLoc, diag::err_ovl_deleted_oper)
9420 << Best->Function->isDeleted()
9421 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009422 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009423 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009424 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9425 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009426 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009427 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009428
Douglas Gregor66950a32009-09-30 21:46:01 +00009429 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009430 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009431}
9432
John McCalldadc5752010-08-24 06:29:42 +00009433ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009434Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9435 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009436 Expr *Base, Expr *Idx) {
9437 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009438 DeclarationName OpName =
9439 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9440
9441 // If either side is type-dependent, create an appropriate dependent
9442 // expression.
9443 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9444
John McCall58cc69d2010-01-27 01:50:18 +00009445 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009446 // CHECKME: no 'operator' keyword?
9447 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9448 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009449 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009450 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009451 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009452 /*ADL*/ true, /*Overloaded*/ false,
9453 UnresolvedSetIterator(),
9454 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009455 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009456
Sebastian Redladba46e2009-10-29 20:17:01 +00009457 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9458 Args, 2,
9459 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009460 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009461 RLoc));
9462 }
9463
John McCall4124c492011-10-17 18:40:02 +00009464 // Handle placeholders on both operands.
9465 if (checkPlaceholderForOverload(*this, Args[0]))
9466 return ExprError();
9467 if (checkPlaceholderForOverload(*this, Args[1]))
9468 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009469
Sebastian Redladba46e2009-10-29 20:17:01 +00009470 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009471 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009472
9473 // Subscript can only be overloaded as a member function.
9474
9475 // Add operator candidates that are member functions.
9476 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9477
9478 // Add builtin operator candidates.
9479 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9480
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009481 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9482
Sebastian Redladba46e2009-10-29 20:17:01 +00009483 // Perform overload resolution.
9484 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009485 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009486 case OR_Success: {
9487 // We found a built-in operator or an overloaded operator.
9488 FunctionDecl *FnDecl = Best->Function;
9489
9490 if (FnDecl) {
9491 // We matched an overloaded operator. Build a call to that
9492 // operator.
9493
Chandler Carruth30141632011-02-25 19:41:05 +00009494 MarkDeclarationReferenced(LLoc, FnDecl);
9495
John McCalla0296f72010-03-19 07:35:19 +00009496 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009497 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009498
Sebastian Redladba46e2009-10-29 20:17:01 +00009499 // Convert the arguments.
9500 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009501 ExprResult Arg0 =
9502 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9503 Best->FoundDecl, Method);
9504 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009505 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009506 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009507
Anders Carlssona68e51e2010-01-29 18:37:50 +00009508 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009509 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009510 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009511 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009512 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009513 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009514 Owned(Args[1]));
9515 if (InputInit.isInvalid())
9516 return ExprError();
9517
9518 Args[1] = InputInit.takeAs<Expr>();
9519
Sebastian Redladba46e2009-10-29 20:17:01 +00009520 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009521 QualType ResultTy = FnDecl->getResultType();
9522 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9523 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009524
9525 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009526 DeclarationNameLoc LocInfo;
9527 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9528 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009529 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9530 HadMultipleCandidates,
9531 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009532 if (FnExpr.isInvalid())
9533 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009534
John McCallb268a282010-08-23 23:25:46 +00009535 CXXOperatorCallExpr *TheCall =
9536 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009537 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009538 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009539
John McCallb268a282010-08-23 23:25:46 +00009540 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009541 FnDecl))
9542 return ExprError();
9543
John McCallb268a282010-08-23 23:25:46 +00009544 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009545 } else {
9546 // We matched a built-in operator. Convert the arguments, then
9547 // break out so that we will build the appropriate built-in
9548 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009549 ExprResult ArgsRes0 =
9550 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9551 Best->Conversions[0], AA_Passing);
9552 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009553 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009554 Args[0] = ArgsRes0.take();
9555
9556 ExprResult ArgsRes1 =
9557 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9558 Best->Conversions[1], AA_Passing);
9559 if (ArgsRes1.isInvalid())
9560 return ExprError();
9561 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009562
9563 break;
9564 }
9565 }
9566
9567 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009568 if (CandidateSet.empty())
9569 Diag(LLoc, diag::err_ovl_no_oper)
9570 << Args[0]->getType() << /*subscript*/ 0
9571 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9572 else
9573 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9574 << Args[0]->getType()
9575 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009576 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9577 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009578 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009579 }
9580
9581 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009582 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009583 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009584 << Args[0]->getType() << Args[1]->getType()
9585 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009586 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9587 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009588 return ExprError();
9589
9590 case OR_Deleted:
9591 Diag(LLoc, diag::err_ovl_deleted_oper)
9592 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009593 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009594 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009595 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9596 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009597 return ExprError();
9598 }
9599
9600 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009601 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009602}
9603
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009604/// BuildCallToMemberFunction - Build a call to a member
9605/// function. MemExpr is the expression that refers to the member
9606/// function (and includes the object parameter), Args/NumArgs are the
9607/// arguments to the function call (not including the object
9608/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009609/// expression refers to a non-static member function or an overloaded
9610/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009611ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009612Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9613 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009614 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009615 assert(MemExprE->getType() == Context.BoundMemberTy ||
9616 MemExprE->getType() == Context.OverloadTy);
9617
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009618 // Dig out the member expression. This holds both the object
9619 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009620 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009621
John McCall0009fcc2011-04-26 20:42:42 +00009622 // Determine whether this is a call to a pointer-to-member function.
9623 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9624 assert(op->getType() == Context.BoundMemberTy);
9625 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9626
9627 QualType fnType =
9628 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9629
9630 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9631 QualType resultType = proto->getCallResultType(Context);
9632 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9633
9634 // Check that the object type isn't more qualified than the
9635 // member function we're calling.
9636 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9637
9638 QualType objectType = op->getLHS()->getType();
9639 if (op->getOpcode() == BO_PtrMemI)
9640 objectType = objectType->castAs<PointerType>()->getPointeeType();
9641 Qualifiers objectQuals = objectType.getQualifiers();
9642
9643 Qualifiers difference = objectQuals - funcQuals;
9644 difference.removeObjCGCAttr();
9645 difference.removeAddressSpace();
9646 if (difference) {
9647 std::string qualsString = difference.getAsString();
9648 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9649 << fnType.getUnqualifiedType()
9650 << qualsString
9651 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9652 }
9653
9654 CXXMemberCallExpr *call
9655 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9656 resultType, valueKind, RParenLoc);
9657
9658 if (CheckCallReturnType(proto->getResultType(),
9659 op->getRHS()->getSourceRange().getBegin(),
9660 call, 0))
9661 return ExprError();
9662
9663 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9664 return ExprError();
9665
9666 return MaybeBindToTemporary(call);
9667 }
9668
John McCall4124c492011-10-17 18:40:02 +00009669 UnbridgedCastsSet UnbridgedCasts;
9670 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9671 return ExprError();
9672
John McCall10eae182009-11-30 22:42:35 +00009673 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009674 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009675 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009676 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009677 if (isa<MemberExpr>(NakedMemExpr)) {
9678 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009679 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009680 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009681 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009682 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009683 } else {
9684 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009685 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009686
John McCall6e9f8f62009-12-03 04:06:58 +00009687 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009688 Expr::Classification ObjectClassification
9689 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9690 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009691
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009692 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009693 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009694
John McCall2d74de92009-12-01 22:10:20 +00009695 // FIXME: avoid copy.
9696 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9697 if (UnresExpr->hasExplicitTemplateArgs()) {
9698 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9699 TemplateArgs = &TemplateArgsBuffer;
9700 }
9701
John McCall10eae182009-11-30 22:42:35 +00009702 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9703 E = UnresExpr->decls_end(); I != E; ++I) {
9704
John McCall6e9f8f62009-12-03 04:06:58 +00009705 NamedDecl *Func = *I;
9706 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9707 if (isa<UsingShadowDecl>(Func))
9708 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9709
Douglas Gregor02824322011-01-26 19:30:28 +00009710
Francois Pichet64225792011-01-18 05:04:39 +00009711 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009712 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009713 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9714 CandidateSet);
9715 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009716 // If explicit template arguments were provided, we can't call a
9717 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009718 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009719 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009720
John McCalla0296f72010-03-19 07:35:19 +00009721 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009722 ObjectClassification,
9723 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009724 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009725 } else {
John McCall10eae182009-11-30 22:42:35 +00009726 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009727 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009728 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009729 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009730 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009731 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009732 }
Mike Stump11289f42009-09-09 15:08:12 +00009733
John McCall10eae182009-11-30 22:42:35 +00009734 DeclarationName DeclName = UnresExpr->getMemberName();
9735
John McCall4124c492011-10-17 18:40:02 +00009736 UnbridgedCasts.restore();
9737
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009738 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009739 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009740 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009741 case OR_Success:
9742 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009743 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009744 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009745 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009746 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009747 break;
9748
9749 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009750 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009751 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009752 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009753 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009754 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009755 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009756
9757 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009758 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009759 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009760 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009761 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009762 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009763
9764 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009765 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009766 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009767 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009768 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009769 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009770 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009771 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009772 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009773 }
9774
John McCall16df1e52010-03-30 21:47:33 +00009775 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009776
John McCall2d74de92009-12-01 22:10:20 +00009777 // If overload resolution picked a static member, build a
9778 // non-member call based on that function.
9779 if (Method->isStatic()) {
9780 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9781 Args, NumArgs, RParenLoc);
9782 }
9783
John McCall10eae182009-11-30 22:42:35 +00009784 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009785 }
9786
John McCall7decc9e2010-11-18 06:31:45 +00009787 QualType ResultType = Method->getResultType();
9788 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9789 ResultType = ResultType.getNonLValueExprType(Context);
9790
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009791 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009792 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009793 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009794 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009795
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009796 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009797 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009798 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009799 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009800
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009801 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009802 // We only need to do this if there was actually an overload; otherwise
9803 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009804 if (!Method->isStatic()) {
9805 ExprResult ObjectArg =
9806 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9807 FoundDecl, Method);
9808 if (ObjectArg.isInvalid())
9809 return ExprError();
9810 MemExpr->setBase(ObjectArg.take());
9811 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009812
9813 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009814 const FunctionProtoType *Proto =
9815 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009816 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009817 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009818 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009819
John McCallb268a282010-08-23 23:25:46 +00009820 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009821 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009822
Anders Carlsson47061ee2011-05-06 14:25:31 +00009823 if ((isa<CXXConstructorDecl>(CurContext) ||
9824 isa<CXXDestructorDecl>(CurContext)) &&
9825 TheCall->getMethodDecl()->isPure()) {
9826 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9827
Chandler Carruth59259262011-06-27 08:31:58 +00009828 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009829 Diag(MemExpr->getLocStart(),
9830 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9831 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9832 << MD->getParent()->getDeclName();
9833
9834 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009835 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009836 }
John McCallb268a282010-08-23 23:25:46 +00009837 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009838}
9839
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009840/// BuildCallToObjectOfClassType - Build a call to an object of class
9841/// type (C++ [over.call.object]), which can end up invoking an
9842/// overloaded function call operator (@c operator()) or performing a
9843/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009844ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009845Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009846 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009847 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009848 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009849 if (checkPlaceholderForOverload(*this, Obj))
9850 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009851 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009852
9853 UnbridgedCastsSet UnbridgedCasts;
9854 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9855 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009856
John Wiegley01296292011-04-08 18:41:53 +00009857 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9858 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009859
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009860 // C++ [over.call.object]p1:
9861 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009862 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009863 // candidate functions includes at least the function call
9864 // operators of T. The function call operators of T are obtained by
9865 // ordinary lookup of the name operator() in the context of
9866 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009867 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009868 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009869
John Wiegley01296292011-04-08 18:41:53 +00009870 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009871 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009872 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009873 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009874
John McCall27b18f82009-11-17 02:14:36 +00009875 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9876 LookupQualifiedName(R, Record->getDecl());
9877 R.suppressDiagnostics();
9878
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009879 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009880 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009881 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9882 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009883 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009885
Douglas Gregorab7897a2008-11-19 22:57:39 +00009886 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009887 // In addition, for each (non-explicit in C++0x) conversion function
9888 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009889 //
9890 // operator conversion-type-id () cv-qualifier;
9891 //
9892 // where cv-qualifier is the same cv-qualification as, or a
9893 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009894 // denotes the type "pointer to function of (P1,...,Pn) returning
9895 // R", or the type "reference to pointer to function of
9896 // (P1,...,Pn) returning R", or the type "reference to function
9897 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009898 // is also considered as a candidate function. Similarly,
9899 // surrogate call functions are added to the set of candidate
9900 // functions for each conversion function declared in an
9901 // accessible base class provided the function is not hidden
9902 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009903 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009904 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009905 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009906 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009907 NamedDecl *D = *I;
9908 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9909 if (isa<UsingShadowDecl>(D))
9910 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009911
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009912 // Skip over templated conversion functions; they aren't
9913 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009914 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009915 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009916
John McCall6e9f8f62009-12-03 04:06:58 +00009917 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009918 if (!Conv->isExplicit()) {
9919 // Strip the reference type (if any) and then the pointer type (if
9920 // any) to get down to what might be a function type.
9921 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9922 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9923 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009924
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009925 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9926 {
9927 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9928 Object.get(), Args, NumArgs, CandidateSet);
9929 }
9930 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009931 }
Mike Stump11289f42009-09-09 15:08:12 +00009932
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009933 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9934
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009935 // Perform overload resolution.
9936 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009937 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009938 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009939 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009940 // Overload resolution succeeded; we'll build the appropriate call
9941 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009942 break;
9943
9944 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009945 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009946 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9947 << Object.get()->getType() << /*call*/ 1
9948 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009949 else
John Wiegley01296292011-04-08 18:41:53 +00009950 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009951 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009952 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009953 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009954 break;
9955
9956 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009957 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009958 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009959 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009960 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009961 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009962
9963 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009964 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009965 diag::err_ovl_deleted_object_call)
9966 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009967 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009968 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009969 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009970 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009971 break;
Mike Stump11289f42009-09-09 15:08:12 +00009972 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009973
Douglas Gregorb412e172010-07-25 18:17:45 +00009974 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009975 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009976
John McCall4124c492011-10-17 18:40:02 +00009977 UnbridgedCasts.restore();
9978
Douglas Gregorab7897a2008-11-19 22:57:39 +00009979 if (Best->Function == 0) {
9980 // Since there is no function declaration, this is one of the
9981 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009982 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009983 = cast<CXXConversionDecl>(
9984 Best->Conversions[0].UserDefined.ConversionFunction);
9985
John Wiegley01296292011-04-08 18:41:53 +00009986 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009987 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009988
Douglas Gregorab7897a2008-11-19 22:57:39 +00009989 // We selected one of the surrogate functions that converts the
9990 // object parameter to a function pointer. Perform the conversion
9991 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009992
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009993 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009994 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009995 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9996 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00009997 if (Call.isInvalid())
9998 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00009999 // Record usage of conversion in an implicit cast.
10000 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10001 CK_UserDefinedConversion,
10002 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010003
Douglas Gregor668443e2011-01-20 00:18:04 +000010004 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010005 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010006 }
10007
Chandler Carruth30141632011-02-25 19:41:05 +000010008 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010009 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010010 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010011
Douglas Gregorab7897a2008-11-19 22:57:39 +000010012 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10013 // that calls this method, using Object for the implicit object
10014 // parameter and passing along the remaining arguments.
10015 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010016 const FunctionProtoType *Proto =
10017 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010018
10019 unsigned NumArgsInProto = Proto->getNumArgs();
10020 unsigned NumArgsToCheck = NumArgs;
10021
10022 // Build the full argument list for the method call (the
10023 // implicit object parameter is placed at the beginning of the
10024 // list).
10025 Expr **MethodArgs;
10026 if (NumArgs < NumArgsInProto) {
10027 NumArgsToCheck = NumArgsInProto;
10028 MethodArgs = new Expr*[NumArgsInProto + 1];
10029 } else {
10030 MethodArgs = new Expr*[NumArgs + 1];
10031 }
John Wiegley01296292011-04-08 18:41:53 +000010032 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010033 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10034 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010035
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010036 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10037 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010038 if (NewFn.isInvalid())
10039 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010040
10041 // Once we've built TheCall, all of the expressions are properly
10042 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010043 QualType ResultTy = Method->getResultType();
10044 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10045 ResultTy = ResultTy.getNonLValueExprType(Context);
10046
John McCallb268a282010-08-23 23:25:46 +000010047 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010048 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010049 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010050 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010051 delete [] MethodArgs;
10052
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010053 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010054 Method))
10055 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010056
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010057 // We may have default arguments. If so, we need to allocate more
10058 // slots in the call for them.
10059 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010060 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010061 else if (NumArgs > NumArgsInProto)
10062 NumArgsToCheck = NumArgsInProto;
10063
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010064 bool IsError = false;
10065
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010066 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010067 ExprResult ObjRes =
10068 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10069 Best->FoundDecl, Method);
10070 if (ObjRes.isInvalid())
10071 IsError = true;
10072 else
10073 Object = move(ObjRes);
10074 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010075
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010076 // Check the argument types.
10077 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010078 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010079 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010080 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010081
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010082 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010083
John McCalldadc5752010-08-24 06:29:42 +000010084 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010085 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010086 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010087 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010088 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010089
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010090 IsError |= InputInit.isInvalid();
10091 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010092 } else {
John McCalldadc5752010-08-24 06:29:42 +000010093 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010094 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10095 if (DefArg.isInvalid()) {
10096 IsError = true;
10097 break;
10098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010099
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010100 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010101 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010102
10103 TheCall->setArg(i + 1, Arg);
10104 }
10105
10106 // If this is a variadic call, handle args passed through "...".
10107 if (Proto->isVariadic()) {
10108 // Promote the arguments (C99 6.5.2.2p7).
10109 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010110 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10111 IsError |= Arg.isInvalid();
10112 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010113 }
10114 }
10115
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010116 if (IsError) return true;
10117
John McCallb268a282010-08-23 23:25:46 +000010118 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010119 return true;
10120
John McCalle172be52010-08-24 06:09:16 +000010121 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010122}
10123
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010124/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010125/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010126/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010127ExprResult
John McCallb268a282010-08-23 23:25:46 +000010128Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010129 assert(Base->getType()->isRecordType() &&
10130 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010131
John McCall4124c492011-10-17 18:40:02 +000010132 if (checkPlaceholderForOverload(*this, Base))
10133 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010134
John McCallbc077cf2010-02-08 23:07:23 +000010135 SourceLocation Loc = Base->getExprLoc();
10136
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010137 // C++ [over.ref]p1:
10138 //
10139 // [...] An expression x->m is interpreted as (x.operator->())->m
10140 // for a class object x of type T if T::operator->() exists and if
10141 // the operator is selected as the best match function by the
10142 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010143 DeclarationName OpName =
10144 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010145 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010146 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010147
John McCallbc077cf2010-02-08 23:07:23 +000010148 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010149 PDiag(diag::err_typecheck_incomplete_tag)
10150 << Base->getSourceRange()))
10151 return ExprError();
10152
John McCall27b18f82009-11-17 02:14:36 +000010153 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10154 LookupQualifiedName(R, BaseRecord->getDecl());
10155 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010156
10157 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010158 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010159 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10160 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010161 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010162
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010163 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10164
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010165 // Perform overload resolution.
10166 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010167 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010168 case OR_Success:
10169 // Overload resolution succeeded; we'll build the call below.
10170 break;
10171
10172 case OR_No_Viable_Function:
10173 if (CandidateSet.empty())
10174 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010175 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010176 else
10177 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010178 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010179 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010180 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010181
10182 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010183 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10184 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010185 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010186 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010187
10188 case OR_Deleted:
10189 Diag(OpLoc, diag::err_ovl_deleted_oper)
10190 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010191 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010192 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010193 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010194 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010195 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010196 }
10197
Chandler Carruth30141632011-02-25 19:41:05 +000010198 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010199 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010200 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010201
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010202 // Convert the object parameter.
10203 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010204 ExprResult BaseResult =
10205 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10206 Best->FoundDecl, Method);
10207 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010208 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010209 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010210
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010211 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010212 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10213 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010214 if (FnExpr.isInvalid())
10215 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010216
John McCall7decc9e2010-11-18 06:31:45 +000010217 QualType ResultTy = Method->getResultType();
10218 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10219 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010220 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010221 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010222 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010223
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010224 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010225 Method))
10226 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010227
10228 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010229}
10230
Douglas Gregorcd695e52008-11-10 20:40:00 +000010231/// FixOverloadedFunctionReference - E is an expression that refers to
10232/// a C++ overloaded function (possibly with some parentheses and
10233/// perhaps a '&' around it). We have resolved the overloaded function
10234/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010235/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010236Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010237 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010238 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010239 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10240 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010241 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010242 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010243
Douglas Gregor51c538b2009-11-20 19:42:02 +000010244 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010245 }
10246
Douglas Gregor51c538b2009-11-20 19:42:02 +000010247 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010248 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10249 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010250 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010251 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010252 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010253 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010254 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010255 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010256
10257 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010258 ICE->getCastKind(),
10259 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010260 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010261 }
10262
Douglas Gregor51c538b2009-11-20 19:42:02 +000010263 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010264 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010265 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010266 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10267 if (Method->isStatic()) {
10268 // Do nothing: static member functions aren't any different
10269 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010270 } else {
John McCalle66edc12009-11-24 19:00:30 +000010271 // Fix the sub expression, which really has to be an
10272 // UnresolvedLookupExpr holding an overloaded member function
10273 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010274 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10275 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010276 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010277 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010278
John McCalld14a8642009-11-21 08:51:07 +000010279 assert(isa<DeclRefExpr>(SubExpr)
10280 && "fixed to something other than a decl ref");
10281 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10282 && "fixed to a member ref with no nested name qualifier");
10283
10284 // We have taken the address of a pointer to member
10285 // function. Perform the computation here so that we get the
10286 // appropriate pointer to member type.
10287 QualType ClassType
10288 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10289 QualType MemPtrType
10290 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10291
John McCall7decc9e2010-11-18 06:31:45 +000010292 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10293 VK_RValue, OK_Ordinary,
10294 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010295 }
10296 }
John McCall16df1e52010-03-30 21:47:33 +000010297 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10298 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010299 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010300 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010301
John McCalle3027922010-08-25 11:45:40 +000010302 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010303 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010304 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010305 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010306 }
John McCalld14a8642009-11-21 08:51:07 +000010307
10308 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010309 // FIXME: avoid copy.
10310 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010311 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010312 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10313 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010314 }
10315
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010316 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10317 ULE->getQualifierLoc(),
10318 Fn,
10319 ULE->getNameLoc(),
10320 Fn->getType(),
10321 VK_LValue,
10322 Found.getDecl(),
10323 TemplateArgs);
10324 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10325 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010326 }
10327
John McCall10eae182009-11-30 22:42:35 +000010328 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010329 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010330 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10331 if (MemExpr->hasExplicitTemplateArgs()) {
10332 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10333 TemplateArgs = &TemplateArgsBuffer;
10334 }
John McCall6b51f282009-11-23 01:53:49 +000010335
John McCall2d74de92009-12-01 22:10:20 +000010336 Expr *Base;
10337
John McCall7decc9e2010-11-18 06:31:45 +000010338 // If we're filling in a static method where we used to have an
10339 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010340 if (MemExpr->isImplicitAccess()) {
10341 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010342 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10343 MemExpr->getQualifierLoc(),
10344 Fn,
10345 MemExpr->getMemberLoc(),
10346 Fn->getType(),
10347 VK_LValue,
10348 Found.getDecl(),
10349 TemplateArgs);
10350 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10351 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010352 } else {
10353 SourceLocation Loc = MemExpr->getMemberLoc();
10354 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010355 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +000010356 Base = new (Context) CXXThisExpr(Loc,
10357 MemExpr->getBaseType(),
10358 /*isImplicit=*/true);
10359 }
John McCall2d74de92009-12-01 22:10:20 +000010360 } else
John McCallc3007a22010-10-26 07:05:15 +000010361 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010362
John McCall4adb38c2011-04-27 00:36:17 +000010363 ExprValueKind valueKind;
10364 QualType type;
10365 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10366 valueKind = VK_LValue;
10367 type = Fn->getType();
10368 } else {
10369 valueKind = VK_RValue;
10370 type = Context.BoundMemberTy;
10371 }
10372
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010373 MemberExpr *ME = MemberExpr::Create(Context, Base,
10374 MemExpr->isArrow(),
10375 MemExpr->getQualifierLoc(),
10376 Fn,
10377 Found,
10378 MemExpr->getMemberNameInfo(),
10379 TemplateArgs,
10380 type, valueKind, OK_Ordinary);
10381 ME->setHadMultipleCandidates(true);
10382 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010384
John McCallc3007a22010-10-26 07:05:15 +000010385 llvm_unreachable("Invalid reference to overloaded function");
10386 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010387}
10388
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010389ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010390 DeclAccessPair Found,
10391 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010392 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010393}
10394
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010395} // end namespace clang