blob: 7f1c86c22487cf3d0074800ca5ab6631f13a8f17 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000052}
53
John McCall5c32be02010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000202}
203
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000242bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261/// DebugPrint - Print this standard conversion sequence to standard
262/// error. Useful for debugging overloading issues.
263void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000264 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 bool PrintedSomething = false;
266 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000268 PrintedSomething = true;
269 }
270
271 if (Second != ICK_Identity) {
272 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000273 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000275 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000276
277 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000279 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000281 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000282 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000283 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 PrintedSomething = true;
285 }
286
287 if (Third != ICK_Identity) {
288 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000289 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000290 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000291 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000292 PrintedSomething = true;
293 }
294
295 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000296 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000297 }
298}
299
300/// DebugPrint - Print this user-defined conversion sequence to standard
301/// error. Useful for debugging overloading issues.
302void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000303 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304 if (Before.First || Before.Second || Before.Third) {
305 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000306 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000307 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000308 if (ConversionFunction)
309 OS << '\'' << *ConversionFunction << '\'';
310 else
311 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000312 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000313 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000314 After.DebugPrint();
315 }
316}
317
318/// DebugPrint - Print this implicit conversion sequence to standard
319/// error. Useful for debugging overloading issues.
320void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000322 switch (ConversionKind) {
323 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000324 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000325 Standard.DebugPrint();
326 break;
327 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000328 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329 UserDefined.DebugPrint();
330 break;
331 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000332 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000333 break;
John McCall0d1da222010-01-12 00:44:57 +0000334 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000335 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000336 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000338 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 break;
340 }
341
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000342 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000343}
344
John McCall0d1da222010-01-12 00:44:57 +0000345void AmbiguousConversionSequence::construct() {
346 new (&conversions()) ConversionSet();
347}
348
349void AmbiguousConversionSequence::destruct() {
350 conversions().~ConversionSet();
351}
352
353void
354AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
355 FromTypePtr = O.FromTypePtr;
356 ToTypePtr = O.ToTypePtr;
357 new (&conversions()) ConversionSet(O.conversions());
358}
359
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360namespace {
361 // Structure used by OverloadCandidate::DeductionFailureInfo to store
362 // template parameter and template argument information.
363 struct DFIParamWithArguments {
364 TemplateParameter Param;
365 TemplateArgument FirstArg;
366 TemplateArgument SecondArg;
367 };
368}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370/// \brief Convert from Sema's representation of template deduction information
371/// to the form used in overload-candidate information.
372OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000373static MakeDeductionFailureInfo(ASTContext &Context,
374 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000375 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 OverloadCandidate::DeductionFailureInfo Result;
377 Result.Result = static_cast<unsigned>(TDK);
378 Result.Data = 0;
379 switch (TDK) {
380 case Sema::TDK_Success:
381 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000382 case Sema::TDK_TooManyArguments:
383 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000387 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 Result.Data = Info.Param.getOpaqueValue();
389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000391 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000392 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000393 // FIXME: Should allocate from normal heap so that we can free this later.
394 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 Saved->Param = Info.Param;
396 Saved->FirstArg = Info.FirstArg;
397 Saved->SecondArg = Info.SecondArg;
398 Result.Data = Saved;
399 break;
400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000401
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000402 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000403 Result.Data = Info.take();
404 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000407 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000408 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411 return Result;
412}
John McCall0d1da222010-01-12 00:44:57 +0000413
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000414void OverloadCandidate::DeductionFailureInfo::Destroy() {
415 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
416 case Sema::TDK_Success:
417 case Sema::TDK_InstantiationDepth:
418 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000419 case Sema::TDK_TooManyArguments:
420 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000421 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000423
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000424 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000425 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000426 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000427 Data = 0;
428 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000429
430 case Sema::TDK_SubstitutionFailure:
431 // FIXME: Destroy the template arugment list?
432 Data = 0;
433 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor461761d2010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
442TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000443OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
444 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
445 case Sema::TDK_Success:
446 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000447 case Sema::TDK_TooManyArguments:
448 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000449 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000450 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000453 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000455
456 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000465
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000466 return TemplateParameter();
467}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Douglas Gregord09efd42010-05-08 20:07:26 +0000469TemplateArgumentList *
470OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
471 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
472 case Sema::TDK_Success:
473 case Sema::TDK_InstantiationDepth:
474 case Sema::TDK_TooManyArguments:
475 case Sema::TDK_TooFewArguments:
476 case Sema::TDK_Incomplete:
477 case Sema::TDK_InvalidExplicitArguments:
478 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000479 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000480 return 0;
481
482 case Sema::TDK_SubstitutionFailure:
483 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000484
Douglas Gregord09efd42010-05-08 20:07:26 +0000485 // Unhandled
486 case Sema::TDK_NonDeducedMismatch:
487 case Sema::TDK_FailedOverloadResolution:
488 break;
489 }
490
491 return 0;
492}
493
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
495 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
496 case Sema::TDK_Success:
497 case Sema::TDK_InstantiationDepth:
498 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000499 case Sema::TDK_TooManyArguments:
500 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000501 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000502 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503 return 0;
504
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000506 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000508
Douglas Gregor461761d2010-05-08 18:20:53 +0000509 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000510 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000511 case Sema::TDK_FailedOverloadResolution:
512 break;
513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000514
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000515 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000516}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000517
518const TemplateArgument *
519OverloadCandidate::DeductionFailureInfo::getSecondArg() {
520 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
521 case Sema::TDK_Success:
522 case Sema::TDK_InstantiationDepth:
523 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000524 case Sema::TDK_TooManyArguments:
525 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000526 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000527 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000528 return 0;
529
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000531 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000532 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
533
Douglas Gregor461761d2010-05-08 18:20:53 +0000534 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000536 case Sema::TDK_FailedOverloadResolution:
537 break;
538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000540 return 0;
541}
542
543void OverloadCandidateSet::clear() {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000544 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000545 Functions.clear();
Benjamin Kramerb0095172012-01-14 16:32:05 +0000546 NumInlineSequences = 0;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000547}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000548
John McCall4124c492011-10-17 18:40:02 +0000549namespace {
550 class UnbridgedCastsSet {
551 struct Entry {
552 Expr **Addr;
553 Expr *Saved;
554 };
555 SmallVector<Entry, 2> Entries;
556
557 public:
558 void save(Sema &S, Expr *&E) {
559 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
560 Entry entry = { &E, E };
561 Entries.push_back(entry);
562 E = S.stripARCUnbridgedCast(E);
563 }
564
565 void restore() {
566 for (SmallVectorImpl<Entry>::iterator
567 i = Entries.begin(), e = Entries.end(); i != e; ++i)
568 *i->Addr = i->Saved;
569 }
570 };
571}
572
573/// checkPlaceholderForOverload - Do any interesting placeholder-like
574/// preprocessing on the given expression.
575///
576/// \param unbridgedCasts a collection to which to add unbridged casts;
577/// without this, they will be immediately diagnosed as errors
578///
579/// Return true on unrecoverable error.
580static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
581 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000582 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
583 // We can't handle overloaded expressions here because overload
584 // resolution might reasonably tweak them.
585 if (placeholder->getKind() == BuiltinType::Overload) return false;
586
587 // If the context potentially accepts unbridged ARC casts, strip
588 // the unbridged cast and add it to the collection for later restoration.
589 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
590 unbridgedCasts) {
591 unbridgedCasts->save(S, E);
592 return false;
593 }
594
595 // Go ahead and check everything else.
596 ExprResult result = S.CheckPlaceholderExpr(E);
597 if (result.isInvalid())
598 return true;
599
600 E = result.take();
601 return false;
602 }
603
604 // Nothing to do.
605 return false;
606}
607
608/// checkArgPlaceholdersForOverload - Check a set of call operands for
609/// placeholders.
610static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
611 unsigned numArgs,
612 UnbridgedCastsSet &unbridged) {
613 for (unsigned i = 0; i != numArgs; ++i)
614 if (checkPlaceholderForOverload(S, args[i], &unbridged))
615 return true;
616
617 return false;
618}
619
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000620// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000621// overload of the declarations in Old. This routine returns false if
622// New and Old cannot be overloaded, e.g., if New has the same
623// signature as some function in Old (C++ 1.3.10) or if the Old
624// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000625// it does return false, MatchedDecl will point to the decl that New
626// cannot be overloaded with. This decl may be a UsingShadowDecl on
627// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000628//
629// Example: Given the following input:
630//
631// void f(int, float); // #1
632// void f(int, int); // #2
633// int f(int, int); // #3
634//
635// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000636// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000637//
John McCall3d988d92009-12-02 08:47:38 +0000638// When we process #2, Old contains only the FunctionDecl for #1. By
639// comparing the parameter types, we see that #1 and #2 are overloaded
640// (since they have different signatures), so this routine returns
641// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000642//
John McCall3d988d92009-12-02 08:47:38 +0000643// When we process #3, Old is an overload set containing #1 and #2. We
644// compare the signatures of #3 to #1 (they're overloaded, so we do
645// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
646// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000647// signature), IsOverload returns false and MatchedDecl will be set to
648// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000649//
650// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
651// into a class by a using declaration. The rules for whether to hide
652// shadow declarations ignore some properties which otherwise figure
653// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000654Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000655Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
656 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000657 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000658 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000659 NamedDecl *OldD = *I;
660
661 bool OldIsUsingDecl = false;
662 if (isa<UsingShadowDecl>(OldD)) {
663 OldIsUsingDecl = true;
664
665 // We can always introduce two using declarations into the same
666 // context, even if they have identical signatures.
667 if (NewIsUsingDecl) continue;
668
669 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
670 }
671
672 // If either declaration was introduced by a using declaration,
673 // we'll need to use slightly different rules for matching.
674 // Essentially, these rules are the normal rules, except that
675 // function templates hide function templates with different
676 // return types or template parameter lists.
677 bool UseMemberUsingDeclRules =
678 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
679
John McCall3d988d92009-12-02 08:47:38 +0000680 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000681 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
682 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
683 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
684 continue;
685 }
686
John McCalldaa3d6b2009-12-09 03:35:25 +0000687 Match = *I;
688 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000689 }
John McCall3d988d92009-12-02 08:47:38 +0000690 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000691 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
692 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
693 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
694 continue;
695 }
696
John McCalldaa3d6b2009-12-09 03:35:25 +0000697 Match = *I;
698 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000699 }
John McCalla8987a2942010-11-10 03:01:53 +0000700 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000701 // We can overload with these, which can show up when doing
702 // redeclaration checks for UsingDecls.
703 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000704 } else if (isa<TagDecl>(OldD)) {
705 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000706 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
707 // Optimistically assume that an unresolved using decl will
708 // overload; if it doesn't, we'll have to diagnose during
709 // template instantiation.
710 } else {
John McCall1f82f242009-11-18 22:49:29 +0000711 // (C++ 13p1):
712 // Only function declarations can be overloaded; object and type
713 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000714 Match = *I;
715 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000716 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000717 }
John McCall1f82f242009-11-18 22:49:29 +0000718
John McCalldaa3d6b2009-12-09 03:35:25 +0000719 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000720}
721
John McCalle9cccd82010-06-16 08:42:20 +0000722bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
723 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000724 // If both of the functions are extern "C", then they are not
725 // overloads.
726 if (Old->isExternC() && New->isExternC())
727 return false;
728
John McCall1f82f242009-11-18 22:49:29 +0000729 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
730 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
731
732 // C++ [temp.fct]p2:
733 // A function template can be overloaded with other function templates
734 // and with normal (non-template) functions.
735 if ((OldTemplate == 0) != (NewTemplate == 0))
736 return true;
737
738 // Is the function New an overload of the function Old?
739 QualType OldQType = Context.getCanonicalType(Old->getType());
740 QualType NewQType = Context.getCanonicalType(New->getType());
741
742 // Compare the signatures (C++ 1.3.10) of the two functions to
743 // determine whether they are overloads. If we find any mismatch
744 // in the signature, they are overloads.
745
746 // If either of these functions is a K&R-style function (no
747 // prototype), then we consider them to have matching signatures.
748 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
749 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
750 return false;
751
John McCall424cec92011-01-19 06:33:43 +0000752 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
753 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000754
755 // The signature of a function includes the types of its
756 // parameters (C++ 1.3.10), which includes the presence or absence
757 // of the ellipsis; see C++ DR 357).
758 if (OldQType != NewQType &&
759 (OldType->getNumArgs() != NewType->getNumArgs() ||
760 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000761 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000762 return true;
763
764 // C++ [temp.over.link]p4:
765 // The signature of a function template consists of its function
766 // signature, its return type and its template parameter list. The names
767 // of the template parameters are significant only for establishing the
768 // relationship between the template parameters and the rest of the
769 // signature.
770 //
771 // We check the return type and template parameter lists for function
772 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000773 //
774 // However, we don't consider either of these when deciding whether
775 // a member introduced by a shadow declaration is hidden.
776 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000777 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
778 OldTemplate->getTemplateParameters(),
779 false, TPL_TemplateMatch) ||
780 OldType->getResultType() != NewType->getResultType()))
781 return true;
782
783 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000784 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000785 //
786 // As part of this, also check whether one of the member functions
787 // is static, in which case they are not overloads (C++
788 // 13.1p2). While not part of the definition of the signature,
789 // this check is important to determine whether these functions
790 // can be overloaded.
791 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
792 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
793 if (OldMethod && NewMethod &&
794 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000795 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000796 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
797 if (!UseUsingDeclRules &&
798 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
799 (OldMethod->getRefQualifier() == RQ_None ||
800 NewMethod->getRefQualifier() == RQ_None)) {
801 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802 // - Member function declarations with the same name and the same
803 // parameter-type-list as well as member function template
804 // declarations with the same name, the same parameter-type-list, and
805 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000806 // them, but not all, have a ref-qualifier (8.3.5).
807 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
808 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
809 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
810 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
John McCall1f82f242009-11-18 22:49:29 +0000812 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
John McCall1f82f242009-11-18 22:49:29 +0000815 // The signatures match; this is not an overload.
816 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000817}
818
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000819/// \brief Checks availability of the function depending on the current
820/// function context. Inside an unavailable function, unavailability is ignored.
821///
822/// \returns true if \arg FD is unavailable and current context is inside
823/// an available function, false otherwise.
824bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
825 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
826}
827
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000828/// \brief Tries a user-defined conversion from From to ToType.
829///
830/// Produces an implicit conversion sequence for when a standard conversion
831/// is not an option. See TryImplicitConversion for more information.
832static ImplicitConversionSequence
833TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
834 bool SuppressUserConversions,
835 bool AllowExplicit,
836 bool InOverloadResolution,
837 bool CStyle,
838 bool AllowObjCWritebackConversion) {
839 ImplicitConversionSequence ICS;
840
841 if (SuppressUserConversions) {
842 // We're not in the case above, so there is no conversion that
843 // we can perform.
844 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
845 return ICS;
846 }
847
848 // Attempt user-defined conversion.
849 OverloadCandidateSet Conversions(From->getExprLoc());
850 OverloadingResult UserDefResult
851 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
852 AllowExplicit);
853
854 if (UserDefResult == OR_Success) {
855 ICS.setUserDefined();
856 // C++ [over.ics.user]p4:
857 // A conversion of an expression of class type to the same class
858 // type is given Exact Match rank, and a conversion of an
859 // expression of class type to a base class of that type is
860 // given Conversion rank, in spite of the fact that a copy
861 // constructor (i.e., a user-defined conversion function) is
862 // called for those cases.
863 if (CXXConstructorDecl *Constructor
864 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
865 QualType FromCanon
866 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
867 QualType ToCanon
868 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
869 if (Constructor->isCopyConstructor() &&
870 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
871 // Turn this into a "standard" conversion sequence, so that it
872 // gets ranked with standard conversion sequences.
873 ICS.setStandard();
874 ICS.Standard.setAsIdentityConversion();
875 ICS.Standard.setFromType(From->getType());
876 ICS.Standard.setAllToTypes(ToType);
877 ICS.Standard.CopyConstructor = Constructor;
878 if (ToCanon != FromCanon)
879 ICS.Standard.Second = ICK_Derived_To_Base;
880 }
881 }
882
883 // C++ [over.best.ics]p4:
884 // However, when considering the argument of a user-defined
885 // conversion function that is a candidate by 13.3.1.3 when
886 // invoked for the copying of the temporary in the second step
887 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
888 // 13.3.1.6 in all cases, only standard conversion sequences and
889 // ellipsis conversion sequences are allowed.
890 if (SuppressUserConversions && ICS.isUserDefined()) {
891 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
892 }
893 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
894 ICS.setAmbiguous();
895 ICS.Ambiguous.setFromType(From->getType());
896 ICS.Ambiguous.setToType(ToType);
897 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
898 Cand != Conversions.end(); ++Cand)
899 if (Cand->Viable)
900 ICS.Ambiguous.addConversion(Cand->Function);
901 } else {
902 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
903 }
904
905 return ICS;
906}
907
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000908/// TryImplicitConversion - Attempt to perform an implicit conversion
909/// from the given expression (Expr) to the given type (ToType). This
910/// function returns an implicit conversion sequence that can be used
911/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912///
913/// void f(float f);
914/// void g(int i) { f(i); }
915///
916/// this routine would produce an implicit conversion sequence to
917/// describe the initialization of f from i, which will be a standard
918/// conversion sequence containing an lvalue-to-rvalue conversion (C++
919/// 4.1) followed by a floating-integral conversion (C++ 4.9).
920//
921/// Note that this routine only determines how the conversion can be
922/// performed; it does not actually perform the conversion. As such,
923/// it will not produce any diagnostics if no conversion is available,
924/// but will instead return an implicit conversion sequence of kind
925/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000926///
927/// If @p SuppressUserConversions, then user-defined conversions are
928/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000929/// If @p AllowExplicit, then explicit user-defined conversions are
930/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000931///
932/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
933/// writeback conversion, which allows __autoreleasing id* parameters to
934/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000935static ImplicitConversionSequence
936TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
937 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000938 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000939 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000940 bool CStyle,
941 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000943 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000944 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000945 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000946 return ICS;
947 }
948
John McCall5c32be02010-08-24 20:38:10 +0000949 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000950 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000951 return ICS;
952 }
953
Douglas Gregor836a7e82010-08-11 02:15:33 +0000954 // C++ [over.ics.user]p4:
955 // A conversion of an expression of class type to the same class
956 // type is given Exact Match rank, and a conversion of an
957 // expression of class type to a base class of that type is
958 // given Conversion rank, in spite of the fact that a copy/move
959 // constructor (i.e., a user-defined conversion function) is
960 // called for those cases.
961 QualType FromType = From->getType();
962 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000963 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
964 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000965 ICS.setStandard();
966 ICS.Standard.setAsIdentityConversion();
967 ICS.Standard.setFromType(FromType);
968 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000969
Douglas Gregor5ab11652010-04-17 22:01:05 +0000970 // We don't actually check at this point whether there is a valid
971 // copy/move constructor, since overloading just assumes that it
972 // exists. When we actually perform initialization, we'll find the
973 // appropriate constructor to copy the returned object, if needed.
974 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000975
Douglas Gregor5ab11652010-04-17 22:01:05 +0000976 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000977 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000978 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000979
Douglas Gregor836a7e82010-08-11 02:15:33 +0000980 return ICS;
981 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000982
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000983 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
984 AllowExplicit, InOverloadResolution, CStyle,
985 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000986}
987
John McCall31168b02011-06-15 23:02:42 +0000988ImplicitConversionSequence
989Sema::TryImplicitConversion(Expr *From, QualType ToType,
990 bool SuppressUserConversions,
991 bool AllowExplicit,
992 bool InOverloadResolution,
993 bool CStyle,
994 bool AllowObjCWritebackConversion) {
995 return clang::TryImplicitConversion(*this, From, ToType,
996 SuppressUserConversions, AllowExplicit,
997 InOverloadResolution, CStyle,
998 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000999}
1000
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001001/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001002/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001003/// converted expression. Flavor is the kind of conversion we're
1004/// performing, used in the error message. If @p AllowExplicit,
1005/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001006ExprResult
1007Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001008 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001009 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001010 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001011}
1012
John Wiegley01296292011-04-08 18:41:53 +00001013ExprResult
1014Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001015 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001016 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001017 if (checkPlaceholderForOverload(*this, From))
1018 return ExprError();
1019
John McCall31168b02011-06-15 23:02:42 +00001020 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1021 bool AllowObjCWritebackConversion
1022 = getLangOptions().ObjCAutoRefCount &&
1023 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001024
John McCall5c32be02010-08-24 20:38:10 +00001025 ICS = clang::TryImplicitConversion(*this, From, ToType,
1026 /*SuppressUserConversions=*/false,
1027 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001028 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001029 /*CStyle=*/false,
1030 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001031 return PerformImplicitConversion(From, ToType, ICS, Action);
1032}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
1034/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001035/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001036bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1037 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001038 if (Context.hasSameUnqualifiedType(FromType, ToType))
1039 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001040
John McCall991eb4b2010-12-21 00:44:39 +00001041 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1042 // where F adds one of the following at most once:
1043 // - a pointer
1044 // - a member pointer
1045 // - a block pointer
1046 CanQualType CanTo = Context.getCanonicalType(ToType);
1047 CanQualType CanFrom = Context.getCanonicalType(FromType);
1048 Type::TypeClass TyClass = CanTo->getTypeClass();
1049 if (TyClass != CanFrom->getTypeClass()) return false;
1050 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1051 if (TyClass == Type::Pointer) {
1052 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1053 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1054 } else if (TyClass == Type::BlockPointer) {
1055 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1056 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1057 } else if (TyClass == Type::MemberPointer) {
1058 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1059 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1060 } else {
1061 return false;
1062 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001063
John McCall991eb4b2010-12-21 00:44:39 +00001064 TyClass = CanTo->getTypeClass();
1065 if (TyClass != CanFrom->getTypeClass()) return false;
1066 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1067 return false;
1068 }
1069
1070 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1071 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1072 if (!EInfo.getNoReturn()) return false;
1073
1074 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1075 assert(QualType(FromFn, 0).isCanonical());
1076 if (QualType(FromFn, 0) != CanTo) return false;
1077
1078 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001079 return true;
1080}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001081
Douglas Gregor46188682010-05-18 22:42:18 +00001082/// \brief Determine whether the conversion from FromType to ToType is a valid
1083/// vector conversion.
1084///
1085/// \param ICK Will be set to the vector conversion kind, if this is a vector
1086/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1088 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001089 // We need at least one of these types to be a vector type to have a vector
1090 // conversion.
1091 if (!ToType->isVectorType() && !FromType->isVectorType())
1092 return false;
1093
1094 // Identical types require no conversions.
1095 if (Context.hasSameUnqualifiedType(FromType, ToType))
1096 return false;
1097
1098 // There are no conversions between extended vector types, only identity.
1099 if (ToType->isExtVectorType()) {
1100 // There are no conversions between extended vector types other than the
1101 // identity conversion.
1102 if (FromType->isExtVectorType())
1103 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001104
Douglas Gregor46188682010-05-18 22:42:18 +00001105 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001106 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001107 ICK = ICK_Vector_Splat;
1108 return true;
1109 }
1110 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001111
1112 // We can perform the conversion between vector types in the following cases:
1113 // 1)vector types are equivalent AltiVec and GCC vector types
1114 // 2)lax vector conversions are permitted and the vector types are of the
1115 // same size
1116 if (ToType->isVectorType() && FromType->isVectorType()) {
1117 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001118 (Context.getLangOptions().LaxVectorConversions &&
1119 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001120 ICK = ICK_Vector_Conversion;
1121 return true;
1122 }
Douglas Gregor46188682010-05-18 22:42:18 +00001123 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001124
Douglas Gregor46188682010-05-18 22:42:18 +00001125 return false;
1126}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001127
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001128/// IsStandardConversion - Determines whether there is a standard
1129/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1130/// expression From to the type ToType. Standard conversion sequences
1131/// only consider non-class types; for conversions that involve class
1132/// types, use TryImplicitConversion. If a conversion exists, SCS will
1133/// contain the standard conversion sequence required to perform this
1134/// conversion and this routine will return true. Otherwise, this
1135/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001136static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1137 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001138 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001139 bool CStyle,
1140 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001141 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001142
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001143 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001144 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001145 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001146 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001147 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001148 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001149
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001150 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001151 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001152 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001153 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001154 return false;
1155
Mike Stump11289f42009-09-09 15:08:12 +00001156 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001157 }
1158
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159 // The first conversion can be an lvalue-to-rvalue conversion,
1160 // array-to-pointer conversion, or function-to-pointer conversion
1161 // (C++ 4p1).
1162
John McCall5c32be02010-08-24 20:38:10 +00001163 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001164 DeclAccessPair AccessPair;
1165 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001166 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001167 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001168 // We were able to resolve the address of the overloaded function,
1169 // so we can convert to the type of that function.
1170 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001171
1172 // we can sometimes resolve &foo<int> regardless of ToType, so check
1173 // if the type matches (identity) or we are converting to bool
1174 if (!S.Context.hasSameUnqualifiedType(
1175 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1176 QualType resultTy;
1177 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001178 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001179 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1180 // otherwise, only a boolean conversion is standard
1181 if (!ToType->isBooleanType())
1182 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001184
Chandler Carruthffce2452011-03-29 08:08:18 +00001185 // Check if the "from" expression is taking the address of an overloaded
1186 // function and recompute the FromType accordingly. Take advantage of the
1187 // fact that non-static member functions *must* have such an address-of
1188 // expression.
1189 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1190 if (Method && !Method->isStatic()) {
1191 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1192 "Non-unary operator on non-static member address");
1193 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1194 == UO_AddrOf &&
1195 "Non-address-of operator on non-static member address");
1196 const Type *ClassType
1197 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1198 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001199 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1200 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1201 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001202 "Non-address-of operator for overloaded function expression");
1203 FromType = S.Context.getPointerType(FromType);
1204 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001205
Douglas Gregor980fb162010-04-29 18:24:40 +00001206 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001207 assert(S.Context.hasSameType(
1208 FromType,
1209 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001210 } else {
1211 return false;
1212 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001213 }
John McCall154a2fd2011-08-30 00:57:29 +00001214 // Lvalue-to-rvalue conversion (C++11 4.1):
1215 // A glvalue (3.10) of a non-function, non-array type T can
1216 // be converted to a prvalue.
1217 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001218 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001219 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001220 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001221 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222
1223 // If T is a non-class type, the type of the rvalue is the
1224 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001225 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1226 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001227 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001228 } else if (FromType->isArrayType()) {
1229 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001230 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231
1232 // An lvalue or rvalue of type "array of N T" or "array of unknown
1233 // bound of T" can be converted to an rvalue of type "pointer to
1234 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001235 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236
John McCall5c32be02010-08-24 20:38:10 +00001237 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001238 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001239 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240
1241 // For the purpose of ranking in overload resolution
1242 // (13.3.3.1.1), this conversion is considered an
1243 // array-to-pointer conversion followed by a qualification
1244 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001245 SCS.Second = ICK_Identity;
1246 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001247 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001248 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001249 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001250 }
John McCall086a4642010-11-24 05:12:34 +00001251 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001252 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001253 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001254
1255 // An lvalue of function type T can be converted to an rvalue of
1256 // type "pointer to T." The result is a pointer to the
1257 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001258 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001259 } else {
1260 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001261 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001262 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001263 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001264
1265 // The second conversion can be an integral promotion, floating
1266 // point promotion, integral conversion, floating point conversion,
1267 // floating-integral conversion, pointer conversion,
1268 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001269 // For overloading in C, this can also be a "compatible-type"
1270 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001271 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001272 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001273 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001274 // The unqualified versions of the types are the same: there's no
1275 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001276 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001277 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001278 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001279 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001280 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001281 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001282 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001283 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001284 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001285 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001286 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001287 SCS.Second = ICK_Complex_Promotion;
1288 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001289 } else if (ToType->isBooleanType() &&
1290 (FromType->isArithmeticType() ||
1291 FromType->isAnyPointerType() ||
1292 FromType->isBlockPointerType() ||
1293 FromType->isMemberPointerType() ||
1294 FromType->isNullPtrType())) {
1295 // Boolean conversions (C++ 4.12).
1296 SCS.Second = ICK_Boolean_Conversion;
1297 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001298 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001299 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001300 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001301 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001303 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001304 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001305 SCS.Second = ICK_Complex_Conversion;
1306 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001307 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1308 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001309 // Complex-real conversions (C99 6.3.1.7)
1310 SCS.Second = ICK_Complex_Real;
1311 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001312 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001313 // Floating point conversions (C++ 4.8).
1314 SCS.Second = ICK_Floating_Conversion;
1315 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001316 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001317 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001318 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001319 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001320 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001321 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001322 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001323 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001324 SCS.Second = ICK_Block_Pointer_Conversion;
1325 } else if (AllowObjCWritebackConversion &&
1326 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1327 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001328 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1329 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001330 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001331 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001332 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001333 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001334 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001335 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001336 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001337 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001338 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001339 SCS.Second = SecondICK;
1340 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001341 } else if (!S.getLangOptions().CPlusPlus &&
1342 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001343 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001344 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001345 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001346 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001347 // Treat a conversion that strips "noreturn" as an identity conversion.
1348 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001349 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1350 InOverloadResolution,
1351 SCS, CStyle)) {
1352 SCS.Second = ICK_TransparentUnionConversion;
1353 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001354 } else {
1355 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001356 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001357 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001358 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001359
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001360 QualType CanonFrom;
1361 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001362 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001363 bool ObjCLifetimeConversion;
1364 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1365 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001366 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001367 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001368 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001369 CanonFrom = S.Context.getCanonicalType(FromType);
1370 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001371 } else {
1372 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001373 SCS.Third = ICK_Identity;
1374
Mike Stump11289f42009-09-09 15:08:12 +00001375 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001376 // [...] Any difference in top-level cv-qualification is
1377 // subsumed by the initialization itself and does not constitute
1378 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001379 CanonFrom = S.Context.getCanonicalType(FromType);
1380 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001381 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001382 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001383 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001384 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1385 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001386 FromType = ToType;
1387 CanonFrom = CanonTo;
1388 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001389 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001390 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001391
1392 // If we have not converted the argument type to the parameter type,
1393 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001394 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001395 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001396
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001397 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001398}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001399
1400static bool
1401IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1402 QualType &ToType,
1403 bool InOverloadResolution,
1404 StandardConversionSequence &SCS,
1405 bool CStyle) {
1406
1407 const RecordType *UT = ToType->getAsUnionType();
1408 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1409 return false;
1410 // The field to initialize within the transparent union.
1411 RecordDecl *UD = UT->getDecl();
1412 // It's compatible if the expression matches any of the fields.
1413 for (RecordDecl::field_iterator it = UD->field_begin(),
1414 itend = UD->field_end();
1415 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001416 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1417 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001418 ToType = it->getType();
1419 return true;
1420 }
1421 }
1422 return false;
1423}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424
1425/// IsIntegralPromotion - Determines whether the conversion from the
1426/// expression From (whose potentially-adjusted type is FromType) to
1427/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1428/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001429bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001430 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001431 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001432 if (!To) {
1433 return false;
1434 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001435
1436 // An rvalue of type char, signed char, unsigned char, short int, or
1437 // unsigned short int can be converted to an rvalue of type int if
1438 // int can represent all the values of the source type; otherwise,
1439 // the source rvalue can be converted to an rvalue of type unsigned
1440 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001441 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1442 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001443 if (// We can promote any signed, promotable integer type to an int
1444 (FromType->isSignedIntegerType() ||
1445 // We can promote any unsigned integer type whose size is
1446 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001447 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001448 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001449 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001450 }
1451
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001452 return To->getKind() == BuiltinType::UInt;
1453 }
1454
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001455 // C++0x [conv.prom]p3:
1456 // A prvalue of an unscoped enumeration type whose underlying type is not
1457 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1458 // following types that can represent all the values of the enumeration
1459 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1460 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001461 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001463 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001464 // with lowest integer conversion rank (4.13) greater than the rank of long
1465 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001466 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001467 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1468 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1469 // provided for a scoped enumeration.
1470 if (FromEnumType->getDecl()->isScoped())
1471 return false;
1472
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001473 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001474 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001475 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001476 return Context.hasSameUnqualifiedType(ToType,
1477 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001478 }
John McCall56774992009-12-09 09:09:27 +00001479
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001480 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001481 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1482 // to an rvalue a prvalue of the first of the following types that can
1483 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001484 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001486 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001487 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001488 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001489 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001490 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001491 // Determine whether the type we're converting from is signed or
1492 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001493 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001494 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001495
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001496 // The types we'll try to promote to, in the appropriate
1497 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001498 QualType PromoteTypes[6] = {
1499 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001500 Context.LongTy, Context.UnsignedLongTy ,
1501 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001502 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001503 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001504 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1505 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001506 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001507 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1508 // We found the type that we can promote to. If this is the
1509 // type we wanted, we have a promotion. Otherwise, no
1510 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001511 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001512 }
1513 }
1514 }
1515
1516 // An rvalue for an integral bit-field (9.6) can be converted to an
1517 // rvalue of type int if int can represent all the values of the
1518 // bit-field; otherwise, it can be converted to unsigned int if
1519 // unsigned int can represent all the values of the bit-field. If
1520 // the bit-field is larger yet, no integral promotion applies to
1521 // it. If the bit-field has an enumerated type, it is treated as any
1522 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001523 // FIXME: We should delay checking of bit-fields until we actually perform the
1524 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001525 using llvm::APSInt;
1526 if (From)
1527 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001528 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001529 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001530 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1531 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1532 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001533
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001534 // Are we promoting to an int from a bitfield that fits in an int?
1535 if (BitWidth < ToSize ||
1536 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1537 return To->getKind() == BuiltinType::Int;
1538 }
Mike Stump11289f42009-09-09 15:08:12 +00001539
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001540 // Are we promoting to an unsigned int from an unsigned bitfield
1541 // that fits into an unsigned int?
1542 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1543 return To->getKind() == BuiltinType::UInt;
1544 }
Mike Stump11289f42009-09-09 15:08:12 +00001545
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001546 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001547 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001548 }
Mike Stump11289f42009-09-09 15:08:12 +00001549
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001550 // An rvalue of type bool can be converted to an rvalue of type int,
1551 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001552 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001554 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001555
1556 return false;
1557}
1558
1559/// IsFloatingPointPromotion - Determines whether the conversion from
1560/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1561/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001562bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001563 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1564 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001565 /// An rvalue of type float can be converted to an rvalue of type
1566 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 if (FromBuiltin->getKind() == BuiltinType::Float &&
1568 ToBuiltin->getKind() == BuiltinType::Double)
1569 return true;
1570
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001571 // C99 6.3.1.5p1:
1572 // When a float is promoted to double or long double, or a
1573 // double is promoted to long double [...].
1574 if (!getLangOptions().CPlusPlus &&
1575 (FromBuiltin->getKind() == BuiltinType::Float ||
1576 FromBuiltin->getKind() == BuiltinType::Double) &&
1577 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1578 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001579
1580 // Half can be promoted to float.
1581 if (FromBuiltin->getKind() == BuiltinType::Half &&
1582 ToBuiltin->getKind() == BuiltinType::Float)
1583 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001584 }
1585
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586 return false;
1587}
1588
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001589/// \brief Determine if a conversion is a complex promotion.
1590///
1591/// A complex promotion is defined as a complex -> complex conversion
1592/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001593/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001594bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001595 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001596 if (!FromComplex)
1597 return false;
1598
John McCall9dd450b2009-09-21 23:43:11 +00001599 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001600 if (!ToComplex)
1601 return false;
1602
1603 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001604 ToComplex->getElementType()) ||
1605 IsIntegralPromotion(0, FromComplex->getElementType(),
1606 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001607}
1608
Douglas Gregor237f96c2008-11-26 23:31:11 +00001609/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1610/// the pointer type FromPtr to a pointer to type ToPointee, with the
1611/// same type qualifiers as FromPtr has on its pointee type. ToType,
1612/// if non-empty, will be a pointer to ToType that may or may not have
1613/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001614///
Mike Stump11289f42009-09-09 15:08:12 +00001615static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001616BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001617 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001618 ASTContext &Context,
1619 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001620 assert((FromPtr->getTypeClass() == Type::Pointer ||
1621 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1622 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623
John McCall31168b02011-06-15 23:02:42 +00001624 /// Conversions to 'id' subsume cv-qualifier conversions.
1625 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001626 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001627
1628 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001629 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001630 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001631 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001632
John McCall31168b02011-06-15 23:02:42 +00001633 if (StripObjCLifetime)
1634 Quals.removeObjCLifetime();
1635
Mike Stump11289f42009-09-09 15:08:12 +00001636 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001637 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001638 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001639 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001640 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001641
1642 // Build a pointer to ToPointee. It has the right qualifiers
1643 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001644 if (isa<ObjCObjectPointerType>(ToType))
1645 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001646 return Context.getPointerType(ToPointee);
1647 }
1648
1649 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001650 QualType QualifiedCanonToPointee
1651 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001652
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001653 if (isa<ObjCObjectPointerType>(ToType))
1654 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1655 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001656}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001657
Mike Stump11289f42009-09-09 15:08:12 +00001658static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001659 bool InOverloadResolution,
1660 ASTContext &Context) {
1661 // Handle value-dependent integral null pointer constants correctly.
1662 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1663 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001664 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001665 return !InOverloadResolution;
1666
Douglas Gregor56751b52009-09-25 04:25:58 +00001667 return Expr->isNullPointerConstant(Context,
1668 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1669 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001670}
Mike Stump11289f42009-09-09 15:08:12 +00001671
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001672/// IsPointerConversion - Determines whether the conversion of the
1673/// expression From, which has the (possibly adjusted) type FromType,
1674/// can be converted to the type ToType via a pointer conversion (C++
1675/// 4.10). If so, returns true and places the converted type (that
1676/// might differ from ToType in its cv-qualifiers at some level) into
1677/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001678///
Douglas Gregora29dc052008-11-27 01:19:21 +00001679/// This routine also supports conversions to and from block pointers
1680/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1681/// pointers to interfaces. FIXME: Once we've determined the
1682/// appropriate overloading rules for Objective-C, we may want to
1683/// split the Objective-C checks into a different routine; however,
1684/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001685/// conversions, so for now they live here. IncompatibleObjC will be
1686/// set if the conversion is an allowed Objective-C conversion that
1687/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001689 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001690 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001691 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001692 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001693 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1694 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001695 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001696
Mike Stump11289f42009-09-09 15:08:12 +00001697 // Conversion from a null pointer constant to any Objective-C pointer type.
1698 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001699 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001700 ConvertedType = ToType;
1701 return true;
1702 }
1703
Douglas Gregor231d1c62008-11-27 00:15:41 +00001704 // Blocks: Block pointers can be converted to void*.
1705 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001706 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001707 ConvertedType = ToType;
1708 return true;
1709 }
1710 // Blocks: A null pointer constant can be converted to a block
1711 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001712 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001713 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001714 ConvertedType = ToType;
1715 return true;
1716 }
1717
Sebastian Redl576fd422009-05-10 18:38:11 +00001718 // If the left-hand-side is nullptr_t, the right side can be a null
1719 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001720 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001721 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001722 ConvertedType = ToType;
1723 return true;
1724 }
1725
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001726 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727 if (!ToTypePtr)
1728 return false;
1729
1730 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001731 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001732 ConvertedType = ToType;
1733 return true;
1734 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001735
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001736 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001737 // , including objective-c pointers.
1738 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001739 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1740 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001741 ConvertedType = BuildSimilarlyQualifiedPointerType(
1742 FromType->getAs<ObjCObjectPointerType>(),
1743 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001744 ToType, Context);
1745 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001746 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001747 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001748 if (!FromTypePtr)
1749 return false;
1750
1751 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001752
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001753 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001754 // pointer conversion, so don't do all of the work below.
1755 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1756 return false;
1757
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758 // An rvalue of type "pointer to cv T," where T is an object type,
1759 // can be converted to an rvalue of type "pointer to cv void" (C++
1760 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001761 if (FromPointeeType->isIncompleteOrObjectType() &&
1762 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001763 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001764 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001765 ToType, Context,
1766 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001767 return true;
1768 }
1769
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001770 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001771 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001772 ToPointeeType->isVoidType()) {
1773 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1774 ToPointeeType,
1775 ToType, Context);
1776 return true;
1777 }
1778
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001779 // When we're overloading in C, we allow a special kind of pointer
1780 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001781 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001782 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001783 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001784 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001785 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001786 return true;
1787 }
1788
Douglas Gregor5c407d92008-10-23 00:40:37 +00001789 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001790 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001791 // An rvalue of type "pointer to cv D," where D is a class type,
1792 // can be converted to an rvalue of type "pointer to cv B," where
1793 // B is a base class (clause 10) of D. If B is an inaccessible
1794 // (clause 11) or ambiguous (10.2) base class of D, a program that
1795 // necessitates this conversion is ill-formed. The result of the
1796 // conversion is a pointer to the base class sub-object of the
1797 // derived class object. The null pointer value is converted to
1798 // the null pointer value of the destination type.
1799 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001800 // Note that we do not check for ambiguity or inaccessibility
1801 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001802 if (getLangOptions().CPlusPlus &&
1803 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001804 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001805 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001806 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001807 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001808 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001809 ToType, Context);
1810 return true;
1811 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001812
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001813 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1814 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1815 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1816 ToPointeeType,
1817 ToType, Context);
1818 return true;
1819 }
1820
Douglas Gregora119f102008-12-19 19:13:09 +00001821 return false;
1822}
Douglas Gregoraec25842011-04-26 23:16:46 +00001823
1824/// \brief Adopt the given qualifiers for the given type.
1825static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1826 Qualifiers TQs = T.getQualifiers();
1827
1828 // Check whether qualifiers already match.
1829 if (TQs == Qs)
1830 return T;
1831
1832 if (Qs.compatiblyIncludes(TQs))
1833 return Context.getQualifiedType(T, Qs);
1834
1835 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1836}
Douglas Gregora119f102008-12-19 19:13:09 +00001837
1838/// isObjCPointerConversion - Determines whether this is an
1839/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1840/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001841bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001842 QualType& ConvertedType,
1843 bool &IncompatibleObjC) {
1844 if (!getLangOptions().ObjC1)
1845 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001846
Douglas Gregoraec25842011-04-26 23:16:46 +00001847 // The set of qualifiers on the type we're converting from.
1848 Qualifiers FromQualifiers = FromType.getQualifiers();
1849
Steve Naroff7cae42b2009-07-10 23:34:53 +00001850 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001851 const ObjCObjectPointerType* ToObjCPtr =
1852 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001853 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001854 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001855
Steve Naroff7cae42b2009-07-10 23:34:53 +00001856 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001857 // If the pointee types are the same (ignoring qualifications),
1858 // then this is not a pointer conversion.
1859 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1860 FromObjCPtr->getPointeeType()))
1861 return false;
1862
Douglas Gregoraec25842011-04-26 23:16:46 +00001863 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001864 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001865 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001866 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001867 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001868 return true;
1869 }
1870 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001871 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001872 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001873 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001874 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001875 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001876 return true;
1877 }
1878 // Objective C++: We're able to convert from a pointer to an
1879 // interface to a pointer to a different interface.
1880 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001881 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1882 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1883 if (getLangOptions().CPlusPlus && LHS && RHS &&
1884 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1885 FromObjCPtr->getPointeeType()))
1886 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001887 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001888 ToObjCPtr->getPointeeType(),
1889 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001890 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001891 return true;
1892 }
1893
1894 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1895 // Okay: this is some kind of implicit downcast of Objective-C
1896 // interfaces, which is permitted. However, we're going to
1897 // complain about it.
1898 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001899 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001900 ToObjCPtr->getPointeeType(),
1901 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001902 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001903 return true;
1904 }
Mike Stump11289f42009-09-09 15:08:12 +00001905 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001906 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001907 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001908 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001909 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001910 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001911 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001912 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001913 // to a block pointer type.
1914 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001915 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001916 return true;
1917 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001918 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001919 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001920 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001921 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001922 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001923 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001924 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001925 return true;
1926 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001927 else
Douglas Gregora119f102008-12-19 19:13:09 +00001928 return false;
1929
Douglas Gregor033f56d2008-12-23 00:53:59 +00001930 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001931 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001932 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001933 else if (const BlockPointerType *FromBlockPtr =
1934 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001935 FromPointeeType = FromBlockPtr->getPointeeType();
1936 else
Douglas Gregora119f102008-12-19 19:13:09 +00001937 return false;
1938
Douglas Gregora119f102008-12-19 19:13:09 +00001939 // If we have pointers to pointers, recursively check whether this
1940 // is an Objective-C conversion.
1941 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1942 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1943 IncompatibleObjC)) {
1944 // We always complain about this conversion.
1945 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001946 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001947 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001948 return true;
1949 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001950 // Allow conversion of pointee being objective-c pointer to another one;
1951 // as in I* to id.
1952 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1953 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1954 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1955 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001956
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001957 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001958 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001959 return true;
1960 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001961
Douglas Gregor033f56d2008-12-23 00:53:59 +00001962 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001963 // differences in the argument and result types are in Objective-C
1964 // pointer conversions. If so, we permit the conversion (but
1965 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001966 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001967 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001968 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001969 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001970 if (FromFunctionType && ToFunctionType) {
1971 // If the function types are exactly the same, this isn't an
1972 // Objective-C pointer conversion.
1973 if (Context.getCanonicalType(FromPointeeType)
1974 == Context.getCanonicalType(ToPointeeType))
1975 return false;
1976
1977 // Perform the quick checks that will tell us whether these
1978 // function types are obviously different.
1979 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1980 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1981 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1982 return false;
1983
1984 bool HasObjCConversion = false;
1985 if (Context.getCanonicalType(FromFunctionType->getResultType())
1986 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1987 // Okay, the types match exactly. Nothing to do.
1988 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1989 ToFunctionType->getResultType(),
1990 ConvertedType, IncompatibleObjC)) {
1991 // Okay, we have an Objective-C pointer conversion.
1992 HasObjCConversion = true;
1993 } else {
1994 // Function types are too different. Abort.
1995 return false;
1996 }
Mike Stump11289f42009-09-09 15:08:12 +00001997
Douglas Gregora119f102008-12-19 19:13:09 +00001998 // Check argument types.
1999 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2000 ArgIdx != NumArgs; ++ArgIdx) {
2001 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2002 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2003 if (Context.getCanonicalType(FromArgType)
2004 == Context.getCanonicalType(ToArgType)) {
2005 // Okay, the types match exactly. Nothing to do.
2006 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2007 ConvertedType, IncompatibleObjC)) {
2008 // Okay, we have an Objective-C pointer conversion.
2009 HasObjCConversion = true;
2010 } else {
2011 // Argument types are too different. Abort.
2012 return false;
2013 }
2014 }
2015
2016 if (HasObjCConversion) {
2017 // We had an Objective-C conversion. Allow this pointer
2018 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002019 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002020 IncompatibleObjC = true;
2021 return true;
2022 }
2023 }
2024
Sebastian Redl72b597d2009-01-25 19:43:20 +00002025 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002026}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002027
John McCall31168b02011-06-15 23:02:42 +00002028/// \brief Determine whether this is an Objective-C writeback conversion,
2029/// used for parameter passing when performing automatic reference counting.
2030///
2031/// \param FromType The type we're converting form.
2032///
2033/// \param ToType The type we're converting to.
2034///
2035/// \param ConvertedType The type that will be produced after applying
2036/// this conversion.
2037bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2038 QualType &ConvertedType) {
2039 if (!getLangOptions().ObjCAutoRefCount ||
2040 Context.hasSameUnqualifiedType(FromType, ToType))
2041 return false;
2042
2043 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2044 QualType ToPointee;
2045 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2046 ToPointee = ToPointer->getPointeeType();
2047 else
2048 return false;
2049
2050 Qualifiers ToQuals = ToPointee.getQualifiers();
2051 if (!ToPointee->isObjCLifetimeType() ||
2052 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2053 !ToQuals.withoutObjCGLifetime().empty())
2054 return false;
2055
2056 // Argument must be a pointer to __strong to __weak.
2057 QualType FromPointee;
2058 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2059 FromPointee = FromPointer->getPointeeType();
2060 else
2061 return false;
2062
2063 Qualifiers FromQuals = FromPointee.getQualifiers();
2064 if (!FromPointee->isObjCLifetimeType() ||
2065 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2066 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2067 return false;
2068
2069 // Make sure that we have compatible qualifiers.
2070 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2071 if (!ToQuals.compatiblyIncludes(FromQuals))
2072 return false;
2073
2074 // Remove qualifiers from the pointee type we're converting from; they
2075 // aren't used in the compatibility check belong, and we'll be adding back
2076 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2077 FromPointee = FromPointee.getUnqualifiedType();
2078
2079 // The unqualified form of the pointee types must be compatible.
2080 ToPointee = ToPointee.getUnqualifiedType();
2081 bool IncompatibleObjC;
2082 if (Context.typesAreCompatible(FromPointee, ToPointee))
2083 FromPointee = ToPointee;
2084 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2085 IncompatibleObjC))
2086 return false;
2087
2088 /// \brief Construct the type we're converting to, which is a pointer to
2089 /// __autoreleasing pointee.
2090 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2091 ConvertedType = Context.getPointerType(FromPointee);
2092 return true;
2093}
2094
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002095bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2096 QualType& ConvertedType) {
2097 QualType ToPointeeType;
2098 if (const BlockPointerType *ToBlockPtr =
2099 ToType->getAs<BlockPointerType>())
2100 ToPointeeType = ToBlockPtr->getPointeeType();
2101 else
2102 return false;
2103
2104 QualType FromPointeeType;
2105 if (const BlockPointerType *FromBlockPtr =
2106 FromType->getAs<BlockPointerType>())
2107 FromPointeeType = FromBlockPtr->getPointeeType();
2108 else
2109 return false;
2110 // We have pointer to blocks, check whether the only
2111 // differences in the argument and result types are in Objective-C
2112 // pointer conversions. If so, we permit the conversion.
2113
2114 const FunctionProtoType *FromFunctionType
2115 = FromPointeeType->getAs<FunctionProtoType>();
2116 const FunctionProtoType *ToFunctionType
2117 = ToPointeeType->getAs<FunctionProtoType>();
2118
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002119 if (!FromFunctionType || !ToFunctionType)
2120 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002121
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002122 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002123 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002124
2125 // Perform the quick checks that will tell us whether these
2126 // function types are obviously different.
2127 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2128 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2129 return false;
2130
2131 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2132 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2133 if (FromEInfo != ToEInfo)
2134 return false;
2135
2136 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002137 if (Context.hasSameType(FromFunctionType->getResultType(),
2138 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002139 // Okay, the types match exactly. Nothing to do.
2140 } else {
2141 QualType RHS = FromFunctionType->getResultType();
2142 QualType LHS = ToFunctionType->getResultType();
2143 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2144 !RHS.hasQualifiers() && LHS.hasQualifiers())
2145 LHS = LHS.getUnqualifiedType();
2146
2147 if (Context.hasSameType(RHS,LHS)) {
2148 // OK exact match.
2149 } else if (isObjCPointerConversion(RHS, LHS,
2150 ConvertedType, IncompatibleObjC)) {
2151 if (IncompatibleObjC)
2152 return false;
2153 // Okay, we have an Objective-C pointer conversion.
2154 }
2155 else
2156 return false;
2157 }
2158
2159 // Check argument types.
2160 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2161 ArgIdx != NumArgs; ++ArgIdx) {
2162 IncompatibleObjC = false;
2163 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2164 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2165 if (Context.hasSameType(FromArgType, ToArgType)) {
2166 // Okay, the types match exactly. Nothing to do.
2167 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2168 ConvertedType, IncompatibleObjC)) {
2169 if (IncompatibleObjC)
2170 return false;
2171 // Okay, we have an Objective-C pointer conversion.
2172 } else
2173 // Argument types are too different. Abort.
2174 return false;
2175 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002176 if (LangOpts.ObjCAutoRefCount &&
2177 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2178 ToFunctionType))
2179 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002180
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002181 ConvertedType = ToType;
2182 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002183}
2184
Richard Trieucaff2472011-11-23 22:32:32 +00002185enum {
2186 ft_default,
2187 ft_different_class,
2188 ft_parameter_arity,
2189 ft_parameter_mismatch,
2190 ft_return_type,
2191 ft_qualifer_mismatch
2192};
2193
2194/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2195/// function types. Catches different number of parameter, mismatch in
2196/// parameter types, and different return types.
2197void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2198 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002199 // If either type is not valid, include no extra info.
2200 if (FromType.isNull() || ToType.isNull()) {
2201 PDiag << ft_default;
2202 return;
2203 }
2204
Richard Trieucaff2472011-11-23 22:32:32 +00002205 // Get the function type from the pointers.
2206 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2207 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2208 *ToMember = ToType->getAs<MemberPointerType>();
2209 if (FromMember->getClass() != ToMember->getClass()) {
2210 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2211 << QualType(FromMember->getClass(), 0);
2212 return;
2213 }
2214 FromType = FromMember->getPointeeType();
2215 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002216 }
2217
Richard Trieu96ed5b62011-12-13 23:19:45 +00002218 if (FromType->isPointerType())
2219 FromType = FromType->getPointeeType();
2220 if (ToType->isPointerType())
2221 ToType = ToType->getPointeeType();
2222
2223 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002224 FromType = FromType.getNonReferenceType();
2225 ToType = ToType.getNonReferenceType();
2226
Richard Trieucaff2472011-11-23 22:32:32 +00002227 // Don't print extra info for non-specialized template functions.
2228 if (FromType->isInstantiationDependentType() &&
2229 !FromType->getAs<TemplateSpecializationType>()) {
2230 PDiag << ft_default;
2231 return;
2232 }
2233
Richard Trieu96ed5b62011-12-13 23:19:45 +00002234 // No extra info for same types.
2235 if (Context.hasSameType(FromType, ToType)) {
2236 PDiag << ft_default;
2237 return;
2238 }
2239
Richard Trieucaff2472011-11-23 22:32:32 +00002240 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2241 *ToFunction = ToType->getAs<FunctionProtoType>();
2242
2243 // Both types need to be function types.
2244 if (!FromFunction || !ToFunction) {
2245 PDiag << ft_default;
2246 return;
2247 }
2248
2249 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2250 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2251 << FromFunction->getNumArgs();
2252 return;
2253 }
2254
2255 // Handle different parameter types.
2256 unsigned ArgPos;
2257 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2258 PDiag << ft_parameter_mismatch << ArgPos + 1
2259 << ToFunction->getArgType(ArgPos)
2260 << FromFunction->getArgType(ArgPos);
2261 return;
2262 }
2263
2264 // Handle different return type.
2265 if (!Context.hasSameType(FromFunction->getResultType(),
2266 ToFunction->getResultType())) {
2267 PDiag << ft_return_type << ToFunction->getResultType()
2268 << FromFunction->getResultType();
2269 return;
2270 }
2271
2272 unsigned FromQuals = FromFunction->getTypeQuals(),
2273 ToQuals = ToFunction->getTypeQuals();
2274 if (FromQuals != ToQuals) {
2275 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2276 return;
2277 }
2278
2279 // Unable to find a difference, so add no extra info.
2280 PDiag << ft_default;
2281}
2282
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002283/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002284/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002285/// they have same number of arguments. This routine assumes that Objective-C
2286/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002287/// If the parameters are different, ArgPos will have the the parameter index
2288/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002289bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002290 const FunctionProtoType *NewType,
2291 unsigned *ArgPos) {
2292 if (!getLangOptions().ObjC1) {
2293 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2294 N = NewType->arg_type_begin(),
2295 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2296 if (!Context.hasSameType(*O, *N)) {
2297 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2298 return false;
2299 }
2300 }
2301 return true;
2302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002303
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002304 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2305 N = NewType->arg_type_begin(),
2306 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2307 QualType ToType = (*O);
2308 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002309 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002310 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2311 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002312 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2313 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2314 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2315 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002316 continue;
2317 }
John McCall8b07ec22010-05-15 11:32:37 +00002318 else if (const ObjCObjectPointerType *PTTo =
2319 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002320 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002321 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002322 if (Context.hasSameUnqualifiedType(
2323 PTTo->getObjectType()->getBaseType(),
2324 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002325 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002326 }
Richard Trieucaff2472011-11-23 22:32:32 +00002327 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002328 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002329 }
2330 }
2331 return true;
2332}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002333
Douglas Gregor39c16d42008-10-24 04:54:22 +00002334/// CheckPointerConversion - Check the pointer conversion from the
2335/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002336/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002337/// conversions for which IsPointerConversion has already returned
2338/// true. It returns true and produces a diagnostic if there was an
2339/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002340bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002341 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002342 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002343 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002344 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002345 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002346
John McCall8cb679e2010-11-15 09:13:47 +00002347 Kind = CK_BitCast;
2348
Chandler Carruthffab8732011-04-09 07:32:05 +00002349 if (!IsCStyleOrFunctionalCast &&
2350 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2351 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2352 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002353 PDiag(diag::warn_impcast_bool_to_null_pointer)
2354 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002355
John McCall9320b872011-09-09 05:25:32 +00002356 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2357 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002358 QualType FromPointeeType = FromPtrType->getPointeeType(),
2359 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002360
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002361 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2362 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002363 // We must have a derived-to-base conversion. Check an
2364 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002365 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2366 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002367 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002368 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002369 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002370
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002371 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002372 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002373 }
2374 }
John McCall9320b872011-09-09 05:25:32 +00002375 } else if (const ObjCObjectPointerType *ToPtrType =
2376 ToType->getAs<ObjCObjectPointerType>()) {
2377 if (const ObjCObjectPointerType *FromPtrType =
2378 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002379 // Objective-C++ conversions are always okay.
2380 // FIXME: We should have a different class of conversions for the
2381 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002382 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002383 return false;
John McCall9320b872011-09-09 05:25:32 +00002384 } else if (FromType->isBlockPointerType()) {
2385 Kind = CK_BlockPointerToObjCPointerCast;
2386 } else {
2387 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002388 }
John McCall9320b872011-09-09 05:25:32 +00002389 } else if (ToType->isBlockPointerType()) {
2390 if (!FromType->isBlockPointerType())
2391 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002392 }
John McCall8cb679e2010-11-15 09:13:47 +00002393
2394 // We shouldn't fall into this case unless it's valid for other
2395 // reasons.
2396 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2397 Kind = CK_NullToPointer;
2398
Douglas Gregor39c16d42008-10-24 04:54:22 +00002399 return false;
2400}
2401
Sebastian Redl72b597d2009-01-25 19:43:20 +00002402/// IsMemberPointerConversion - Determines whether the conversion of the
2403/// expression From, which has the (possibly adjusted) type FromType, can be
2404/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2405/// If so, returns true and places the converted type (that might differ from
2406/// ToType in its cv-qualifiers at some level) into ConvertedType.
2407bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002408 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002409 bool InOverloadResolution,
2410 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002411 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002412 if (!ToTypePtr)
2413 return false;
2414
2415 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002416 if (From->isNullPointerConstant(Context,
2417 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2418 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002419 ConvertedType = ToType;
2420 return true;
2421 }
2422
2423 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002424 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002425 if (!FromTypePtr)
2426 return false;
2427
2428 // A pointer to member of B can be converted to a pointer to member of D,
2429 // where D is derived from B (C++ 4.11p2).
2430 QualType FromClass(FromTypePtr->getClass(), 0);
2431 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002432
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002433 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2434 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2435 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002436 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2437 ToClass.getTypePtr());
2438 return true;
2439 }
2440
2441 return false;
2442}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002443
Sebastian Redl72b597d2009-01-25 19:43:20 +00002444/// CheckMemberPointerConversion - Check the member pointer conversion from the
2445/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002446/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002447/// for which IsMemberPointerConversion has already returned true. It returns
2448/// true and produces a diagnostic if there was an error, or returns false
2449/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002450bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002451 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002452 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002453 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002454 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002455 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002456 if (!FromPtrType) {
2457 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002458 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002459 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002460 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002461 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002462 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002463 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002464
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002465 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002466 assert(ToPtrType && "No member pointer cast has a target type "
2467 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002468
Sebastian Redled8f2002009-01-28 18:33:18 +00002469 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2470 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002471
Sebastian Redled8f2002009-01-28 18:33:18 +00002472 // FIXME: What about dependent types?
2473 assert(FromClass->isRecordType() && "Pointer into non-class.");
2474 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002475
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002476 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002477 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002478 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2479 assert(DerivationOkay &&
2480 "Should not have been called if derivation isn't OK.");
2481 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002482
Sebastian Redled8f2002009-01-28 18:33:18 +00002483 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2484 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002485 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2486 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2487 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2488 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002489 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002490
Douglas Gregor89ee6822009-02-28 01:32:25 +00002491 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002492 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2493 << FromClass << ToClass << QualType(VBase, 0)
2494 << From->getSourceRange();
2495 return true;
2496 }
2497
John McCall5b0829a2010-02-10 09:31:12 +00002498 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002499 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2500 Paths.front(),
2501 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002502
Anders Carlssond7923c62009-08-22 23:33:40 +00002503 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002504 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002505 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002506 return false;
2507}
2508
Douglas Gregor9a657932008-10-21 23:43:52 +00002509/// IsQualificationConversion - Determines whether the conversion from
2510/// an rvalue of type FromType to ToType is a qualification conversion
2511/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002512///
2513/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2514/// when the qualification conversion involves a change in the Objective-C
2515/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002516bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002517Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002518 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002519 FromType = Context.getCanonicalType(FromType);
2520 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002521 ObjCLifetimeConversion = false;
2522
Douglas Gregor9a657932008-10-21 23:43:52 +00002523 // If FromType and ToType are the same type, this is not a
2524 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002525 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002526 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002527
Douglas Gregor9a657932008-10-21 23:43:52 +00002528 // (C++ 4.4p4):
2529 // A conversion can add cv-qualifiers at levels other than the first
2530 // in multi-level pointers, subject to the following rules: [...]
2531 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002532 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002533 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002534 // Within each iteration of the loop, we check the qualifiers to
2535 // determine if this still looks like a qualification
2536 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002537 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002538 // until there are no more pointers or pointers-to-members left to
2539 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002540 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002541
Douglas Gregor90609aa2011-04-25 18:40:17 +00002542 Qualifiers FromQuals = FromType.getQualifiers();
2543 Qualifiers ToQuals = ToType.getQualifiers();
2544
John McCall31168b02011-06-15 23:02:42 +00002545 // Objective-C ARC:
2546 // Check Objective-C lifetime conversions.
2547 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2548 UnwrappedAnyPointer) {
2549 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2550 ObjCLifetimeConversion = true;
2551 FromQuals.removeObjCLifetime();
2552 ToQuals.removeObjCLifetime();
2553 } else {
2554 // Qualification conversions cannot cast between different
2555 // Objective-C lifetime qualifiers.
2556 return false;
2557 }
2558 }
2559
Douglas Gregorf30053d2011-05-08 06:09:53 +00002560 // Allow addition/removal of GC attributes but not changing GC attributes.
2561 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2562 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2563 FromQuals.removeObjCGCAttr();
2564 ToQuals.removeObjCGCAttr();
2565 }
2566
Douglas Gregor9a657932008-10-21 23:43:52 +00002567 // -- for every j > 0, if const is in cv 1,j then const is in cv
2568 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002569 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002570 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002571
Douglas Gregor9a657932008-10-21 23:43:52 +00002572 // -- if the cv 1,j and cv 2,j are different, then const is in
2573 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002574 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002575 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002576 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002577
Douglas Gregor9a657932008-10-21 23:43:52 +00002578 // Keep track of whether all prior cv-qualifiers in the "to" type
2579 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002580 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002581 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002582 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002583
2584 // We are left with FromType and ToType being the pointee types
2585 // after unwrapping the original FromType and ToType the same number
2586 // of types. If we unwrapped any pointers, and if FromType and
2587 // ToType have the same unqualified type (since we checked
2588 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002589 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002590}
2591
Douglas Gregor576e98c2009-01-30 23:27:23 +00002592/// Determines whether there is a user-defined conversion sequence
2593/// (C++ [over.ics.user]) that converts expression From to the type
2594/// ToType. If such a conversion exists, User will contain the
2595/// user-defined conversion sequence that performs such a conversion
2596/// and this routine will return true. Otherwise, this routine returns
2597/// false and User is unspecified.
2598///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002599/// \param AllowExplicit true if the conversion should consider C++0x
2600/// "explicit" conversion functions as well as non-explicit conversion
2601/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002602static OverloadingResult
2603IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2604 UserDefinedConversionSequence& User,
2605 OverloadCandidateSet& CandidateSet,
2606 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002607 // Whether we will only visit constructors.
2608 bool ConstructorsOnly = false;
2609
2610 // If the type we are conversion to is a class type, enumerate its
2611 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002612 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002613 // C++ [over.match.ctor]p1:
2614 // When objects of class type are direct-initialized (8.5), or
2615 // copy-initialized from an expression of the same or a
2616 // derived class type (8.5), overload resolution selects the
2617 // constructor. [...] For copy-initialization, the candidate
2618 // functions are all the converting constructors (12.3.1) of
2619 // that class. The argument list is the expression-list within
2620 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002621 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002622 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002623 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002624 ConstructorsOnly = true;
2625
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002626 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2627 // RequireCompleteType may have returned true due to some invalid decl
2628 // during template instantiation, but ToType may be complete enough now
2629 // to try to recover.
2630 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002631 // We're not going to find any constructors.
2632 } else if (CXXRecordDecl *ToRecordDecl
2633 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002634
2635 Expr **Args = &From;
2636 unsigned NumArgs = 1;
2637 bool ListInitializing = false;
2638 // If we're list-initializing, we pass the individual elements as
2639 // arguments, not the entire list.
2640 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2641 Args = InitList->getInits();
2642 NumArgs = InitList->getNumInits();
2643 ListInitializing = true;
2644 }
2645
Douglas Gregor89ee6822009-02-28 01:32:25 +00002646 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002647 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002648 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002649 NamedDecl *D = *Con;
2650 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2651
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002652 // Find the constructor (which may be a template).
2653 CXXConstructorDecl *Constructor = 0;
2654 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002655 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002656 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002657 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002658 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2659 else
John McCalla0296f72010-03-19 07:35:19 +00002660 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002662 bool Usable = !Constructor->isInvalidDecl();
2663 if (ListInitializing)
2664 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2665 else
2666 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2667 if (Usable) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002668 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002669 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2670 /*ExplicitArgs*/ 0,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002671 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002672 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002673 !ConstructorsOnly &&
2674 !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002675 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002676 // Allow one user-defined conversion when user specifies a
2677 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002678 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002679 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002680 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002681 !ConstructorsOnly && !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002682 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002683 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002684 }
2685 }
2686
Douglas Gregor5ab11652010-04-17 22:01:05 +00002687 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002688 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002689 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2690 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002691 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002692 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002693 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002694 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002695 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2696 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002697 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002698 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002699 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002700 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002701 DeclAccessPair FoundDecl = I.getPair();
2702 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002703 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2704 if (isa<UsingShadowDecl>(D))
2705 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2706
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002707 CXXConversionDecl *Conv;
2708 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002709 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2710 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002711 else
John McCallda4458e2010-03-31 01:36:47 +00002712 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002713
2714 if (AllowExplicit || !Conv->isExplicit()) {
2715 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002716 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2717 ActingContext, From, ToType,
2718 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002719 else
John McCall5c32be02010-08-24 20:38:10 +00002720 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2721 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002722 }
2723 }
2724 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002725 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002726
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002727 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2728
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002729 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002730 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002731 case OR_Success:
2732 // Record the standard conversion we used and the conversion function.
2733 if (CXXConstructorDecl *Constructor
2734 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002735 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2736
John McCall5c32be02010-08-24 20:38:10 +00002737 // C++ [over.ics.user]p1:
2738 // If the user-defined conversion is specified by a
2739 // constructor (12.3.1), the initial standard conversion
2740 // sequence converts the source type to the type required by
2741 // the argument of the constructor.
2742 //
2743 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002744 if (isa<InitListExpr>(From)) {
2745 // Initializer lists don't have conversions as such.
2746 User.Before.setAsIdentityConversion();
2747 } else {
2748 if (Best->Conversions[0].isEllipsis())
2749 User.EllipsisConversion = true;
2750 else {
2751 User.Before = Best->Conversions[0].Standard;
2752 User.EllipsisConversion = false;
2753 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002754 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002755 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002756 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002757 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002758 User.After.setAsIdentityConversion();
2759 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2760 User.After.setAllToTypes(ToType);
2761 return OR_Success;
2762 } else if (CXXConversionDecl *Conversion
2763 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002764 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2765
John McCall5c32be02010-08-24 20:38:10 +00002766 // C++ [over.ics.user]p1:
2767 //
2768 // [...] If the user-defined conversion is specified by a
2769 // conversion function (12.3.2), the initial standard
2770 // conversion sequence converts the source type to the
2771 // implicit object parameter of the conversion function.
2772 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002773 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002774 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002775 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002776 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002777
John McCall5c32be02010-08-24 20:38:10 +00002778 // C++ [over.ics.user]p2:
2779 // The second standard conversion sequence converts the
2780 // result of the user-defined conversion to the target type
2781 // for the sequence. Since an implicit conversion sequence
2782 // is an initialization, the special rules for
2783 // initialization by user-defined conversion apply when
2784 // selecting the best user-defined conversion for a
2785 // user-defined conversion sequence (see 13.3.3 and
2786 // 13.3.3.1).
2787 User.After = Best->FinalConversion;
2788 return OR_Success;
2789 } else {
2790 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002791 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002792 }
2793
John McCall5c32be02010-08-24 20:38:10 +00002794 case OR_No_Viable_Function:
2795 return OR_No_Viable_Function;
2796 case OR_Deleted:
2797 // No conversion here! We're done.
2798 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002799
John McCall5c32be02010-08-24 20:38:10 +00002800 case OR_Ambiguous:
2801 return OR_Ambiguous;
2802 }
2803
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002804 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002805}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002806
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002807bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002808Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002809 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002810 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002811 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002812 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002813 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002814 if (OvResult == OR_Ambiguous)
2815 Diag(From->getSourceRange().getBegin(),
2816 diag::err_typecheck_ambiguous_condition)
2817 << From->getType() << ToType << From->getSourceRange();
2818 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2819 Diag(From->getSourceRange().getBegin(),
2820 diag::err_typecheck_nonviable_condition)
2821 << From->getType() << ToType << From->getSourceRange();
2822 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002823 return false;
John McCall5c32be02010-08-24 20:38:10 +00002824 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002825 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002826}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002827
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002828/// CompareImplicitConversionSequences - Compare two implicit
2829/// conversion sequences to determine whether one is better than the
2830/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002831static ImplicitConversionSequence::CompareKind
2832CompareImplicitConversionSequences(Sema &S,
2833 const ImplicitConversionSequence& ICS1,
2834 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002835{
2836 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2837 // conversion sequences (as defined in 13.3.3.1)
2838 // -- a standard conversion sequence (13.3.3.1.1) is a better
2839 // conversion sequence than a user-defined conversion sequence or
2840 // an ellipsis conversion sequence, and
2841 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2842 // conversion sequence than an ellipsis conversion sequence
2843 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002844 //
John McCall0d1da222010-01-12 00:44:57 +00002845 // C++0x [over.best.ics]p10:
2846 // For the purpose of ranking implicit conversion sequences as
2847 // described in 13.3.3.2, the ambiguous conversion sequence is
2848 // treated as a user-defined sequence that is indistinguishable
2849 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002850 if (ICS1.getKindRank() < ICS2.getKindRank())
2851 return ImplicitConversionSequence::Better;
2852 else if (ICS2.getKindRank() < ICS1.getKindRank())
2853 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002854
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002855 // The following checks require both conversion sequences to be of
2856 // the same kind.
2857 if (ICS1.getKind() != ICS2.getKind())
2858 return ImplicitConversionSequence::Indistinguishable;
2859
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002860 ImplicitConversionSequence::CompareKind Result =
2861 ImplicitConversionSequence::Indistinguishable;
2862
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002863 // Two implicit conversion sequences of the same form are
2864 // indistinguishable conversion sequences unless one of the
2865 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002866 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002867 Result = CompareStandardConversionSequences(S,
2868 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002869 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002870 // User-defined conversion sequence U1 is a better conversion
2871 // sequence than another user-defined conversion sequence U2 if
2872 // they contain the same user-defined conversion function or
2873 // constructor and if the second standard conversion sequence of
2874 // U1 is better than the second standard conversion sequence of
2875 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002876 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002877 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002878 Result = CompareStandardConversionSequences(S,
2879 ICS1.UserDefined.After,
2880 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002881 }
2882
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002883 // List-initialization sequence L1 is a better conversion sequence than
2884 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2885 // for some X and L2 does not.
2886 if (Result == ImplicitConversionSequence::Indistinguishable &&
2887 ICS1.isListInitializationSequence() &&
2888 ICS2.isListInitializationSequence()) {
2889 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2890 }
2891
2892 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002893}
2894
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002895static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2896 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2897 Qualifiers Quals;
2898 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002899 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002901
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002902 return Context.hasSameUnqualifiedType(T1, T2);
2903}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002904
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002905// Per 13.3.3.2p3, compare the given standard conversion sequences to
2906// determine if one is a proper subset of the other.
2907static ImplicitConversionSequence::CompareKind
2908compareStandardConversionSubsets(ASTContext &Context,
2909 const StandardConversionSequence& SCS1,
2910 const StandardConversionSequence& SCS2) {
2911 ImplicitConversionSequence::CompareKind Result
2912 = ImplicitConversionSequence::Indistinguishable;
2913
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002914 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002915 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002916 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2917 return ImplicitConversionSequence::Better;
2918 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2919 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002920
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002921 if (SCS1.Second != SCS2.Second) {
2922 if (SCS1.Second == ICK_Identity)
2923 Result = ImplicitConversionSequence::Better;
2924 else if (SCS2.Second == ICK_Identity)
2925 Result = ImplicitConversionSequence::Worse;
2926 else
2927 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002928 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002929 return ImplicitConversionSequence::Indistinguishable;
2930
2931 if (SCS1.Third == SCS2.Third) {
2932 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2933 : ImplicitConversionSequence::Indistinguishable;
2934 }
2935
2936 if (SCS1.Third == ICK_Identity)
2937 return Result == ImplicitConversionSequence::Worse
2938 ? ImplicitConversionSequence::Indistinguishable
2939 : ImplicitConversionSequence::Better;
2940
2941 if (SCS2.Third == ICK_Identity)
2942 return Result == ImplicitConversionSequence::Better
2943 ? ImplicitConversionSequence::Indistinguishable
2944 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002945
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002946 return ImplicitConversionSequence::Indistinguishable;
2947}
2948
Douglas Gregore696ebb2011-01-26 14:52:12 +00002949/// \brief Determine whether one of the given reference bindings is better
2950/// than the other based on what kind of bindings they are.
2951static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2952 const StandardConversionSequence &SCS2) {
2953 // C++0x [over.ics.rank]p3b4:
2954 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2955 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002957 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002958 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002959 // reference*.
2960 //
2961 // FIXME: Rvalue references. We're going rogue with the above edits,
2962 // because the semantics in the current C++0x working paper (N3225 at the
2963 // time of this writing) break the standard definition of std::forward
2964 // and std::reference_wrapper when dealing with references to functions.
2965 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002966 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2967 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2968 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002969
Douglas Gregore696ebb2011-01-26 14:52:12 +00002970 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2971 SCS2.IsLvalueReference) ||
2972 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2973 !SCS2.IsLvalueReference);
2974}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002975
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002976/// CompareStandardConversionSequences - Compare two standard
2977/// conversion sequences to determine whether one is better than the
2978/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002979static ImplicitConversionSequence::CompareKind
2980CompareStandardConversionSequences(Sema &S,
2981 const StandardConversionSequence& SCS1,
2982 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002983{
2984 // Standard conversion sequence S1 is a better conversion sequence
2985 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2986
2987 // -- S1 is a proper subsequence of S2 (comparing the conversion
2988 // sequences in the canonical form defined by 13.3.3.1.1,
2989 // excluding any Lvalue Transformation; the identity conversion
2990 // sequence is considered to be a subsequence of any
2991 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002992 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002993 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002994 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002995
2996 // -- the rank of S1 is better than the rank of S2 (by the rules
2997 // defined below), or, if not that,
2998 ImplicitConversionRank Rank1 = SCS1.getRank();
2999 ImplicitConversionRank Rank2 = SCS2.getRank();
3000 if (Rank1 < Rank2)
3001 return ImplicitConversionSequence::Better;
3002 else if (Rank2 < Rank1)
3003 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003004
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003005 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3006 // are indistinguishable unless one of the following rules
3007 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003008
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003009 // A conversion that is not a conversion of a pointer, or
3010 // pointer to member, to bool is better than another conversion
3011 // that is such a conversion.
3012 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3013 return SCS2.isPointerConversionToBool()
3014 ? ImplicitConversionSequence::Better
3015 : ImplicitConversionSequence::Worse;
3016
Douglas Gregor5c407d92008-10-23 00:40:37 +00003017 // C++ [over.ics.rank]p4b2:
3018 //
3019 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003020 // conversion of B* to A* is better than conversion of B* to
3021 // void*, and conversion of A* to void* is better than conversion
3022 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003023 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003024 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003025 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003026 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003027 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3028 // Exactly one of the conversion sequences is a conversion to
3029 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003030 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3031 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003032 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3033 // Neither conversion sequence converts to a void pointer; compare
3034 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003035 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003036 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003037 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003038 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3039 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003040 // Both conversion sequences are conversions to void
3041 // pointers. Compare the source types to determine if there's an
3042 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003043 QualType FromType1 = SCS1.getFromType();
3044 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003045
3046 // Adjust the types we're converting from via the array-to-pointer
3047 // conversion, if we need to.
3048 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003049 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003050 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003051 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003052
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003053 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3054 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003055
John McCall5c32be02010-08-24 20:38:10 +00003056 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003057 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003058 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003059 return ImplicitConversionSequence::Worse;
3060
3061 // Objective-C++: If one interface is more specific than the
3062 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003063 const ObjCObjectPointerType* FromObjCPtr1
3064 = FromType1->getAs<ObjCObjectPointerType>();
3065 const ObjCObjectPointerType* FromObjCPtr2
3066 = FromType2->getAs<ObjCObjectPointerType>();
3067 if (FromObjCPtr1 && FromObjCPtr2) {
3068 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3069 FromObjCPtr2);
3070 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3071 FromObjCPtr1);
3072 if (AssignLeft != AssignRight) {
3073 return AssignLeft? ImplicitConversionSequence::Better
3074 : ImplicitConversionSequence::Worse;
3075 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003076 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003077 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003078
3079 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3080 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003081 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003082 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003083 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003084
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003085 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003086 // Check for a better reference binding based on the kind of bindings.
3087 if (isBetterReferenceBindingKind(SCS1, SCS2))
3088 return ImplicitConversionSequence::Better;
3089 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3090 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003091
Sebastian Redlb28b4072009-03-22 23:49:27 +00003092 // C++ [over.ics.rank]p3b4:
3093 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3094 // which the references refer are the same type except for
3095 // top-level cv-qualifiers, and the type to which the reference
3096 // initialized by S2 refers is more cv-qualified than the type
3097 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003098 QualType T1 = SCS1.getToType(2);
3099 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003100 T1 = S.Context.getCanonicalType(T1);
3101 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003102 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003103 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3104 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003105 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003106 // Objective-C++ ARC: If the references refer to objects with different
3107 // lifetimes, prefer bindings that don't change lifetime.
3108 if (SCS1.ObjCLifetimeConversionBinding !=
3109 SCS2.ObjCLifetimeConversionBinding) {
3110 return SCS1.ObjCLifetimeConversionBinding
3111 ? ImplicitConversionSequence::Worse
3112 : ImplicitConversionSequence::Better;
3113 }
3114
Chandler Carruth8e543b32010-12-12 08:17:55 +00003115 // If the type is an array type, promote the element qualifiers to the
3116 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003117 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003118 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003119 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003120 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003121 if (T2.isMoreQualifiedThan(T1))
3122 return ImplicitConversionSequence::Better;
3123 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003124 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003125 }
3126 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003127
Francois Pichet08d2fa02011-09-18 21:37:37 +00003128 // In Microsoft mode, prefer an integral conversion to a
3129 // floating-to-integral conversion if the integral conversion
3130 // is between types of the same size.
3131 // For example:
3132 // void f(float);
3133 // void f(int);
3134 // int main {
3135 // long a;
3136 // f(a);
3137 // }
3138 // Here, MSVC will call f(int) instead of generating a compile error
3139 // as clang will do in standard mode.
3140 if (S.getLangOptions().MicrosoftMode &&
3141 SCS1.Second == ICK_Integral_Conversion &&
3142 SCS2.Second == ICK_Floating_Integral &&
3143 S.Context.getTypeSize(SCS1.getFromType()) ==
3144 S.Context.getTypeSize(SCS1.getToType(2)))
3145 return ImplicitConversionSequence::Better;
3146
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003147 return ImplicitConversionSequence::Indistinguishable;
3148}
3149
3150/// CompareQualificationConversions - Compares two standard conversion
3151/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003152/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3153ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003154CompareQualificationConversions(Sema &S,
3155 const StandardConversionSequence& SCS1,
3156 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003157 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003158 // -- S1 and S2 differ only in their qualification conversion and
3159 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3160 // cv-qualification signature of type T1 is a proper subset of
3161 // the cv-qualification signature of type T2, and S1 is not the
3162 // deprecated string literal array-to-pointer conversion (4.2).
3163 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3164 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3165 return ImplicitConversionSequence::Indistinguishable;
3166
3167 // FIXME: the example in the standard doesn't use a qualification
3168 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003169 QualType T1 = SCS1.getToType(2);
3170 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003171 T1 = S.Context.getCanonicalType(T1);
3172 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003173 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003174 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3175 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003176
3177 // If the types are the same, we won't learn anything by unwrapped
3178 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003179 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003180 return ImplicitConversionSequence::Indistinguishable;
3181
Chandler Carruth607f38e2009-12-29 07:16:59 +00003182 // If the type is an array type, promote the element qualifiers to the type
3183 // for comparison.
3184 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003185 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003186 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003187 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003188
Mike Stump11289f42009-09-09 15:08:12 +00003189 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003190 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003191
3192 // Objective-C++ ARC:
3193 // Prefer qualification conversions not involving a change in lifetime
3194 // to qualification conversions that do not change lifetime.
3195 if (SCS1.QualificationIncludesObjCLifetime !=
3196 SCS2.QualificationIncludesObjCLifetime) {
3197 Result = SCS1.QualificationIncludesObjCLifetime
3198 ? ImplicitConversionSequence::Worse
3199 : ImplicitConversionSequence::Better;
3200 }
3201
John McCall5c32be02010-08-24 20:38:10 +00003202 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003203 // Within each iteration of the loop, we check the qualifiers to
3204 // determine if this still looks like a qualification
3205 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003206 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003207 // until there are no more pointers or pointers-to-members left
3208 // to unwrap. This essentially mimics what
3209 // IsQualificationConversion does, but here we're checking for a
3210 // strict subset of qualifiers.
3211 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3212 // The qualifiers are the same, so this doesn't tell us anything
3213 // about how the sequences rank.
3214 ;
3215 else if (T2.isMoreQualifiedThan(T1)) {
3216 // T1 has fewer qualifiers, so it could be the better sequence.
3217 if (Result == ImplicitConversionSequence::Worse)
3218 // Neither has qualifiers that are a subset of the other's
3219 // qualifiers.
3220 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003221
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003222 Result = ImplicitConversionSequence::Better;
3223 } else if (T1.isMoreQualifiedThan(T2)) {
3224 // T2 has fewer qualifiers, so it could be the better sequence.
3225 if (Result == ImplicitConversionSequence::Better)
3226 // Neither has qualifiers that are a subset of the other's
3227 // qualifiers.
3228 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003229
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003230 Result = ImplicitConversionSequence::Worse;
3231 } else {
3232 // Qualifiers are disjoint.
3233 return ImplicitConversionSequence::Indistinguishable;
3234 }
3235
3236 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003237 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003238 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003239 }
3240
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003241 // Check that the winning standard conversion sequence isn't using
3242 // the deprecated string literal array to pointer conversion.
3243 switch (Result) {
3244 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003245 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003246 Result = ImplicitConversionSequence::Indistinguishable;
3247 break;
3248
3249 case ImplicitConversionSequence::Indistinguishable:
3250 break;
3251
3252 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003253 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003254 Result = ImplicitConversionSequence::Indistinguishable;
3255 break;
3256 }
3257
3258 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003259}
3260
Douglas Gregor5c407d92008-10-23 00:40:37 +00003261/// CompareDerivedToBaseConversions - Compares two standard conversion
3262/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003263/// various kinds of derived-to-base conversions (C++
3264/// [over.ics.rank]p4b3). As part of these checks, we also look at
3265/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003266ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003267CompareDerivedToBaseConversions(Sema &S,
3268 const StandardConversionSequence& SCS1,
3269 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003270 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003271 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003272 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003273 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003274
3275 // Adjust the types we're converting from via the array-to-pointer
3276 // conversion, if we need to.
3277 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003278 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003279 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003280 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003281
3282 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003283 FromType1 = S.Context.getCanonicalType(FromType1);
3284 ToType1 = S.Context.getCanonicalType(ToType1);
3285 FromType2 = S.Context.getCanonicalType(FromType2);
3286 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003287
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003288 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003289 //
3290 // If class B is derived directly or indirectly from class A and
3291 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003292 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003293 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003294 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003295 SCS2.Second == ICK_Pointer_Conversion &&
3296 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3297 FromType1->isPointerType() && FromType2->isPointerType() &&
3298 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003299 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003300 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003301 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003302 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003303 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003304 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003305 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003306 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003307
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003308 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003309 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003310 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003311 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003312 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003313 return ImplicitConversionSequence::Worse;
3314 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003315
3316 // -- conversion of B* to A* is better than conversion of C* to A*,
3317 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003318 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003319 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003320 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003321 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003322 }
3323 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3324 SCS2.Second == ICK_Pointer_Conversion) {
3325 const ObjCObjectPointerType *FromPtr1
3326 = FromType1->getAs<ObjCObjectPointerType>();
3327 const ObjCObjectPointerType *FromPtr2
3328 = FromType2->getAs<ObjCObjectPointerType>();
3329 const ObjCObjectPointerType *ToPtr1
3330 = ToType1->getAs<ObjCObjectPointerType>();
3331 const ObjCObjectPointerType *ToPtr2
3332 = ToType2->getAs<ObjCObjectPointerType>();
3333
3334 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3335 // Apply the same conversion ranking rules for Objective-C pointer types
3336 // that we do for C++ pointers to class types. However, we employ the
3337 // Objective-C pseudo-subtyping relationship used for assignment of
3338 // Objective-C pointer types.
3339 bool FromAssignLeft
3340 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3341 bool FromAssignRight
3342 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3343 bool ToAssignLeft
3344 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3345 bool ToAssignRight
3346 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3347
3348 // A conversion to an a non-id object pointer type or qualified 'id'
3349 // type is better than a conversion to 'id'.
3350 if (ToPtr1->isObjCIdType() &&
3351 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3352 return ImplicitConversionSequence::Worse;
3353 if (ToPtr2->isObjCIdType() &&
3354 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3355 return ImplicitConversionSequence::Better;
3356
3357 // A conversion to a non-id object pointer type is better than a
3358 // conversion to a qualified 'id' type
3359 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3360 return ImplicitConversionSequence::Worse;
3361 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3362 return ImplicitConversionSequence::Better;
3363
3364 // A conversion to an a non-Class object pointer type or qualified 'Class'
3365 // type is better than a conversion to 'Class'.
3366 if (ToPtr1->isObjCClassType() &&
3367 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3368 return ImplicitConversionSequence::Worse;
3369 if (ToPtr2->isObjCClassType() &&
3370 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3371 return ImplicitConversionSequence::Better;
3372
3373 // A conversion to a non-Class object pointer type is better than a
3374 // conversion to a qualified 'Class' type.
3375 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3376 return ImplicitConversionSequence::Worse;
3377 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3378 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003379
Douglas Gregor058d3de2011-01-31 18:51:41 +00003380 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3381 if (S.Context.hasSameType(FromType1, FromType2) &&
3382 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3383 (ToAssignLeft != ToAssignRight))
3384 return ToAssignLeft? ImplicitConversionSequence::Worse
3385 : ImplicitConversionSequence::Better;
3386
3387 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3388 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3389 (FromAssignLeft != FromAssignRight))
3390 return FromAssignLeft? ImplicitConversionSequence::Better
3391 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003392 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003393 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003394
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003395 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003396 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3397 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3398 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003399 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003400 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003401 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003402 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003404 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003405 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003406 ToType2->getAs<MemberPointerType>();
3407 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3408 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3409 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3410 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3411 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3412 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3413 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3414 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003415 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003416 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003417 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003418 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003419 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003420 return ImplicitConversionSequence::Better;
3421 }
3422 // conversion of B::* to C::* is better than conversion of A::* to C::*
3423 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003424 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003425 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003426 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003427 return ImplicitConversionSequence::Worse;
3428 }
3429 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003430
Douglas Gregor5ab11652010-04-17 22:01:05 +00003431 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003432 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003433 // -- binding of an expression of type C to a reference of type
3434 // B& is better than binding an expression of type C to a
3435 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003436 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3437 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3438 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003439 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003440 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003441 return ImplicitConversionSequence::Worse;
3442 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003443
Douglas Gregor2fe98832008-11-03 19:09:14 +00003444 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003445 // -- binding of an expression of type B to a reference of type
3446 // A& is better than binding an expression of type C to a
3447 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003448 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3449 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3450 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003451 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003452 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003453 return ImplicitConversionSequence::Worse;
3454 }
3455 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003456
Douglas Gregor5c407d92008-10-23 00:40:37 +00003457 return ImplicitConversionSequence::Indistinguishable;
3458}
3459
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003460/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3461/// determine whether they are reference-related,
3462/// reference-compatible, reference-compatible with added
3463/// qualification, or incompatible, for use in C++ initialization by
3464/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3465/// type, and the first type (T1) is the pointee type of the reference
3466/// type being initialized.
3467Sema::ReferenceCompareResult
3468Sema::CompareReferenceRelationship(SourceLocation Loc,
3469 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003470 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003471 bool &ObjCConversion,
3472 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003473 assert(!OrigT1->isReferenceType() &&
3474 "T1 must be the pointee type of the reference type");
3475 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3476
3477 QualType T1 = Context.getCanonicalType(OrigT1);
3478 QualType T2 = Context.getCanonicalType(OrigT2);
3479 Qualifiers T1Quals, T2Quals;
3480 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3481 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3482
3483 // C++ [dcl.init.ref]p4:
3484 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3485 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3486 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003487 DerivedToBase = false;
3488 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003489 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003490 if (UnqualT1 == UnqualT2) {
3491 // Nothing to do.
3492 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003493 IsDerivedFrom(UnqualT2, UnqualT1))
3494 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003495 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3496 UnqualT2->isObjCObjectOrInterfaceType() &&
3497 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3498 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003499 else
3500 return Ref_Incompatible;
3501
3502 // At this point, we know that T1 and T2 are reference-related (at
3503 // least).
3504
3505 // If the type is an array type, promote the element qualifiers to the type
3506 // for comparison.
3507 if (isa<ArrayType>(T1) && T1Quals)
3508 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3509 if (isa<ArrayType>(T2) && T2Quals)
3510 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3511
3512 // C++ [dcl.init.ref]p4:
3513 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3514 // reference-related to T2 and cv1 is the same cv-qualification
3515 // as, or greater cv-qualification than, cv2. For purposes of
3516 // overload resolution, cases for which cv1 is greater
3517 // cv-qualification than cv2 are identified as
3518 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003519 //
3520 // Note that we also require equivalence of Objective-C GC and address-space
3521 // qualifiers when performing these computations, so that e.g., an int in
3522 // address space 1 is not reference-compatible with an int in address
3523 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003524 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3525 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3526 T1Quals.removeObjCLifetime();
3527 T2Quals.removeObjCLifetime();
3528 ObjCLifetimeConversion = true;
3529 }
3530
Douglas Gregord517d552011-04-28 17:56:11 +00003531 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003532 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003533 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003534 return Ref_Compatible_With_Added_Qualification;
3535 else
3536 return Ref_Related;
3537}
3538
Douglas Gregor836a7e82010-08-11 02:15:33 +00003539/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003540/// with DeclType. Return true if something definite is found.
3541static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003542FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3543 QualType DeclType, SourceLocation DeclLoc,
3544 Expr *Init, QualType T2, bool AllowRvalues,
3545 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003546 assert(T2->isRecordType() && "Can only find conversions of record types.");
3547 CXXRecordDecl *T2RecordDecl
3548 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3549
3550 OverloadCandidateSet CandidateSet(DeclLoc);
3551 const UnresolvedSetImpl *Conversions
3552 = T2RecordDecl->getVisibleConversionFunctions();
3553 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3554 E = Conversions->end(); I != E; ++I) {
3555 NamedDecl *D = *I;
3556 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3557 if (isa<UsingShadowDecl>(D))
3558 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3559
3560 FunctionTemplateDecl *ConvTemplate
3561 = dyn_cast<FunctionTemplateDecl>(D);
3562 CXXConversionDecl *Conv;
3563 if (ConvTemplate)
3564 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3565 else
3566 Conv = cast<CXXConversionDecl>(D);
3567
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003569 // explicit conversions, skip it.
3570 if (!AllowExplicit && Conv->isExplicit())
3571 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572
Douglas Gregor836a7e82010-08-11 02:15:33 +00003573 if (AllowRvalues) {
3574 bool DerivedToBase = false;
3575 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003576 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003577
3578 // If we are initializing an rvalue reference, don't permit conversion
3579 // functions that return lvalues.
3580 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3581 const ReferenceType *RefType
3582 = Conv->getConversionType()->getAs<LValueReferenceType>();
3583 if (RefType && !RefType->getPointeeType()->isFunctionType())
3584 continue;
3585 }
3586
Douglas Gregor836a7e82010-08-11 02:15:33 +00003587 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003588 S.CompareReferenceRelationship(
3589 DeclLoc,
3590 Conv->getConversionType().getNonReferenceType()
3591 .getUnqualifiedType(),
3592 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003593 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003594 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003595 continue;
3596 } else {
3597 // If the conversion function doesn't return a reference type,
3598 // it can't be considered for this conversion. An rvalue reference
3599 // is only acceptable if its referencee is a function type.
3600
3601 const ReferenceType *RefType =
3602 Conv->getConversionType()->getAs<ReferenceType>();
3603 if (!RefType ||
3604 (!RefType->isLValueReferenceType() &&
3605 !RefType->getPointeeType()->isFunctionType()))
3606 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003607 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Douglas Gregor836a7e82010-08-11 02:15:33 +00003609 if (ConvTemplate)
3610 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003611 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003612 else
3613 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003614 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003615 }
3616
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003617 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3618
Sebastian Redld92badf2010-06-30 18:13:39 +00003619 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003620 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003621 case OR_Success:
3622 // C++ [over.ics.ref]p1:
3623 //
3624 // [...] If the parameter binds directly to the result of
3625 // applying a conversion function to the argument
3626 // expression, the implicit conversion sequence is a
3627 // user-defined conversion sequence (13.3.3.1.2), with the
3628 // second standard conversion sequence either an identity
3629 // conversion or, if the conversion function returns an
3630 // entity of a type that is a derived class of the parameter
3631 // type, a derived-to-base Conversion.
3632 if (!Best->FinalConversion.DirectBinding)
3633 return false;
3634
Chandler Carruth30141632011-02-25 19:41:05 +00003635 if (Best->Function)
3636 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003637 ICS.setUserDefined();
3638 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3639 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003640 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003641 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003642 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003643 ICS.UserDefined.EllipsisConversion = false;
3644 assert(ICS.UserDefined.After.ReferenceBinding &&
3645 ICS.UserDefined.After.DirectBinding &&
3646 "Expected a direct reference binding!");
3647 return true;
3648
3649 case OR_Ambiguous:
3650 ICS.setAmbiguous();
3651 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3652 Cand != CandidateSet.end(); ++Cand)
3653 if (Cand->Viable)
3654 ICS.Ambiguous.addConversion(Cand->Function);
3655 return true;
3656
3657 case OR_No_Viable_Function:
3658 case OR_Deleted:
3659 // There was no suitable conversion, or we found a deleted
3660 // conversion; continue with other checks.
3661 return false;
3662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663
Eric Christopheraba9fb22010-06-30 18:36:32 +00003664 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003665}
3666
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003667/// \brief Compute an implicit conversion sequence for reference
3668/// initialization.
3669static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003670TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003671 SourceLocation DeclLoc,
3672 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003673 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003674 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3675
3676 // Most paths end in a failed conversion.
3677 ImplicitConversionSequence ICS;
3678 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3679
3680 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3681 QualType T2 = Init->getType();
3682
3683 // If the initializer is the address of an overloaded function, try
3684 // to resolve the overloaded function. If all goes well, T2 is the
3685 // type of the resulting function.
3686 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3687 DeclAccessPair Found;
3688 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3689 false, Found))
3690 T2 = Fn->getType();
3691 }
3692
3693 // Compute some basic properties of the types and the initializer.
3694 bool isRValRef = DeclType->isRValueReferenceType();
3695 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003696 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003697 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003698 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003699 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003700 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003701 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003702
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003703
Sebastian Redld92badf2010-06-30 18:13:39 +00003704 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003705 // A reference to type "cv1 T1" is initialized by an expression
3706 // of type "cv2 T2" as follows:
3707
Sebastian Redld92badf2010-06-30 18:13:39 +00003708 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003709 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003710 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3711 // reference-compatible with "cv2 T2," or
3712 //
3713 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3714 if (InitCategory.isLValue() &&
3715 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003716 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003717 // When a parameter of reference type binds directly (8.5.3)
3718 // to an argument expression, the implicit conversion sequence
3719 // is the identity conversion, unless the argument expression
3720 // has a type that is a derived class of the parameter type,
3721 // in which case the implicit conversion sequence is a
3722 // derived-to-base Conversion (13.3.3.1).
3723 ICS.setStandard();
3724 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003725 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3726 : ObjCConversion? ICK_Compatible_Conversion
3727 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003728 ICS.Standard.Third = ICK_Identity;
3729 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3730 ICS.Standard.setToType(0, T2);
3731 ICS.Standard.setToType(1, T1);
3732 ICS.Standard.setToType(2, T1);
3733 ICS.Standard.ReferenceBinding = true;
3734 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003735 ICS.Standard.IsLvalueReference = !isRValRef;
3736 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3737 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003738 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003739 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003740 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003741
Sebastian Redld92badf2010-06-30 18:13:39 +00003742 // Nothing more to do: the inaccessibility/ambiguity check for
3743 // derived-to-base conversions is suppressed when we're
3744 // computing the implicit conversion sequence (C++
3745 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003746 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003747 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003748
Sebastian Redld92badf2010-06-30 18:13:39 +00003749 // -- has a class type (i.e., T2 is a class type), where T1 is
3750 // not reference-related to T2, and can be implicitly
3751 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3752 // is reference-compatible with "cv3 T3" 92) (this
3753 // conversion is selected by enumerating the applicable
3754 // conversion functions (13.3.1.6) and choosing the best
3755 // one through overload resolution (13.3)),
3756 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003758 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003759 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3760 Init, T2, /*AllowRvalues=*/false,
3761 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003762 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003763 }
3764 }
3765
Sebastian Redld92badf2010-06-30 18:13:39 +00003766 // -- Otherwise, the reference shall be an lvalue reference to a
3767 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003768 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003770 // We actually handle one oddity of C++ [over.ics.ref] at this
3771 // point, which is that, due to p2 (which short-circuits reference
3772 // binding by only attempting a simple conversion for non-direct
3773 // bindings) and p3's strange wording, we allow a const volatile
3774 // reference to bind to an rvalue. Hence the check for the presence
3775 // of "const" rather than checking for "const" being the only
3776 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003777 // This is also the point where rvalue references and lvalue inits no longer
3778 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003779 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003780 return ICS;
3781
Douglas Gregorf143cd52011-01-24 16:14:37 +00003782 // -- If the initializer expression
3783 //
3784 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003785 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003786 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3787 (InitCategory.isXValue() ||
3788 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3789 (InitCategory.isLValue() && T2->isFunctionType()))) {
3790 ICS.setStandard();
3791 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003792 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003793 : ObjCConversion? ICK_Compatible_Conversion
3794 : ICK_Identity;
3795 ICS.Standard.Third = ICK_Identity;
3796 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3797 ICS.Standard.setToType(0, T2);
3798 ICS.Standard.setToType(1, T1);
3799 ICS.Standard.setToType(2, T1);
3800 ICS.Standard.ReferenceBinding = true;
3801 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3802 // binding unless we're binding to a class prvalue.
3803 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3804 // allow the use of rvalue references in C++98/03 for the benefit of
3805 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003806 ICS.Standard.DirectBinding =
3807 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003808 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003809 ICS.Standard.IsLvalueReference = !isRValRef;
3810 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003811 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003812 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003813 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003814 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003815 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003817
Douglas Gregorf143cd52011-01-24 16:14:37 +00003818 // -- has a class type (i.e., T2 is a class type), where T1 is not
3819 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820 // an xvalue, class prvalue, or function lvalue of type
3821 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003822 // "cv3 T3",
3823 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003825 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003826 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003827 // class subobject).
3828 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003829 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003830 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3831 Init, T2, /*AllowRvalues=*/true,
3832 AllowExplicit)) {
3833 // In the second case, if the reference is an rvalue reference
3834 // and the second standard conversion sequence of the
3835 // user-defined conversion sequence includes an lvalue-to-rvalue
3836 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003837 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003838 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3839 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3840
Douglas Gregor95273c32011-01-21 16:36:05 +00003841 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003842 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003843
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003844 // -- Otherwise, a temporary of type "cv1 T1" is created and
3845 // initialized from the initializer expression using the
3846 // rules for a non-reference copy initialization (8.5). The
3847 // reference is then bound to the temporary. If T1 is
3848 // reference-related to T2, cv1 must be the same
3849 // cv-qualification as, or greater cv-qualification than,
3850 // cv2; otherwise, the program is ill-formed.
3851 if (RefRelationship == Sema::Ref_Related) {
3852 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3853 // we would be reference-compatible or reference-compatible with
3854 // added qualification. But that wasn't the case, so the reference
3855 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003856 //
3857 // Note that we only want to check address spaces and cvr-qualifiers here.
3858 // ObjC GC and lifetime qualifiers aren't important.
3859 Qualifiers T1Quals = T1.getQualifiers();
3860 Qualifiers T2Quals = T2.getQualifiers();
3861 T1Quals.removeObjCGCAttr();
3862 T1Quals.removeObjCLifetime();
3863 T2Quals.removeObjCGCAttr();
3864 T2Quals.removeObjCLifetime();
3865 if (!T1Quals.compatiblyIncludes(T2Quals))
3866 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003867 }
3868
3869 // If at least one of the types is a class type, the types are not
3870 // related, and we aren't allowed any user conversions, the
3871 // reference binding fails. This case is important for breaking
3872 // recursion, since TryImplicitConversion below will attempt to
3873 // create a temporary through the use of a copy constructor.
3874 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3875 (T1->isRecordType() || T2->isRecordType()))
3876 return ICS;
3877
Douglas Gregorcba72b12011-01-21 05:18:22 +00003878 // If T1 is reference-related to T2 and the reference is an rvalue
3879 // reference, the initializer expression shall not be an lvalue.
3880 if (RefRelationship >= Sema::Ref_Related &&
3881 isRValRef && Init->Classify(S.Context).isLValue())
3882 return ICS;
3883
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003884 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003885 // When a parameter of reference type is not bound directly to
3886 // an argument expression, the conversion sequence is the one
3887 // required to convert the argument expression to the
3888 // underlying type of the reference according to
3889 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3890 // to copy-initializing a temporary of the underlying type with
3891 // the argument expression. Any difference in top-level
3892 // cv-qualification is subsumed by the initialization itself
3893 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003894 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3895 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003896 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003897 /*CStyle=*/false,
3898 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003899
3900 // Of course, that's still a reference binding.
3901 if (ICS.isStandard()) {
3902 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003903 ICS.Standard.IsLvalueReference = !isRValRef;
3904 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3905 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003906 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003907 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003908 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003909 // Don't allow rvalue references to bind to lvalues.
3910 if (DeclType->isRValueReferenceType()) {
3911 if (const ReferenceType *RefType
3912 = ICS.UserDefined.ConversionFunction->getResultType()
3913 ->getAs<LValueReferenceType>()) {
3914 if (!RefType->getPointeeType()->isFunctionType()) {
3915 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3916 DeclType);
3917 return ICS;
3918 }
3919 }
3920 }
3921
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003922 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003923 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3924 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3925 ICS.UserDefined.After.BindsToRvalue = true;
3926 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3927 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003928 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003929
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003930 return ICS;
3931}
3932
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003933static ImplicitConversionSequence
3934TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3935 bool SuppressUserConversions,
3936 bool InOverloadResolution,
3937 bool AllowObjCWritebackConversion);
3938
3939/// TryListConversion - Try to copy-initialize a value of type ToType from the
3940/// initializer list From.
3941static ImplicitConversionSequence
3942TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3943 bool SuppressUserConversions,
3944 bool InOverloadResolution,
3945 bool AllowObjCWritebackConversion) {
3946 // C++11 [over.ics.list]p1:
3947 // When an argument is an initializer list, it is not an expression and
3948 // special rules apply for converting it to a parameter type.
3949
3950 ImplicitConversionSequence Result;
3951 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003952 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003953
3954 // C++11 [over.ics.list]p2:
3955 // If the parameter type is std::initializer_list<X> or "array of X" and
3956 // all the elements can be implicitly converted to X, the implicit
3957 // conversion sequence is the worst conversion necessary to convert an
3958 // element of the list to X.
3959 // FIXME: Recognize std::initializer_list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003960 // FIXME: Implement arrays.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003961 if (ToType->isArrayType())
3962 return Result;
3963
3964 // C++11 [over.ics.list]p3:
3965 // Otherwise, if the parameter is a non-aggregate class X and overload
3966 // resolution chooses a single best constructor [...] the implicit
3967 // conversion sequence is a user-defined conversion sequence. If multiple
3968 // constructors are viable but none is better than the others, the
3969 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003970 if (ToType->isRecordType() && !ToType->isAggregateType()) {
3971 // This function can deal with initializer lists.
3972 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
3973 /*AllowExplicit=*/false,
3974 InOverloadResolution, /*CStyle=*/false,
3975 AllowObjCWritebackConversion);
3976 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003977 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003978 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003979
3980 // C++11 [over.ics.list]p4:
3981 // Otherwise, if the parameter has an aggregate type which can be
3982 // initialized from the initializer list [...] the implicit conversion
3983 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003984 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003985 // Type is an aggregate, argument is an init list. At this point it comes
3986 // down to checking whether the initialization works.
3987 // FIXME: Find out whether this parameter is consumed or not.
3988 InitializedEntity Entity =
3989 InitializedEntity::InitializeParameter(S.Context, ToType,
3990 /*Consumed=*/false);
3991 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3992 Result.setUserDefined();
3993 Result.UserDefined.Before.setAsIdentityConversion();
3994 // Initializer lists don't have a type.
3995 Result.UserDefined.Before.setFromType(QualType());
3996 Result.UserDefined.Before.setAllToTypes(QualType());
3997
3998 Result.UserDefined.After.setAsIdentityConversion();
3999 Result.UserDefined.After.setFromType(ToType);
4000 Result.UserDefined.After.setAllToTypes(ToType);
4001 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004002 return Result;
4003 }
4004
4005 // C++11 [over.ics.list]p5:
4006 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004007 if (ToType->isReferenceType()) {
4008 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4009 // mention initializer lists in any way. So we go by what list-
4010 // initialization would do and try to extrapolate from that.
4011
4012 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4013
4014 // If the initializer list has a single element that is reference-related
4015 // to the parameter type, we initialize the reference from that.
4016 if (From->getNumInits() == 1) {
4017 Expr *Init = From->getInit(0);
4018
4019 QualType T2 = Init->getType();
4020
4021 // If the initializer is the address of an overloaded function, try
4022 // to resolve the overloaded function. If all goes well, T2 is the
4023 // type of the resulting function.
4024 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4025 DeclAccessPair Found;
4026 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4027 Init, ToType, false, Found))
4028 T2 = Fn->getType();
4029 }
4030
4031 // Compute some basic properties of the types and the initializer.
4032 bool dummy1 = false;
4033 bool dummy2 = false;
4034 bool dummy3 = false;
4035 Sema::ReferenceCompareResult RefRelationship
4036 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4037 dummy2, dummy3);
4038
4039 if (RefRelationship >= Sema::Ref_Related)
4040 return TryReferenceInit(S, Init, ToType,
4041 /*FIXME:*/From->getLocStart(),
4042 SuppressUserConversions,
4043 /*AllowExplicit=*/false);
4044 }
4045
4046 // Otherwise, we bind the reference to a temporary created from the
4047 // initializer list.
4048 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4049 InOverloadResolution,
4050 AllowObjCWritebackConversion);
4051 if (Result.isFailure())
4052 return Result;
4053 assert(!Result.isEllipsis() &&
4054 "Sub-initialization cannot result in ellipsis conversion.");
4055
4056 // Can we even bind to a temporary?
4057 if (ToType->isRValueReferenceType() ||
4058 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4059 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4060 Result.UserDefined.After;
4061 SCS.ReferenceBinding = true;
4062 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4063 SCS.BindsToRvalue = true;
4064 SCS.BindsToFunctionLvalue = false;
4065 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4066 SCS.ObjCLifetimeConversionBinding = false;
4067 } else
4068 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4069 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004070 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004071 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004072
4073 // C++11 [over.ics.list]p6:
4074 // Otherwise, if the parameter type is not a class:
4075 if (!ToType->isRecordType()) {
4076 // - if the initializer list has one element, the implicit conversion
4077 // sequence is the one required to convert the element to the
4078 // parameter type.
4079 // FIXME: Catch narrowing here?
4080 unsigned NumInits = From->getNumInits();
4081 if (NumInits == 1)
4082 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4083 SuppressUserConversions,
4084 InOverloadResolution,
4085 AllowObjCWritebackConversion);
4086 // - if the initializer list has no elements, the implicit conversion
4087 // sequence is the identity conversion.
4088 else if (NumInits == 0) {
4089 Result.setStandard();
4090 Result.Standard.setAsIdentityConversion();
4091 }
4092 return Result;
4093 }
4094
4095 // C++11 [over.ics.list]p7:
4096 // In all cases other than those enumerated above, no conversion is possible
4097 return Result;
4098}
4099
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004100/// TryCopyInitialization - Try to copy-initialize a value of type
4101/// ToType from the expression From. Return the implicit conversion
4102/// sequence required to pass this argument, which may be a bad
4103/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004104/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004105/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004106static ImplicitConversionSequence
4107TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004109 bool InOverloadResolution,
4110 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004111 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4112 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4113 InOverloadResolution,AllowObjCWritebackConversion);
4114
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004115 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004116 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004117 /*FIXME:*/From->getLocStart(),
4118 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004119 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004120
John McCall5c32be02010-08-24 20:38:10 +00004121 return TryImplicitConversion(S, From, ToType,
4122 SuppressUserConversions,
4123 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004124 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004125 /*CStyle=*/false,
4126 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004127}
4128
Anna Zaks1b068122011-07-28 19:46:48 +00004129static bool TryCopyInitialization(const CanQualType FromQTy,
4130 const CanQualType ToQTy,
4131 Sema &S,
4132 SourceLocation Loc,
4133 ExprValueKind FromVK) {
4134 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4135 ImplicitConversionSequence ICS =
4136 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4137
4138 return !ICS.isBad();
4139}
4140
Douglas Gregor436424c2008-11-18 23:14:02 +00004141/// TryObjectArgumentInitialization - Try to initialize the object
4142/// parameter of the given member function (@c Method) from the
4143/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004144static ImplicitConversionSequence
4145TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004146 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004147 CXXMethodDecl *Method,
4148 CXXRecordDecl *ActingContext) {
4149 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004150 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4151 // const volatile object.
4152 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4153 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004154 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004155
4156 // Set up the conversion sequence as a "bad" conversion, to allow us
4157 // to exit early.
4158 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004159
4160 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004161 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004162 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004163 FromType = PT->getPointeeType();
4164
Douglas Gregor02824322011-01-26 19:30:28 +00004165 // When we had a pointer, it's implicitly dereferenced, so we
4166 // better have an lvalue.
4167 assert(FromClassification.isLValue());
4168 }
4169
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004170 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004171
Douglas Gregor02824322011-01-26 19:30:28 +00004172 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004174 // parameter is
4175 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004176 // - "lvalue reference to cv X" for functions declared without a
4177 // ref-qualifier or with the & ref-qualifier
4178 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004179 // ref-qualifier
4180 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004181 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004182 // cv-qualification on the member function declaration.
4183 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004185 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004186 // (C++ [over.match.funcs]p5). We perform a simplified version of
4187 // reference binding here, that allows class rvalues to bind to
4188 // non-constant references.
4189
Douglas Gregor02824322011-01-26 19:30:28 +00004190 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004191 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004193 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004194 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004195 ICS.setBad(BadConversionSequence::bad_qualifiers,
4196 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004197 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004198 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004199
4200 // Check that we have either the same type or a derived type. It
4201 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004202 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004203 ImplicitConversionKind SecondKind;
4204 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4205 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004206 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004207 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004208 else {
John McCall65eb8792010-02-25 01:37:24 +00004209 ICS.setBad(BadConversionSequence::unrelated_class,
4210 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004211 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004212 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004213
Douglas Gregor02824322011-01-26 19:30:28 +00004214 // Check the ref-qualifier.
4215 switch (Method->getRefQualifier()) {
4216 case RQ_None:
4217 // Do nothing; we don't care about lvalueness or rvalueness.
4218 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004219
Douglas Gregor02824322011-01-26 19:30:28 +00004220 case RQ_LValue:
4221 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4222 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004224 ImplicitParamType);
4225 return ICS;
4226 }
4227 break;
4228
4229 case RQ_RValue:
4230 if (!FromClassification.isRValue()) {
4231 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004233 ImplicitParamType);
4234 return ICS;
4235 }
4236 break;
4237 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004238
Douglas Gregor436424c2008-11-18 23:14:02 +00004239 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004240 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004241 ICS.Standard.setAsIdentityConversion();
4242 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004243 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004244 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004245 ICS.Standard.ReferenceBinding = true;
4246 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004248 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004249 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4250 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4251 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004252 return ICS;
4253}
4254
4255/// PerformObjectArgumentInitialization - Perform initialization of
4256/// the implicit object parameter for the given Method with the given
4257/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004258ExprResult
4259Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004260 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004261 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004262 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004263 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004264 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004265 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004266
Douglas Gregor02824322011-01-26 19:30:28 +00004267 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004268 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004269 FromRecordType = PT->getPointeeType();
4270 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004271 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004272 } else {
4273 FromRecordType = From->getType();
4274 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004275 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004276 }
4277
John McCall6e9f8f62009-12-03 04:06:58 +00004278 // Note that we always use the true parent context when performing
4279 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004280 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004281 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4282 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004283 if (ICS.isBad()) {
4284 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4285 Qualifiers FromQs = FromRecordType.getQualifiers();
4286 Qualifiers ToQs = DestType.getQualifiers();
4287 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4288 if (CVR) {
4289 Diag(From->getSourceRange().getBegin(),
4290 diag::err_member_function_call_bad_cvr)
4291 << Method->getDeclName() << FromRecordType << (CVR - 1)
4292 << From->getSourceRange();
4293 Diag(Method->getLocation(), diag::note_previous_decl)
4294 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004295 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004296 }
4297 }
4298
Douglas Gregor436424c2008-11-18 23:14:02 +00004299 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004300 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004301 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004302 }
Mike Stump11289f42009-09-09 15:08:12 +00004303
John Wiegley01296292011-04-08 18:41:53 +00004304 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4305 ExprResult FromRes =
4306 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4307 if (FromRes.isInvalid())
4308 return ExprError();
4309 From = FromRes.take();
4310 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004311
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004312 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004313 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004314 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004315 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004316}
4317
Douglas Gregor5fb53972009-01-14 15:45:31 +00004318/// TryContextuallyConvertToBool - Attempt to contextually convert the
4319/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004320static ImplicitConversionSequence
4321TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004322 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004323 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004324 // FIXME: Are these flags correct?
4325 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004326 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004327 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004328 /*CStyle=*/false,
4329 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004330}
4331
4332/// PerformContextuallyConvertToBool - Perform a contextual conversion
4333/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004334ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004335 if (checkPlaceholderForOverload(*this, From))
4336 return ExprError();
4337
John McCall5c32be02010-08-24 20:38:10 +00004338 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004339 if (!ICS.isBad())
4340 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341
Fariborz Jahanian76197412009-11-18 18:26:29 +00004342 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004343 return Diag(From->getSourceRange().getBegin(),
4344 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004345 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004346 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004347}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348
John McCallfec112d2011-09-09 06:11:02 +00004349/// dropPointerConversions - If the given standard conversion sequence
4350/// involves any pointer conversions, remove them. This may change
4351/// the result type of the conversion sequence.
4352static void dropPointerConversion(StandardConversionSequence &SCS) {
4353 if (SCS.Second == ICK_Pointer_Conversion) {
4354 SCS.Second = ICK_Identity;
4355 SCS.Third = ICK_Identity;
4356 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4357 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004358}
John McCall5c32be02010-08-24 20:38:10 +00004359
John McCallfec112d2011-09-09 06:11:02 +00004360/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4361/// convert the expression From to an Objective-C pointer type.
4362static ImplicitConversionSequence
4363TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4364 // Do an implicit conversion to 'id'.
4365 QualType Ty = S.Context.getObjCIdType();
4366 ImplicitConversionSequence ICS
4367 = TryImplicitConversion(S, From, Ty,
4368 // FIXME: Are these flags correct?
4369 /*SuppressUserConversions=*/false,
4370 /*AllowExplicit=*/true,
4371 /*InOverloadResolution=*/false,
4372 /*CStyle=*/false,
4373 /*AllowObjCWritebackConversion=*/false);
4374
4375 // Strip off any final conversions to 'id'.
4376 switch (ICS.getKind()) {
4377 case ImplicitConversionSequence::BadConversion:
4378 case ImplicitConversionSequence::AmbiguousConversion:
4379 case ImplicitConversionSequence::EllipsisConversion:
4380 break;
4381
4382 case ImplicitConversionSequence::UserDefinedConversion:
4383 dropPointerConversion(ICS.UserDefined.After);
4384 break;
4385
4386 case ImplicitConversionSequence::StandardConversion:
4387 dropPointerConversion(ICS.Standard);
4388 break;
4389 }
4390
4391 return ICS;
4392}
4393
4394/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4395/// conversion of the expression From to an Objective-C pointer type.
4396ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004397 if (checkPlaceholderForOverload(*this, From))
4398 return ExprError();
4399
John McCall8b07ec22010-05-15 11:32:37 +00004400 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004401 ImplicitConversionSequence ICS =
4402 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004403 if (!ICS.isBad())
4404 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004405 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004406}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004407
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004408/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004409/// enumeration type.
4410///
4411/// This routine will attempt to convert an expression of class type to an
4412/// integral or enumeration type, if that class type only has a single
4413/// conversion to an integral or enumeration type.
4414///
Douglas Gregor4799d032010-06-30 00:20:43 +00004415/// \param Loc The source location of the construct that requires the
4416/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004417///
Douglas Gregor4799d032010-06-30 00:20:43 +00004418/// \param FromE The expression we're converting from.
4419///
4420/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4421/// have integral or enumeration type.
4422///
4423/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4424/// incomplete class type.
4425///
4426/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4427/// explicit conversion function (because no implicit conversion functions
4428/// were available). This is a recovery mode.
4429///
4430/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4431/// showing which conversion was picked.
4432///
4433/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4434/// conversion function that could convert to integral or enumeration type.
4435///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004437/// usable conversion function.
4438///
4439/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4440/// function, which may be an extension in this case.
4441///
4442/// \returns The expression, converted to an integral or enumeration type if
4443/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444ExprResult
John McCallb268a282010-08-23 23:25:46 +00004445Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004446 const PartialDiagnostic &NotIntDiag,
4447 const PartialDiagnostic &IncompleteDiag,
4448 const PartialDiagnostic &ExplicitConvDiag,
4449 const PartialDiagnostic &ExplicitConvNote,
4450 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004451 const PartialDiagnostic &AmbigNote,
4452 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004453 // We can't perform any more checking for type-dependent expressions.
4454 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004455 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004456
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004457 // If the expression already has integral or enumeration type, we're golden.
4458 QualType T = From->getType();
4459 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004460 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004461
4462 // FIXME: Check for missing '()' if T is a function type?
4463
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464 // 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 +00004465 // expression of integral or enumeration type.
4466 const RecordType *RecordTy = T->getAs<RecordType>();
4467 if (!RecordTy || !getLangOptions().CPlusPlus) {
4468 Diag(Loc, NotIntDiag)
4469 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004470 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004471 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004472
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004473 // We must have a complete class type.
4474 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004475 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004476
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004477 // Look for a conversion to an integral or enumeration type.
4478 UnresolvedSet<4> ViableConversions;
4479 UnresolvedSet<4> ExplicitConversions;
4480 const UnresolvedSetImpl *Conversions
4481 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004482
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004483 bool HadMultipleCandidates = (Conversions->size() > 1);
4484
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004485 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004486 E = Conversions->end();
4487 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004488 ++I) {
4489 if (CXXConversionDecl *Conversion
4490 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4491 if (Conversion->getConversionType().getNonReferenceType()
4492 ->isIntegralOrEnumerationType()) {
4493 if (Conversion->isExplicit())
4494 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4495 else
4496 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4497 }
4498 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004500 switch (ViableConversions.size()) {
4501 case 0:
4502 if (ExplicitConversions.size() == 1) {
4503 DeclAccessPair Found = ExplicitConversions[0];
4504 CXXConversionDecl *Conversion
4505 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004507 // The user probably meant to invoke the given explicit
4508 // conversion; use it.
4509 QualType ConvTy
4510 = Conversion->getConversionType().getNonReferenceType();
4511 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004512 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004514 Diag(Loc, ExplicitConvDiag)
4515 << T << ConvTy
4516 << FixItHint::CreateInsertion(From->getLocStart(),
4517 "static_cast<" + TypeStr + ">(")
4518 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4519 ")");
4520 Diag(Conversion->getLocation(), ExplicitConvNote)
4521 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
4523 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004524 // explicit conversion function.
4525 if (isSFINAEContext())
4526 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004528 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004529 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4530 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004531 if (Result.isInvalid())
4532 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004533 // Record usage of conversion in an implicit cast.
4534 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4535 CK_UserDefinedConversion,
4536 Result.get(), 0,
4537 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004539
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004540 // We'll complain below about a non-integral condition type.
4541 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004542
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004543 case 1: {
4544 // Apply this conversion.
4545 DeclAccessPair Found = ViableConversions[0];
4546 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004547
Douglas Gregor4799d032010-06-30 00:20:43 +00004548 CXXConversionDecl *Conversion
4549 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4550 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004551 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004552 if (ConvDiag.getDiagID()) {
4553 if (isSFINAEContext())
4554 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004555
Douglas Gregor4799d032010-06-30 00:20:43 +00004556 Diag(Loc, ConvDiag)
4557 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4558 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004559
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004560 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4561 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004562 if (Result.isInvalid())
4563 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004564 // Record usage of conversion in an implicit cast.
4565 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4566 CK_UserDefinedConversion,
4567 Result.get(), 0,
4568 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004569 break;
4570 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004571
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004572 default:
4573 Diag(Loc, AmbigDiag)
4574 << T << From->getSourceRange();
4575 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4576 CXXConversionDecl *Conv
4577 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4578 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4579 Diag(Conv->getLocation(), AmbigNote)
4580 << ConvTy->isEnumeralType() << ConvTy;
4581 }
John McCallb268a282010-08-23 23:25:46 +00004582 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004583 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584
Douglas Gregor5823da32010-06-29 23:25:20 +00004585 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004586 Diag(Loc, NotIntDiag)
4587 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004588
John McCallb268a282010-08-23 23:25:46 +00004589 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004590}
4591
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004592/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004593/// candidate functions, using the given function call arguments. If
4594/// @p SuppressUserConversions, then don't allow user-defined
4595/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004596///
4597/// \para PartialOverloading true if we are performing "partial" overloading
4598/// based on an incomplete set of function arguments. This feature is used by
4599/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004600void
4601Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004602 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004603 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004604 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004605 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004606 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004607 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004608 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004609 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004610 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004611 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004612
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004613 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004614 if (!isa<CXXConstructorDecl>(Method)) {
4615 // If we get here, it's because we're calling a member function
4616 // that is named without a member access expression (e.g.,
4617 // "this->f") that was either written explicitly or created
4618 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004619 // function, e.g., X::f(). We use an empty type for the implied
4620 // object argument (C++ [over.call.func]p3), and the acting context
4621 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004622 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004624 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004625 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004626 return;
4627 }
4628 // We treat a constructor like a non-member function, since its object
4629 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004630 }
4631
Douglas Gregorff7028a2009-11-13 23:59:09 +00004632 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004633 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004634
Douglas Gregor27381f32009-11-23 12:27:39 +00004635 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004636 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004637
Douglas Gregorffe14e32009-11-14 01:20:54 +00004638 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4639 // C++ [class.copy]p3:
4640 // A member function template is never instantiated to perform the copy
4641 // of a class object to an object of its class type.
4642 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004643 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004644 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004645 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4646 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004647 return;
4648 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004650 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004651 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00004652 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004653 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004654 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004655 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004656 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004657 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004658
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004659 unsigned NumArgsInProto = Proto->getNumArgs();
4660
4661 // (C++ 13.3.2p2): A candidate function having fewer than m
4662 // parameters is viable only if it has an ellipsis in its parameter
4663 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004664 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004665 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004666 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004667 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004668 return;
4669 }
4670
4671 // (C++ 13.3.2p2): A candidate function having more than m parameters
4672 // is viable only if the (m+1)st parameter has a default argument
4673 // (8.3.6). For the purposes of overload resolution, the
4674 // parameter list is truncated on the right, so that there are
4675 // exactly m parameters.
4676 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004677 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004678 // Not enough arguments.
4679 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004680 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004681 return;
4682 }
4683
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004684 // (CUDA B.1): Check for invalid calls between targets.
4685 if (getLangOptions().CUDA)
4686 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4687 if (CheckCUDATarget(Caller, Function)) {
4688 Candidate.Viable = false;
4689 Candidate.FailureKind = ovl_fail_bad_target;
4690 return;
4691 }
4692
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004693 // Determine the implicit conversion sequences for each of the
4694 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004695 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4696 if (ArgIdx < NumArgsInProto) {
4697 // (C++ 13.3.2p3): for F to be a viable function, there shall
4698 // exist for each argument an implicit conversion sequence
4699 // (13.3.3.1) that converts that argument to the corresponding
4700 // parameter of F.
4701 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004702 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004703 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004704 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004705 /*InOverloadResolution=*/true,
4706 /*AllowObjCWritebackConversion=*/
4707 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004708 if (Candidate.Conversions[ArgIdx].isBad()) {
4709 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004710 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004711 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004712 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004713 } else {
4714 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4715 // argument for which there is no corresponding parameter is
4716 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004717 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004718 }
4719 }
4720}
4721
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004722/// \brief Add all of the function declarations in the given function set to
4723/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004724void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004725 Expr **Args, unsigned NumArgs,
4726 OverloadCandidateSet& CandidateSet,
4727 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004728 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004729 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4730 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004731 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004732 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004733 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004734 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004735 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004736 CandidateSet, SuppressUserConversions);
4737 else
John McCalla0296f72010-03-19 07:35:19 +00004738 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004739 SuppressUserConversions);
4740 } else {
John McCalla0296f72010-03-19 07:35:19 +00004741 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004742 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4743 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004744 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004745 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004746 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004747 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004748 Args[0]->Classify(Context),
4749 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004750 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004751 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004752 else
John McCalla0296f72010-03-19 07:35:19 +00004753 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004754 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004755 Args, NumArgs, CandidateSet,
4756 SuppressUserConversions);
4757 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004758 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004759}
4760
John McCallf0f1cf02009-11-17 07:50:12 +00004761/// AddMethodCandidate - Adds a named decl (which is some kind of
4762/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004763void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004764 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004765 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004766 Expr **Args, unsigned NumArgs,
4767 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004768 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004769 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004770 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004771
4772 if (isa<UsingShadowDecl>(Decl))
4773 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004774
John McCallf0f1cf02009-11-17 07:50:12 +00004775 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4776 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4777 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004778 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4779 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004780 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004781 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004782 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004783 } else {
John McCalla0296f72010-03-19 07:35:19 +00004784 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004785 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004786 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004787 }
4788}
4789
Douglas Gregor436424c2008-11-18 23:14:02 +00004790/// AddMethodCandidate - Adds the given C++ member function to the set
4791/// of candidate functions, using the given function call arguments
4792/// and the object argument (@c Object). For example, in a call
4793/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4794/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4795/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004796/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004797void
John McCalla0296f72010-03-19 07:35:19 +00004798Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004799 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004800 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004801 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004802 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004803 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004804 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004805 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004806 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004807 assert(!isa<CXXConstructorDecl>(Method) &&
4808 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004809
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004810 if (!CandidateSet.isNewCandidate(Method))
4811 return;
4812
Douglas Gregor27381f32009-11-23 12:27:39 +00004813 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004814 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004815
Douglas Gregor436424c2008-11-18 23:14:02 +00004816 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004817 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00004818 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004819 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004820 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004821 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004822 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004823
4824 unsigned NumArgsInProto = Proto->getNumArgs();
4825
4826 // (C++ 13.3.2p2): A candidate function having fewer than m
4827 // parameters is viable only if it has an ellipsis in its parameter
4828 // list (8.3.5).
4829 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4830 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004831 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004832 return;
4833 }
4834
4835 // (C++ 13.3.2p2): A candidate function having more than m parameters
4836 // is viable only if the (m+1)st parameter has a default argument
4837 // (8.3.6). For the purposes of overload resolution, the
4838 // parameter list is truncated on the right, so that there are
4839 // exactly m parameters.
4840 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4841 if (NumArgs < MinRequiredArgs) {
4842 // Not enough arguments.
4843 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004844 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004845 return;
4846 }
4847
4848 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00004849
John McCall6e9f8f62009-12-03 04:06:58 +00004850 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004851 // The implicit object argument is ignored.
4852 Candidate.IgnoreObjectArgument = true;
4853 else {
4854 // Determine the implicit conversion sequence for the object
4855 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004856 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004857 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4858 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004859 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004860 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004861 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004862 return;
4863 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004864 }
4865
4866 // Determine the implicit conversion sequences for each of the
4867 // arguments.
4868 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4869 if (ArgIdx < NumArgsInProto) {
4870 // (C++ 13.3.2p3): for F to be a viable function, there shall
4871 // exist for each argument an implicit conversion sequence
4872 // (13.3.3.1) that converts that argument to the corresponding
4873 // parameter of F.
4874 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004875 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004876 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004877 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004878 /*InOverloadResolution=*/true,
4879 /*AllowObjCWritebackConversion=*/
4880 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004881 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004882 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004883 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004884 break;
4885 }
4886 } else {
4887 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4888 // argument for which there is no corresponding parameter is
4889 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004890 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004891 }
4892 }
4893}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004894
Douglas Gregor97628d62009-08-21 00:16:32 +00004895/// \brief Add a C++ member function template as a candidate to the candidate
4896/// set, using template argument deduction to produce an appropriate member
4897/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004898void
Douglas Gregor97628d62009-08-21 00:16:32 +00004899Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004900 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004901 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004902 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004903 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004904 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004905 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004906 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004907 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004908 if (!CandidateSet.isNewCandidate(MethodTmpl))
4909 return;
4910
Douglas Gregor97628d62009-08-21 00:16:32 +00004911 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004912 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004913 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004914 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004915 // candidate functions in the usual way.113) A given name can refer to one
4916 // or more function templates and also to a set of overloaded non-template
4917 // functions. In such a case, the candidate functions generated from each
4918 // function template are combined with the set of non-template candidate
4919 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004920 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004921 FunctionDecl *Specialization = 0;
4922 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004923 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004924 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004925 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004926 Candidate.FoundDecl = FoundDecl;
4927 Candidate.Function = MethodTmpl->getTemplatedDecl();
4928 Candidate.Viable = false;
4929 Candidate.FailureKind = ovl_fail_bad_deduction;
4930 Candidate.IsSurrogate = false;
4931 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004932 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004933 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004934 Info);
4935 return;
4936 }
Mike Stump11289f42009-09-09 15:08:12 +00004937
Douglas Gregor97628d62009-08-21 00:16:32 +00004938 // Add the function template specialization produced by template argument
4939 // deduction as a candidate.
4940 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004941 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004942 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004943 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004944 ActingContext, ObjectType, ObjectClassification,
4945 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004946}
4947
Douglas Gregor05155d82009-08-21 23:19:43 +00004948/// \brief Add a C++ function template specialization as a candidate
4949/// in the candidate set, using template argument deduction to produce
4950/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004951void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004952Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004953 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004954 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004955 Expr **Args, unsigned NumArgs,
4956 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004957 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004958 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4959 return;
4960
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004961 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004962 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004963 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004964 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004965 // candidate functions in the usual way.113) A given name can refer to one
4966 // or more function templates and also to a set of overloaded non-template
4967 // functions. In such a case, the candidate functions generated from each
4968 // function template are combined with the set of non-template candidate
4969 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004970 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004971 FunctionDecl *Specialization = 0;
4972 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004973 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004974 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004975 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00004976 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004977 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4978 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004979 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004980 Candidate.IsSurrogate = false;
4981 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004982 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004984 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004985 return;
4986 }
Mike Stump11289f42009-09-09 15:08:12 +00004987
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004988 // Add the function template specialization produced by template argument
4989 // deduction as a candidate.
4990 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004991 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004992 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004993}
Mike Stump11289f42009-09-09 15:08:12 +00004994
Douglas Gregora1f013e2008-11-07 22:36:19 +00004995/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004996/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004997/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004998/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004999/// (which may or may not be the same type as the type that the
5000/// conversion function produces).
5001void
5002Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005003 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005004 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005005 Expr *From, QualType ToType,
5006 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005007 assert(!Conversion->getDescribedFunctionTemplate() &&
5008 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005009 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005010 if (!CandidateSet.isNewCandidate(Conversion))
5011 return;
5012
Douglas Gregor27381f32009-11-23 12:27:39 +00005013 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005014 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005015
Douglas Gregora1f013e2008-11-07 22:36:19 +00005016 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005017 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005018 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005019 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005020 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005021 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005022 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005023 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005024 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005025 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005026 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005027
Douglas Gregor6affc782010-08-19 15:37:02 +00005028 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005029 // For conversion functions, the function is considered to be a member of
5030 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005031 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005032 //
5033 // Determine the implicit conversion sequence for the implicit
5034 // object parameter.
5035 QualType ImplicitParamType = From->getType();
5036 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5037 ImplicitParamType = FromPtrType->getPointeeType();
5038 CXXRecordDecl *ConversionContext
5039 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005041 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005042 = TryObjectArgumentInitialization(*this, From->getType(),
5043 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005044 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045
John McCall0d1da222010-01-12 00:44:57 +00005046 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005047 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005048 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005049 return;
5050 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005051
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005053 // derived to base as such conversions are given Conversion Rank. They only
5054 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5055 QualType FromCanon
5056 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5057 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5058 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5059 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005060 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005061 return;
5062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005063
Douglas Gregora1f013e2008-11-07 22:36:19 +00005064 // To determine what the conversion from the result of calling the
5065 // conversion function to the type we're eventually trying to
5066 // convert to (ToType), we need to synthesize a call to the
5067 // conversion function and attempt copy initialization from it. This
5068 // makes sure that we get the right semantics with respect to
5069 // lvalues/rvalues and the type. Fortunately, we can allocate this
5070 // call on the stack and we don't need its arguments to be
5071 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005072 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005073 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005074 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5075 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005076 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005077 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005078
Richard Smith48d24642011-07-13 22:53:21 +00005079 QualType ConversionType = Conversion->getConversionType();
5080 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005081 Candidate.Viable = false;
5082 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5083 return;
5084 }
5085
Richard Smith48d24642011-07-13 22:53:21 +00005086 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005087
Mike Stump11289f42009-09-09 15:08:12 +00005088 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005089 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5090 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005091 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005092 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005093 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005094 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005095 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005096 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005097 /*InOverloadResolution=*/false,
5098 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005099
John McCall0d1da222010-01-12 00:44:57 +00005100 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005101 case ImplicitConversionSequence::StandardConversion:
5102 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005103
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005104 // C++ [over.ics.user]p3:
5105 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005106 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005107 // shall have exact match rank.
5108 if (Conversion->getPrimaryTemplate() &&
5109 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5110 Candidate.Viable = false;
5111 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5112 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113
Douglas Gregorcba72b12011-01-21 05:18:22 +00005114 // C++0x [dcl.init.ref]p5:
5115 // In the second case, if the reference is an rvalue reference and
5116 // the second standard conversion sequence of the user-defined
5117 // conversion sequence includes an lvalue-to-rvalue conversion, the
5118 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005119 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005120 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5121 Candidate.Viable = false;
5122 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5123 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005124 break;
5125
5126 case ImplicitConversionSequence::BadConversion:
5127 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005128 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005129 break;
5130
5131 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005132 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005133 "Can only end up with a standard conversion sequence or failure");
5134 }
5135}
5136
Douglas Gregor05155d82009-08-21 23:19:43 +00005137/// \brief Adds a conversion function template specialization
5138/// candidate to the overload set, using template argument deduction
5139/// to deduce the template arguments of the conversion function
5140/// template from the type that we are converting to (C++
5141/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005142void
Douglas Gregor05155d82009-08-21 23:19:43 +00005143Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005144 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005145 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005146 Expr *From, QualType ToType,
5147 OverloadCandidateSet &CandidateSet) {
5148 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5149 "Only conversion function templates permitted here");
5150
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005151 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5152 return;
5153
John McCallbc077cf2010-02-08 23:07:23 +00005154 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005155 CXXConversionDecl *Specialization = 0;
5156 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005157 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005158 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005159 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005160 Candidate.FoundDecl = FoundDecl;
5161 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5162 Candidate.Viable = false;
5163 Candidate.FailureKind = ovl_fail_bad_deduction;
5164 Candidate.IsSurrogate = false;
5165 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005166 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005168 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005169 return;
5170 }
Mike Stump11289f42009-09-09 15:08:12 +00005171
Douglas Gregor05155d82009-08-21 23:19:43 +00005172 // Add the conversion function template specialization produced by
5173 // template argument deduction as a candidate.
5174 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005175 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005176 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005177}
5178
Douglas Gregorab7897a2008-11-19 22:57:39 +00005179/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5180/// converts the given @c Object to a function pointer via the
5181/// conversion function @c Conversion, and then attempts to call it
5182/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5183/// the type of function that we'll eventually be calling.
5184void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005185 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005186 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005187 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005188 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005189 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005190 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005191 if (!CandidateSet.isNewCandidate(Conversion))
5192 return;
5193
Douglas Gregor27381f32009-11-23 12:27:39 +00005194 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005195 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005196
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005197 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005198 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005199 Candidate.Function = 0;
5200 Candidate.Surrogate = Conversion;
5201 Candidate.Viable = true;
5202 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005203 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005204 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005205
5206 // Determine the implicit conversion sequence for the implicit
5207 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005208 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005209 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005210 Object->Classify(Context),
5211 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005212 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005213 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005214 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005215 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005216 return;
5217 }
5218
5219 // The first conversion is actually a user-defined conversion whose
5220 // first conversion is ObjectInit's standard conversion (which is
5221 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005222 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005223 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005224 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005225 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005226 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005227 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005228 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005229 = Candidate.Conversions[0].UserDefined.Before;
5230 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5231
Mike Stump11289f42009-09-09 15:08:12 +00005232 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005233 unsigned NumArgsInProto = Proto->getNumArgs();
5234
5235 // (C++ 13.3.2p2): A candidate function having fewer than m
5236 // parameters is viable only if it has an ellipsis in its parameter
5237 // list (8.3.5).
5238 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5239 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005240 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005241 return;
5242 }
5243
5244 // Function types don't have any default arguments, so just check if
5245 // we have enough arguments.
5246 if (NumArgs < NumArgsInProto) {
5247 // Not enough arguments.
5248 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005249 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005250 return;
5251 }
5252
5253 // Determine the implicit conversion sequences for each of the
5254 // arguments.
5255 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5256 if (ArgIdx < NumArgsInProto) {
5257 // (C++ 13.3.2p3): for F to be a viable function, there shall
5258 // exist for each argument an implicit conversion sequence
5259 // (13.3.3.1) that converts that argument to the corresponding
5260 // parameter of F.
5261 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005262 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005263 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005264 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005265 /*InOverloadResolution=*/false,
5266 /*AllowObjCWritebackConversion=*/
5267 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005268 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005269 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005270 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005271 break;
5272 }
5273 } else {
5274 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5275 // argument for which there is no corresponding parameter is
5276 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005277 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005278 }
5279 }
5280}
5281
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005282/// \brief Add overload candidates for overloaded operators that are
5283/// member functions.
5284///
5285/// Add the overloaded operator candidates that are member functions
5286/// for the operator Op that was used in an operator expression such
5287/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5288/// CandidateSet will store the added overload candidates. (C++
5289/// [over.match.oper]).
5290void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5291 SourceLocation OpLoc,
5292 Expr **Args, unsigned NumArgs,
5293 OverloadCandidateSet& CandidateSet,
5294 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005295 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5296
5297 // C++ [over.match.oper]p3:
5298 // For a unary operator @ with an operand of a type whose
5299 // cv-unqualified version is T1, and for a binary operator @ with
5300 // a left operand of a type whose cv-unqualified version is T1 and
5301 // a right operand of a type whose cv-unqualified version is T2,
5302 // three sets of candidate functions, designated member
5303 // candidates, non-member candidates and built-in candidates, are
5304 // constructed as follows:
5305 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005306
5307 // -- If T1 is a class type, the set of member candidates is the
5308 // result of the qualified lookup of T1::operator@
5309 // (13.3.1.1.1); otherwise, the set of member candidates is
5310 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005311 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005312 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005313 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005314 return;
Mike Stump11289f42009-09-09 15:08:12 +00005315
John McCall27b18f82009-11-17 02:14:36 +00005316 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5317 LookupQualifiedName(Operators, T1Rec->getDecl());
5318 Operators.suppressDiagnostics();
5319
Mike Stump11289f42009-09-09 15:08:12 +00005320 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005321 OperEnd = Operators.end();
5322 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005323 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005324 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005325 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005326 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005327 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005328 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005329}
5330
Douglas Gregora11693b2008-11-12 17:17:38 +00005331/// AddBuiltinCandidate - Add a candidate for a built-in
5332/// operator. ResultTy and ParamTys are the result and parameter types
5333/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005334/// arguments being passed to the candidate. IsAssignmentOperator
5335/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005336/// operator. NumContextualBoolArguments is the number of arguments
5337/// (at the beginning of the argument list) that will be contextually
5338/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005339void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005340 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005341 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005342 bool IsAssignmentOperator,
5343 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005344 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005345 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005346
Douglas Gregora11693b2008-11-12 17:17:38 +00005347 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005348 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005349 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005350 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005351 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005352 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005353 Candidate.BuiltinTypes.ResultTy = ResultTy;
5354 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5355 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5356
5357 // Determine the implicit conversion sequences for each of the
5358 // arguments.
5359 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005360 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005361 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005362 // C++ [over.match.oper]p4:
5363 // For the built-in assignment operators, conversions of the
5364 // left operand are restricted as follows:
5365 // -- no temporaries are introduced to hold the left operand, and
5366 // -- no user-defined conversions are applied to the left
5367 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005368 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005369 //
5370 // We block these conversions by turning off user-defined
5371 // conversions, since that is the only way that initialization of
5372 // a reference to a non-class type can occur from something that
5373 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005374 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005375 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005376 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005377 Candidate.Conversions[ArgIdx]
5378 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005379 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005380 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005381 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005382 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005383 /*InOverloadResolution=*/false,
5384 /*AllowObjCWritebackConversion=*/
5385 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005386 }
John McCall0d1da222010-01-12 00:44:57 +00005387 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005388 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005389 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005390 break;
5391 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005392 }
5393}
5394
5395/// BuiltinCandidateTypeSet - A set of types that will be used for the
5396/// candidate operator functions for built-in operators (C++
5397/// [over.built]). The types are separated into pointer types and
5398/// enumeration types.
5399class BuiltinCandidateTypeSet {
5400 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005401 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005402
5403 /// PointerTypes - The set of pointer types that will be used in the
5404 /// built-in candidates.
5405 TypeSet PointerTypes;
5406
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005407 /// MemberPointerTypes - The set of member pointer types that will be
5408 /// used in the built-in candidates.
5409 TypeSet MemberPointerTypes;
5410
Douglas Gregora11693b2008-11-12 17:17:38 +00005411 /// EnumerationTypes - The set of enumeration types that will be
5412 /// used in the built-in candidates.
5413 TypeSet EnumerationTypes;
5414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005415 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005416 /// candidates.
5417 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005418
5419 /// \brief A flag indicating non-record types are viable candidates
5420 bool HasNonRecordTypes;
5421
5422 /// \brief A flag indicating whether either arithmetic or enumeration types
5423 /// were present in the candidate set.
5424 bool HasArithmeticOrEnumeralTypes;
5425
Douglas Gregor80af3132011-05-21 23:15:46 +00005426 /// \brief A flag indicating whether the nullptr type was present in the
5427 /// candidate set.
5428 bool HasNullPtrType;
5429
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005430 /// Sema - The semantic analysis instance where we are building the
5431 /// candidate type set.
5432 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005433
Douglas Gregora11693b2008-11-12 17:17:38 +00005434 /// Context - The AST context in which we will build the type sets.
5435 ASTContext &Context;
5436
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005437 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5438 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005439 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005440
5441public:
5442 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005443 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005444
Mike Stump11289f42009-09-09 15:08:12 +00005445 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005446 : HasNonRecordTypes(false),
5447 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005448 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005449 SemaRef(SemaRef),
5450 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005451
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005452 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005453 SourceLocation Loc,
5454 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005455 bool AllowExplicitConversions,
5456 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005457
5458 /// pointer_begin - First pointer type found;
5459 iterator pointer_begin() { return PointerTypes.begin(); }
5460
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005461 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005462 iterator pointer_end() { return PointerTypes.end(); }
5463
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005464 /// member_pointer_begin - First member pointer type found;
5465 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5466
5467 /// member_pointer_end - Past the last member pointer type found;
5468 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5469
Douglas Gregora11693b2008-11-12 17:17:38 +00005470 /// enumeration_begin - First enumeration type found;
5471 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5472
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005473 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005474 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005476 iterator vector_begin() { return VectorTypes.begin(); }
5477 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005478
5479 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5480 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005481 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005482};
5483
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005484/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005485/// the set of pointer types along with any more-qualified variants of
5486/// that type. For example, if @p Ty is "int const *", this routine
5487/// will add "int const *", "int const volatile *", "int const
5488/// restrict *", and "int const volatile restrict *" to the set of
5489/// pointer types. Returns true if the add of @p Ty itself succeeded,
5490/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005491///
5492/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005493bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005494BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5495 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005496
Douglas Gregora11693b2008-11-12 17:17:38 +00005497 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005498 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005499 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005500
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005501 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005502 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005503 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005504 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005505 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005506 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005507 buildObjCPtr = true;
5508 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005509 else
David Blaikie83d382b2011-09-23 05:06:16 +00005510 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005511 }
5512 else
5513 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005514
Sebastian Redl4990a632009-11-18 20:39:26 +00005515 // Don't add qualified variants of arrays. For one, they're not allowed
5516 // (the qualifier would sink to the element type), and for another, the
5517 // only overload situation where it matters is subscript or pointer +- int,
5518 // and those shouldn't have qualifier variants anyway.
5519 if (PointeeTy->isArrayType())
5520 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005521 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005522 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005523 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005524 bool hasVolatile = VisibleQuals.hasVolatile();
5525 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005526
John McCall8ccfcb52009-09-24 19:53:00 +00005527 // Iterate through all strict supersets of BaseCVR.
5528 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5529 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005530 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5531 // in the types.
5532 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5533 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005534 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005535 if (!buildObjCPtr)
5536 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5537 else
5538 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005539 }
5540
5541 return true;
5542}
5543
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005544/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5545/// to the set of pointer types along with any more-qualified variants of
5546/// that type. For example, if @p Ty is "int const *", this routine
5547/// will add "int const *", "int const volatile *", "int const
5548/// restrict *", and "int const volatile restrict *" to the set of
5549/// pointer types. Returns true if the add of @p Ty itself succeeded,
5550/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005551///
5552/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005553bool
5554BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5555 QualType Ty) {
5556 // Insert this type.
5557 if (!MemberPointerTypes.insert(Ty))
5558 return false;
5559
John McCall8ccfcb52009-09-24 19:53:00 +00005560 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5561 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005562
John McCall8ccfcb52009-09-24 19:53:00 +00005563 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005564 // Don't add qualified variants of arrays. For one, they're not allowed
5565 // (the qualifier would sink to the element type), and for another, the
5566 // only overload situation where it matters is subscript or pointer +- int,
5567 // and those shouldn't have qualifier variants anyway.
5568 if (PointeeTy->isArrayType())
5569 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005570 const Type *ClassTy = PointerTy->getClass();
5571
5572 // Iterate through all strict supersets of the pointee type's CVR
5573 // qualifiers.
5574 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5575 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5576 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005577
John McCall8ccfcb52009-09-24 19:53:00 +00005578 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005579 MemberPointerTypes.insert(
5580 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005581 }
5582
5583 return true;
5584}
5585
Douglas Gregora11693b2008-11-12 17:17:38 +00005586/// AddTypesConvertedFrom - Add each of the types to which the type @p
5587/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005588/// primarily interested in pointer types and enumeration types. We also
5589/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005590/// AllowUserConversions is true if we should look at the conversion
5591/// functions of a class type, and AllowExplicitConversions if we
5592/// should also include the explicit conversion functions of a class
5593/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005594void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005595BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005596 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005597 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005598 bool AllowExplicitConversions,
5599 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005600 // Only deal with canonical types.
5601 Ty = Context.getCanonicalType(Ty);
5602
5603 // Look through reference types; they aren't part of the type of an
5604 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005605 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005606 Ty = RefTy->getPointeeType();
5607
John McCall33ddac02011-01-19 10:06:00 +00005608 // If we're dealing with an array type, decay to the pointer.
5609 if (Ty->isArrayType())
5610 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5611
5612 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005613 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005614
Chandler Carruth00a38332010-12-13 01:44:01 +00005615 // Flag if we ever add a non-record type.
5616 const RecordType *TyRec = Ty->getAs<RecordType>();
5617 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5618
Chandler Carruth00a38332010-12-13 01:44:01 +00005619 // Flag if we encounter an arithmetic type.
5620 HasArithmeticOrEnumeralTypes =
5621 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5622
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005623 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5624 PointerTypes.insert(Ty);
5625 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005626 // Insert our type, and its more-qualified variants, into the set
5627 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005628 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005629 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005630 } else if (Ty->isMemberPointerType()) {
5631 // Member pointers are far easier, since the pointee can't be converted.
5632 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5633 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005634 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005635 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005636 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005637 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005638 // We treat vector types as arithmetic types in many contexts as an
5639 // extension.
5640 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005641 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005642 } else if (Ty->isNullPtrType()) {
5643 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005644 } else if (AllowUserConversions && TyRec) {
5645 // No conversion functions in incomplete types.
5646 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5647 return;
Mike Stump11289f42009-09-09 15:08:12 +00005648
Chandler Carruth00a38332010-12-13 01:44:01 +00005649 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5650 const UnresolvedSetImpl *Conversions
5651 = ClassDecl->getVisibleConversionFunctions();
5652 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5653 E = Conversions->end(); I != E; ++I) {
5654 NamedDecl *D = I.getDecl();
5655 if (isa<UsingShadowDecl>(D))
5656 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005657
Chandler Carruth00a38332010-12-13 01:44:01 +00005658 // Skip conversion function templates; they don't tell us anything
5659 // about which builtin types we can convert to.
5660 if (isa<FunctionTemplateDecl>(D))
5661 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005662
Chandler Carruth00a38332010-12-13 01:44:01 +00005663 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5664 if (AllowExplicitConversions || !Conv->isExplicit()) {
5665 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5666 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005667 }
5668 }
5669 }
5670}
5671
Douglas Gregor84605ae2009-08-24 13:43:27 +00005672/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5673/// the volatile- and non-volatile-qualified assignment operators for the
5674/// given type to the candidate set.
5675static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5676 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005677 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005678 unsigned NumArgs,
5679 OverloadCandidateSet &CandidateSet) {
5680 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005681
Douglas Gregor84605ae2009-08-24 13:43:27 +00005682 // T& operator=(T&, T)
5683 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5684 ParamTypes[1] = T;
5685 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5686 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005687
Douglas Gregor84605ae2009-08-24 13:43:27 +00005688 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5689 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005690 ParamTypes[0]
5691 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005692 ParamTypes[1] = T;
5693 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005694 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005695 }
5696}
Mike Stump11289f42009-09-09 15:08:12 +00005697
Sebastian Redl1054fae2009-10-25 17:03:50 +00005698/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5699/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005700static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5701 Qualifiers VRQuals;
5702 const RecordType *TyRec;
5703 if (const MemberPointerType *RHSMPType =
5704 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005705 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005706 else
5707 TyRec = ArgExpr->getType()->getAs<RecordType>();
5708 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005709 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005710 VRQuals.addVolatile();
5711 VRQuals.addRestrict();
5712 return VRQuals;
5713 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005714
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005715 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005716 if (!ClassDecl->hasDefinition())
5717 return VRQuals;
5718
John McCallad371252010-01-20 00:46:10 +00005719 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005720 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005721
John McCallad371252010-01-20 00:46:10 +00005722 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005723 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005724 NamedDecl *D = I.getDecl();
5725 if (isa<UsingShadowDecl>(D))
5726 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5727 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005728 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5729 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5730 CanTy = ResTypeRef->getPointeeType();
5731 // Need to go down the pointer/mempointer chain and add qualifiers
5732 // as see them.
5733 bool done = false;
5734 while (!done) {
5735 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5736 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005737 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005738 CanTy->getAs<MemberPointerType>())
5739 CanTy = ResTypeMPtr->getPointeeType();
5740 else
5741 done = true;
5742 if (CanTy.isVolatileQualified())
5743 VRQuals.addVolatile();
5744 if (CanTy.isRestrictQualified())
5745 VRQuals.addRestrict();
5746 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5747 return VRQuals;
5748 }
5749 }
5750 }
5751 return VRQuals;
5752}
John McCall52872982010-11-13 05:51:15 +00005753
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005754namespace {
John McCall52872982010-11-13 05:51:15 +00005755
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005756/// \brief Helper class to manage the addition of builtin operator overload
5757/// candidates. It provides shared state and utility methods used throughout
5758/// the process, as well as a helper method to add each group of builtin
5759/// operator overloads from the standard to a candidate set.
5760class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005761 // Common instance state available to all overload candidate addition methods.
5762 Sema &S;
5763 Expr **Args;
5764 unsigned NumArgs;
5765 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005766 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005767 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005768 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005769
Chandler Carruthc6586e52010-12-12 10:35:00 +00005770 // Define some constants used to index and iterate over the arithemetic types
5771 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005772 // The "promoted arithmetic types" are the arithmetic
5773 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005774 static const unsigned FirstIntegralType = 3;
5775 static const unsigned LastIntegralType = 18;
5776 static const unsigned FirstPromotedIntegralType = 3,
5777 LastPromotedIntegralType = 9;
5778 static const unsigned FirstPromotedArithmeticType = 0,
5779 LastPromotedArithmeticType = 9;
5780 static const unsigned NumArithmeticTypes = 18;
5781
Chandler Carruthc6586e52010-12-12 10:35:00 +00005782 /// \brief Get the canonical type for a given arithmetic type index.
5783 CanQualType getArithmeticType(unsigned index) {
5784 assert(index < NumArithmeticTypes);
5785 static CanQualType ASTContext::* const
5786 ArithmeticTypes[NumArithmeticTypes] = {
5787 // Start of promoted types.
5788 &ASTContext::FloatTy,
5789 &ASTContext::DoubleTy,
5790 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005791
Chandler Carruthc6586e52010-12-12 10:35:00 +00005792 // Start of integral types.
5793 &ASTContext::IntTy,
5794 &ASTContext::LongTy,
5795 &ASTContext::LongLongTy,
5796 &ASTContext::UnsignedIntTy,
5797 &ASTContext::UnsignedLongTy,
5798 &ASTContext::UnsignedLongLongTy,
5799 // End of promoted types.
5800
5801 &ASTContext::BoolTy,
5802 &ASTContext::CharTy,
5803 &ASTContext::WCharTy,
5804 &ASTContext::Char16Ty,
5805 &ASTContext::Char32Ty,
5806 &ASTContext::SignedCharTy,
5807 &ASTContext::ShortTy,
5808 &ASTContext::UnsignedCharTy,
5809 &ASTContext::UnsignedShortTy,
5810 // End of integral types.
5811 // FIXME: What about complex?
5812 };
5813 return S.Context.*ArithmeticTypes[index];
5814 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005815
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005816 /// \brief Gets the canonical type resulting from the usual arithemetic
5817 /// converions for the given arithmetic types.
5818 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5819 // Accelerator table for performing the usual arithmetic conversions.
5820 // The rules are basically:
5821 // - if either is floating-point, use the wider floating-point
5822 // - if same signedness, use the higher rank
5823 // - if same size, use unsigned of the higher rank
5824 // - use the larger type
5825 // These rules, together with the axiom that higher ranks are
5826 // never smaller, are sufficient to precompute all of these results
5827 // *except* when dealing with signed types of higher rank.
5828 // (we could precompute SLL x UI for all known platforms, but it's
5829 // better not to make any assumptions).
5830 enum PromotedType {
5831 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5832 };
5833 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5834 [LastPromotedArithmeticType] = {
5835 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5836 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5837 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5838 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5839 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5840 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5841 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5842 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5843 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5844 };
5845
5846 assert(L < LastPromotedArithmeticType);
5847 assert(R < LastPromotedArithmeticType);
5848 int Idx = ConversionsTable[L][R];
5849
5850 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005851 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005852
5853 // Slow path: we need to compare widths.
5854 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005855 CanQualType LT = getArithmeticType(L),
5856 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005857 unsigned LW = S.Context.getIntWidth(LT),
5858 RW = S.Context.getIntWidth(RT);
5859
5860 // If they're different widths, use the signed type.
5861 if (LW > RW) return LT;
5862 else if (LW < RW) return RT;
5863
5864 // Otherwise, use the unsigned type of the signed type's rank.
5865 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5866 assert(L == SLL || R == SLL);
5867 return S.Context.UnsignedLongLongTy;
5868 }
5869
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005870 /// \brief Helper method to factor out the common pattern of adding overloads
5871 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005872 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5873 bool HasVolatile) {
5874 QualType ParamTypes[2] = {
5875 S.Context.getLValueReferenceType(CandidateTy),
5876 S.Context.IntTy
5877 };
5878
5879 // Non-volatile version.
5880 if (NumArgs == 1)
5881 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5882 else
5883 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5884
5885 // Use a heuristic to reduce number of builtin candidates in the set:
5886 // add volatile version only if there are conversions to a volatile type.
5887 if (HasVolatile) {
5888 ParamTypes[0] =
5889 S.Context.getLValueReferenceType(
5890 S.Context.getVolatileType(CandidateTy));
5891 if (NumArgs == 1)
5892 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5893 else
5894 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5895 }
5896 }
5897
5898public:
5899 BuiltinOperatorOverloadBuilder(
5900 Sema &S, Expr **Args, unsigned NumArgs,
5901 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005902 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005903 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005904 OverloadCandidateSet &CandidateSet)
5905 : S(S), Args(Args), NumArgs(NumArgs),
5906 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005907 HasArithmeticOrEnumeralCandidateType(
5908 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005909 CandidateTypes(CandidateTypes),
5910 CandidateSet(CandidateSet) {
5911 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005912 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005913 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005914 assert(getArithmeticType(LastPromotedIntegralType - 1)
5915 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005916 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005917 assert(getArithmeticType(FirstPromotedArithmeticType)
5918 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005919 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005920 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5921 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005922 "Invalid last promoted arithmetic type");
5923 }
5924
5925 // C++ [over.built]p3:
5926 //
5927 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5928 // is either volatile or empty, there exist candidate operator
5929 // functions of the form
5930 //
5931 // VQ T& operator++(VQ T&);
5932 // T operator++(VQ T&, int);
5933 //
5934 // C++ [over.built]p4:
5935 //
5936 // For every pair (T, VQ), where T is an arithmetic type other
5937 // than bool, and VQ is either volatile or empty, there exist
5938 // candidate operator functions of the form
5939 //
5940 // VQ T& operator--(VQ T&);
5941 // T operator--(VQ T&, int);
5942 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005943 if (!HasArithmeticOrEnumeralCandidateType)
5944 return;
5945
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005946 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5947 Arith < NumArithmeticTypes; ++Arith) {
5948 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005949 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005950 VisibleTypeConversionsQuals.hasVolatile());
5951 }
5952 }
5953
5954 // C++ [over.built]p5:
5955 //
5956 // For every pair (T, VQ), where T is a cv-qualified or
5957 // cv-unqualified object type, and VQ is either volatile or
5958 // empty, there exist candidate operator functions of the form
5959 //
5960 // T*VQ& operator++(T*VQ&);
5961 // T*VQ& operator--(T*VQ&);
5962 // T* operator++(T*VQ&, int);
5963 // T* operator--(T*VQ&, int);
5964 void addPlusPlusMinusMinusPointerOverloads() {
5965 for (BuiltinCandidateTypeSet::iterator
5966 Ptr = CandidateTypes[0].pointer_begin(),
5967 PtrEnd = CandidateTypes[0].pointer_end();
5968 Ptr != PtrEnd; ++Ptr) {
5969 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005970 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005971 continue;
5972
5973 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5974 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5975 VisibleTypeConversionsQuals.hasVolatile()));
5976 }
5977 }
5978
5979 // C++ [over.built]p6:
5980 // For every cv-qualified or cv-unqualified object type T, there
5981 // exist candidate operator functions of the form
5982 //
5983 // T& operator*(T*);
5984 //
5985 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005986 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005987 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005988 // T& operator*(T*);
5989 void addUnaryStarPointerOverloads() {
5990 for (BuiltinCandidateTypeSet::iterator
5991 Ptr = CandidateTypes[0].pointer_begin(),
5992 PtrEnd = CandidateTypes[0].pointer_end();
5993 Ptr != PtrEnd; ++Ptr) {
5994 QualType ParamTy = *Ptr;
5995 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005996 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5997 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005998
Douglas Gregor02824322011-01-26 19:30:28 +00005999 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6000 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6001 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006002
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006003 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6004 &ParamTy, Args, 1, CandidateSet);
6005 }
6006 }
6007
6008 // C++ [over.built]p9:
6009 // For every promoted arithmetic type T, there exist candidate
6010 // operator functions of the form
6011 //
6012 // T operator+(T);
6013 // T operator-(T);
6014 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006015 if (!HasArithmeticOrEnumeralCandidateType)
6016 return;
6017
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006018 for (unsigned Arith = FirstPromotedArithmeticType;
6019 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006020 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006021 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6022 }
6023
6024 // Extension: We also add these operators for vector types.
6025 for (BuiltinCandidateTypeSet::iterator
6026 Vec = CandidateTypes[0].vector_begin(),
6027 VecEnd = CandidateTypes[0].vector_end();
6028 Vec != VecEnd; ++Vec) {
6029 QualType VecTy = *Vec;
6030 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6031 }
6032 }
6033
6034 // C++ [over.built]p8:
6035 // For every type T, there exist candidate operator functions of
6036 // the form
6037 //
6038 // T* operator+(T*);
6039 void addUnaryPlusPointerOverloads() {
6040 for (BuiltinCandidateTypeSet::iterator
6041 Ptr = CandidateTypes[0].pointer_begin(),
6042 PtrEnd = CandidateTypes[0].pointer_end();
6043 Ptr != PtrEnd; ++Ptr) {
6044 QualType ParamTy = *Ptr;
6045 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6046 }
6047 }
6048
6049 // C++ [over.built]p10:
6050 // For every promoted integral type T, there exist candidate
6051 // operator functions of the form
6052 //
6053 // T operator~(T);
6054 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006055 if (!HasArithmeticOrEnumeralCandidateType)
6056 return;
6057
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006058 for (unsigned Int = FirstPromotedIntegralType;
6059 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006060 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006061 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6062 }
6063
6064 // Extension: We also add this operator for vector types.
6065 for (BuiltinCandidateTypeSet::iterator
6066 Vec = CandidateTypes[0].vector_begin(),
6067 VecEnd = CandidateTypes[0].vector_end();
6068 Vec != VecEnd; ++Vec) {
6069 QualType VecTy = *Vec;
6070 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6071 }
6072 }
6073
6074 // C++ [over.match.oper]p16:
6075 // For every pointer to member type T, there exist candidate operator
6076 // functions of the form
6077 //
6078 // bool operator==(T,T);
6079 // bool operator!=(T,T);
6080 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6081 /// Set of (canonical) types that we've already handled.
6082 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6083
6084 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6085 for (BuiltinCandidateTypeSet::iterator
6086 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6087 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6088 MemPtr != MemPtrEnd;
6089 ++MemPtr) {
6090 // Don't add the same builtin candidate twice.
6091 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6092 continue;
6093
6094 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6095 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6096 CandidateSet);
6097 }
6098 }
6099 }
6100
6101 // C++ [over.built]p15:
6102 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006103 // For every T, where T is an enumeration type, a pointer type, or
6104 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006105 //
6106 // bool operator<(T, T);
6107 // bool operator>(T, T);
6108 // bool operator<=(T, T);
6109 // bool operator>=(T, T);
6110 // bool operator==(T, T);
6111 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006112 void addRelationalPointerOrEnumeralOverloads() {
6113 // C++ [over.built]p1:
6114 // If there is a user-written candidate with the same name and parameter
6115 // types as a built-in candidate operator function, the built-in operator
6116 // function is hidden and is not included in the set of candidate
6117 // functions.
6118 //
6119 // The text is actually in a note, but if we don't implement it then we end
6120 // up with ambiguities when the user provides an overloaded operator for
6121 // an enumeration type. Note that only enumeration types have this problem,
6122 // so we track which enumeration types we've seen operators for. Also, the
6123 // only other overloaded operator with enumeration argumenst, operator=,
6124 // cannot be overloaded for enumeration types, so this is the only place
6125 // where we must suppress candidates like this.
6126 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6127 UserDefinedBinaryOperators;
6128
6129 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6130 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6131 CandidateTypes[ArgIdx].enumeration_end()) {
6132 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6133 CEnd = CandidateSet.end();
6134 C != CEnd; ++C) {
6135 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6136 continue;
6137
6138 QualType FirstParamType =
6139 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6140 QualType SecondParamType =
6141 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6142
6143 // Skip if either parameter isn't of enumeral type.
6144 if (!FirstParamType->isEnumeralType() ||
6145 !SecondParamType->isEnumeralType())
6146 continue;
6147
6148 // Add this operator to the set of known user-defined operators.
6149 UserDefinedBinaryOperators.insert(
6150 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6151 S.Context.getCanonicalType(SecondParamType)));
6152 }
6153 }
6154 }
6155
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006156 /// Set of (canonical) types that we've already handled.
6157 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6158
6159 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6160 for (BuiltinCandidateTypeSet::iterator
6161 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6162 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6163 Ptr != PtrEnd; ++Ptr) {
6164 // Don't add the same builtin candidate twice.
6165 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6166 continue;
6167
6168 QualType ParamTypes[2] = { *Ptr, *Ptr };
6169 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6170 CandidateSet);
6171 }
6172 for (BuiltinCandidateTypeSet::iterator
6173 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6174 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6175 Enum != EnumEnd; ++Enum) {
6176 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6177
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006178 // Don't add the same builtin candidate twice, or if a user defined
6179 // candidate exists.
6180 if (!AddedTypes.insert(CanonType) ||
6181 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6182 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006183 continue;
6184
6185 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006186 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6187 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006188 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006189
6190 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6191 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6192 if (AddedTypes.insert(NullPtrTy) &&
6193 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6194 NullPtrTy))) {
6195 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6196 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6197 CandidateSet);
6198 }
6199 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006200 }
6201 }
6202
6203 // C++ [over.built]p13:
6204 //
6205 // For every cv-qualified or cv-unqualified object type T
6206 // there exist candidate operator functions of the form
6207 //
6208 // T* operator+(T*, ptrdiff_t);
6209 // T& operator[](T*, ptrdiff_t); [BELOW]
6210 // T* operator-(T*, ptrdiff_t);
6211 // T* operator+(ptrdiff_t, T*);
6212 // T& operator[](ptrdiff_t, T*); [BELOW]
6213 //
6214 // C++ [over.built]p14:
6215 //
6216 // For every T, where T is a pointer to object type, there
6217 // exist candidate operator functions of the form
6218 //
6219 // ptrdiff_t operator-(T, T);
6220 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6221 /// Set of (canonical) types that we've already handled.
6222 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6223
6224 for (int Arg = 0; Arg < 2; ++Arg) {
6225 QualType AsymetricParamTypes[2] = {
6226 S.Context.getPointerDiffType(),
6227 S.Context.getPointerDiffType(),
6228 };
6229 for (BuiltinCandidateTypeSet::iterator
6230 Ptr = CandidateTypes[Arg].pointer_begin(),
6231 PtrEnd = CandidateTypes[Arg].pointer_end();
6232 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006233 QualType PointeeTy = (*Ptr)->getPointeeType();
6234 if (!PointeeTy->isObjectType())
6235 continue;
6236
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006237 AsymetricParamTypes[Arg] = *Ptr;
6238 if (Arg == 0 || Op == OO_Plus) {
6239 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6240 // T* operator+(ptrdiff_t, T*);
6241 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6242 CandidateSet);
6243 }
6244 if (Op == OO_Minus) {
6245 // ptrdiff_t operator-(T, T);
6246 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6247 continue;
6248
6249 QualType ParamTypes[2] = { *Ptr, *Ptr };
6250 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6251 Args, 2, CandidateSet);
6252 }
6253 }
6254 }
6255 }
6256
6257 // C++ [over.built]p12:
6258 //
6259 // For every pair of promoted arithmetic types L and R, there
6260 // exist candidate operator functions of the form
6261 //
6262 // LR operator*(L, R);
6263 // LR operator/(L, R);
6264 // LR operator+(L, R);
6265 // LR operator-(L, R);
6266 // bool operator<(L, R);
6267 // bool operator>(L, R);
6268 // bool operator<=(L, R);
6269 // bool operator>=(L, R);
6270 // bool operator==(L, R);
6271 // bool operator!=(L, R);
6272 //
6273 // where LR is the result of the usual arithmetic conversions
6274 // between types L and R.
6275 //
6276 // C++ [over.built]p24:
6277 //
6278 // For every pair of promoted arithmetic types L and R, there exist
6279 // candidate operator functions of the form
6280 //
6281 // LR operator?(bool, L, R);
6282 //
6283 // where LR is the result of the usual arithmetic conversions
6284 // between types L and R.
6285 // Our candidates ignore the first parameter.
6286 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006287 if (!HasArithmeticOrEnumeralCandidateType)
6288 return;
6289
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006290 for (unsigned Left = FirstPromotedArithmeticType;
6291 Left < LastPromotedArithmeticType; ++Left) {
6292 for (unsigned Right = FirstPromotedArithmeticType;
6293 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006294 QualType LandR[2] = { getArithmeticType(Left),
6295 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006296 QualType Result =
6297 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006298 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006299 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6300 }
6301 }
6302
6303 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6304 // conditional operator for vector types.
6305 for (BuiltinCandidateTypeSet::iterator
6306 Vec1 = CandidateTypes[0].vector_begin(),
6307 Vec1End = CandidateTypes[0].vector_end();
6308 Vec1 != Vec1End; ++Vec1) {
6309 for (BuiltinCandidateTypeSet::iterator
6310 Vec2 = CandidateTypes[1].vector_begin(),
6311 Vec2End = CandidateTypes[1].vector_end();
6312 Vec2 != Vec2End; ++Vec2) {
6313 QualType LandR[2] = { *Vec1, *Vec2 };
6314 QualType Result = S.Context.BoolTy;
6315 if (!isComparison) {
6316 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6317 Result = *Vec1;
6318 else
6319 Result = *Vec2;
6320 }
6321
6322 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6323 }
6324 }
6325 }
6326
6327 // C++ [over.built]p17:
6328 //
6329 // For every pair of promoted integral types L and R, there
6330 // exist candidate operator functions of the form
6331 //
6332 // LR operator%(L, R);
6333 // LR operator&(L, R);
6334 // LR operator^(L, R);
6335 // LR operator|(L, R);
6336 // L operator<<(L, R);
6337 // L operator>>(L, R);
6338 //
6339 // where LR is the result of the usual arithmetic conversions
6340 // between types L and R.
6341 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006342 if (!HasArithmeticOrEnumeralCandidateType)
6343 return;
6344
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006345 for (unsigned Left = FirstPromotedIntegralType;
6346 Left < LastPromotedIntegralType; ++Left) {
6347 for (unsigned Right = FirstPromotedIntegralType;
6348 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006349 QualType LandR[2] = { getArithmeticType(Left),
6350 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006351 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6352 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006353 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006354 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6355 }
6356 }
6357 }
6358
6359 // C++ [over.built]p20:
6360 //
6361 // For every pair (T, VQ), where T is an enumeration or
6362 // pointer to member type and VQ is either volatile or
6363 // empty, there exist candidate operator functions of the form
6364 //
6365 // VQ T& operator=(VQ T&, T);
6366 void addAssignmentMemberPointerOrEnumeralOverloads() {
6367 /// Set of (canonical) types that we've already handled.
6368 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6369
6370 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6371 for (BuiltinCandidateTypeSet::iterator
6372 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6373 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6374 Enum != EnumEnd; ++Enum) {
6375 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6376 continue;
6377
6378 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6379 CandidateSet);
6380 }
6381
6382 for (BuiltinCandidateTypeSet::iterator
6383 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6384 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6385 MemPtr != MemPtrEnd; ++MemPtr) {
6386 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6387 continue;
6388
6389 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6390 CandidateSet);
6391 }
6392 }
6393 }
6394
6395 // C++ [over.built]p19:
6396 //
6397 // For every pair (T, VQ), where T is any type and VQ is either
6398 // volatile or empty, there exist candidate operator functions
6399 // of the form
6400 //
6401 // T*VQ& operator=(T*VQ&, T*);
6402 //
6403 // C++ [over.built]p21:
6404 //
6405 // For every pair (T, VQ), where T is a cv-qualified or
6406 // cv-unqualified object type and VQ is either volatile or
6407 // empty, there exist candidate operator functions of the form
6408 //
6409 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6410 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6411 void addAssignmentPointerOverloads(bool isEqualOp) {
6412 /// Set of (canonical) types that we've already handled.
6413 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6414
6415 for (BuiltinCandidateTypeSet::iterator
6416 Ptr = CandidateTypes[0].pointer_begin(),
6417 PtrEnd = CandidateTypes[0].pointer_end();
6418 Ptr != PtrEnd; ++Ptr) {
6419 // If this is operator=, keep track of the builtin candidates we added.
6420 if (isEqualOp)
6421 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006422 else if (!(*Ptr)->getPointeeType()->isObjectType())
6423 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006424
6425 // non-volatile version
6426 QualType ParamTypes[2] = {
6427 S.Context.getLValueReferenceType(*Ptr),
6428 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6429 };
6430 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6431 /*IsAssigmentOperator=*/ isEqualOp);
6432
6433 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6434 VisibleTypeConversionsQuals.hasVolatile()) {
6435 // volatile version
6436 ParamTypes[0] =
6437 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6438 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6439 /*IsAssigmentOperator=*/isEqualOp);
6440 }
6441 }
6442
6443 if (isEqualOp) {
6444 for (BuiltinCandidateTypeSet::iterator
6445 Ptr = CandidateTypes[1].pointer_begin(),
6446 PtrEnd = CandidateTypes[1].pointer_end();
6447 Ptr != PtrEnd; ++Ptr) {
6448 // Make sure we don't add the same candidate twice.
6449 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6450 continue;
6451
Chandler Carruth8e543b32010-12-12 08:17:55 +00006452 QualType ParamTypes[2] = {
6453 S.Context.getLValueReferenceType(*Ptr),
6454 *Ptr,
6455 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006456
6457 // non-volatile version
6458 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6459 /*IsAssigmentOperator=*/true);
6460
6461 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6462 VisibleTypeConversionsQuals.hasVolatile()) {
6463 // volatile version
6464 ParamTypes[0] =
6465 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006466 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6467 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006468 }
6469 }
6470 }
6471 }
6472
6473 // C++ [over.built]p18:
6474 //
6475 // For every triple (L, VQ, R), where L is an arithmetic type,
6476 // VQ is either volatile or empty, and R is a promoted
6477 // arithmetic type, there exist candidate operator functions of
6478 // the form
6479 //
6480 // VQ L& operator=(VQ L&, R);
6481 // VQ L& operator*=(VQ L&, R);
6482 // VQ L& operator/=(VQ L&, R);
6483 // VQ L& operator+=(VQ L&, R);
6484 // VQ L& operator-=(VQ L&, R);
6485 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006486 if (!HasArithmeticOrEnumeralCandidateType)
6487 return;
6488
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006489 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6490 for (unsigned Right = FirstPromotedArithmeticType;
6491 Right < LastPromotedArithmeticType; ++Right) {
6492 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006493 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006494
6495 // Add this built-in operator as a candidate (VQ is empty).
6496 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006497 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006498 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6499 /*IsAssigmentOperator=*/isEqualOp);
6500
6501 // Add this built-in operator as a candidate (VQ is 'volatile').
6502 if (VisibleTypeConversionsQuals.hasVolatile()) {
6503 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006504 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006505 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006506 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6507 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006508 /*IsAssigmentOperator=*/isEqualOp);
6509 }
6510 }
6511 }
6512
6513 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6514 for (BuiltinCandidateTypeSet::iterator
6515 Vec1 = CandidateTypes[0].vector_begin(),
6516 Vec1End = CandidateTypes[0].vector_end();
6517 Vec1 != Vec1End; ++Vec1) {
6518 for (BuiltinCandidateTypeSet::iterator
6519 Vec2 = CandidateTypes[1].vector_begin(),
6520 Vec2End = CandidateTypes[1].vector_end();
6521 Vec2 != Vec2End; ++Vec2) {
6522 QualType ParamTypes[2];
6523 ParamTypes[1] = *Vec2;
6524 // Add this built-in operator as a candidate (VQ is empty).
6525 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6526 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6527 /*IsAssigmentOperator=*/isEqualOp);
6528
6529 // Add this built-in operator as a candidate (VQ is 'volatile').
6530 if (VisibleTypeConversionsQuals.hasVolatile()) {
6531 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6532 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006533 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6534 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006535 /*IsAssigmentOperator=*/isEqualOp);
6536 }
6537 }
6538 }
6539 }
6540
6541 // C++ [over.built]p22:
6542 //
6543 // For every triple (L, VQ, R), where L is an integral type, VQ
6544 // is either volatile or empty, and R is a promoted integral
6545 // type, there exist candidate operator functions of the form
6546 //
6547 // VQ L& operator%=(VQ L&, R);
6548 // VQ L& operator<<=(VQ L&, R);
6549 // VQ L& operator>>=(VQ L&, R);
6550 // VQ L& operator&=(VQ L&, R);
6551 // VQ L& operator^=(VQ L&, R);
6552 // VQ L& operator|=(VQ L&, R);
6553 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006554 if (!HasArithmeticOrEnumeralCandidateType)
6555 return;
6556
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006557 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6558 for (unsigned Right = FirstPromotedIntegralType;
6559 Right < LastPromotedIntegralType; ++Right) {
6560 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006561 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006562
6563 // Add this built-in operator as a candidate (VQ is empty).
6564 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006565 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006566 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6567 if (VisibleTypeConversionsQuals.hasVolatile()) {
6568 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006569 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006570 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6571 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6572 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6573 CandidateSet);
6574 }
6575 }
6576 }
6577 }
6578
6579 // C++ [over.operator]p23:
6580 //
6581 // There also exist candidate operator functions of the form
6582 //
6583 // bool operator!(bool);
6584 // bool operator&&(bool, bool);
6585 // bool operator||(bool, bool);
6586 void addExclaimOverload() {
6587 QualType ParamTy = S.Context.BoolTy;
6588 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6589 /*IsAssignmentOperator=*/false,
6590 /*NumContextualBoolArguments=*/1);
6591 }
6592 void addAmpAmpOrPipePipeOverload() {
6593 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6594 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6595 /*IsAssignmentOperator=*/false,
6596 /*NumContextualBoolArguments=*/2);
6597 }
6598
6599 // C++ [over.built]p13:
6600 //
6601 // For every cv-qualified or cv-unqualified object type T there
6602 // exist candidate operator functions of the form
6603 //
6604 // T* operator+(T*, ptrdiff_t); [ABOVE]
6605 // T& operator[](T*, ptrdiff_t);
6606 // T* operator-(T*, ptrdiff_t); [ABOVE]
6607 // T* operator+(ptrdiff_t, T*); [ABOVE]
6608 // T& operator[](ptrdiff_t, T*);
6609 void addSubscriptOverloads() {
6610 for (BuiltinCandidateTypeSet::iterator
6611 Ptr = CandidateTypes[0].pointer_begin(),
6612 PtrEnd = CandidateTypes[0].pointer_end();
6613 Ptr != PtrEnd; ++Ptr) {
6614 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6615 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006616 if (!PointeeType->isObjectType())
6617 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006618
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006619 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6620
6621 // T& operator[](T*, ptrdiff_t)
6622 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6623 }
6624
6625 for (BuiltinCandidateTypeSet::iterator
6626 Ptr = CandidateTypes[1].pointer_begin(),
6627 PtrEnd = CandidateTypes[1].pointer_end();
6628 Ptr != PtrEnd; ++Ptr) {
6629 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6630 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006631 if (!PointeeType->isObjectType())
6632 continue;
6633
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006634 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6635
6636 // T& operator[](ptrdiff_t, T*)
6637 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6638 }
6639 }
6640
6641 // C++ [over.built]p11:
6642 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6643 // C1 is the same type as C2 or is a derived class of C2, T is an object
6644 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6645 // there exist candidate operator functions of the form
6646 //
6647 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6648 //
6649 // where CV12 is the union of CV1 and CV2.
6650 void addArrowStarOverloads() {
6651 for (BuiltinCandidateTypeSet::iterator
6652 Ptr = CandidateTypes[0].pointer_begin(),
6653 PtrEnd = CandidateTypes[0].pointer_end();
6654 Ptr != PtrEnd; ++Ptr) {
6655 QualType C1Ty = (*Ptr);
6656 QualType C1;
6657 QualifierCollector Q1;
6658 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6659 if (!isa<RecordType>(C1))
6660 continue;
6661 // heuristic to reduce number of builtin candidates in the set.
6662 // Add volatile/restrict version only if there are conversions to a
6663 // volatile/restrict type.
6664 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6665 continue;
6666 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6667 continue;
6668 for (BuiltinCandidateTypeSet::iterator
6669 MemPtr = CandidateTypes[1].member_pointer_begin(),
6670 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6671 MemPtr != MemPtrEnd; ++MemPtr) {
6672 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6673 QualType C2 = QualType(mptr->getClass(), 0);
6674 C2 = C2.getUnqualifiedType();
6675 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6676 break;
6677 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6678 // build CV12 T&
6679 QualType T = mptr->getPointeeType();
6680 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6681 T.isVolatileQualified())
6682 continue;
6683 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6684 T.isRestrictQualified())
6685 continue;
6686 T = Q1.apply(S.Context, T);
6687 QualType ResultTy = S.Context.getLValueReferenceType(T);
6688 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6689 }
6690 }
6691 }
6692
6693 // Note that we don't consider the first argument, since it has been
6694 // contextually converted to bool long ago. The candidates below are
6695 // therefore added as binary.
6696 //
6697 // C++ [over.built]p25:
6698 // For every type T, where T is a pointer, pointer-to-member, or scoped
6699 // enumeration type, there exist candidate operator functions of the form
6700 //
6701 // T operator?(bool, T, T);
6702 //
6703 void addConditionalOperatorOverloads() {
6704 /// Set of (canonical) types that we've already handled.
6705 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6706
6707 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6708 for (BuiltinCandidateTypeSet::iterator
6709 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6710 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6711 Ptr != PtrEnd; ++Ptr) {
6712 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6713 continue;
6714
6715 QualType ParamTypes[2] = { *Ptr, *Ptr };
6716 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6717 }
6718
6719 for (BuiltinCandidateTypeSet::iterator
6720 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6721 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6722 MemPtr != MemPtrEnd; ++MemPtr) {
6723 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6724 continue;
6725
6726 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6727 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6728 }
6729
6730 if (S.getLangOptions().CPlusPlus0x) {
6731 for (BuiltinCandidateTypeSet::iterator
6732 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6733 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6734 Enum != EnumEnd; ++Enum) {
6735 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6736 continue;
6737
6738 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6739 continue;
6740
6741 QualType ParamTypes[2] = { *Enum, *Enum };
6742 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6743 }
6744 }
6745 }
6746 }
6747};
6748
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006749} // end anonymous namespace
6750
6751/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6752/// operator overloads to the candidate set (C++ [over.built]), based
6753/// on the operator @p Op and the arguments given. For example, if the
6754/// operator is a binary '+', this routine might add "int
6755/// operator+(int, int)" to cover integer addition.
6756void
6757Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6758 SourceLocation OpLoc,
6759 Expr **Args, unsigned NumArgs,
6760 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006761 // Find all of the types that the arguments can convert to, but only
6762 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006763 // that make use of these types. Also record whether we encounter non-record
6764 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006765 Qualifiers VisibleTypeConversionsQuals;
6766 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006767 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6768 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006769
6770 bool HasNonRecordCandidateType = false;
6771 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006772 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006773 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6774 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6775 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6776 OpLoc,
6777 true,
6778 (Op == OO_Exclaim ||
6779 Op == OO_AmpAmp ||
6780 Op == OO_PipePipe),
6781 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006782 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6783 CandidateTypes[ArgIdx].hasNonRecordTypes();
6784 HasArithmeticOrEnumeralCandidateType =
6785 HasArithmeticOrEnumeralCandidateType ||
6786 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006787 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006788
Chandler Carruth00a38332010-12-13 01:44:01 +00006789 // Exit early when no non-record types have been added to the candidate set
6790 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006791 //
6792 // We can't exit early for !, ||, or &&, since there we have always have
6793 // 'bool' overloads.
6794 if (!HasNonRecordCandidateType &&
6795 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006796 return;
6797
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006798 // Setup an object to manage the common state for building overloads.
6799 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6800 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006801 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006802 CandidateTypes, CandidateSet);
6803
6804 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006805 switch (Op) {
6806 case OO_None:
6807 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006808 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006809
Chandler Carruth5184de02010-12-12 08:51:33 +00006810 case OO_New:
6811 case OO_Delete:
6812 case OO_Array_New:
6813 case OO_Array_Delete:
6814 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006815 llvm_unreachable(
6816 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006817
6818 case OO_Comma:
6819 case OO_Arrow:
6820 // C++ [over.match.oper]p3:
6821 // -- For the operator ',', the unary operator '&', or the
6822 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006823 break;
6824
6825 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006826 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006827 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006828 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006829
6830 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006831 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006832 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006833 } else {
6834 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6835 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6836 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006837 break;
6838
Chandler Carruth5184de02010-12-12 08:51:33 +00006839 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006840 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006841 OpBuilder.addUnaryStarPointerOverloads();
6842 else
6843 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6844 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006845
Chandler Carruth5184de02010-12-12 08:51:33 +00006846 case OO_Slash:
6847 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006848 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006849
6850 case OO_PlusPlus:
6851 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006852 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6853 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006854 break;
6855
Douglas Gregor84605ae2009-08-24 13:43:27 +00006856 case OO_EqualEqual:
6857 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006858 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006859 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006860
Douglas Gregora11693b2008-11-12 17:17:38 +00006861 case OO_Less:
6862 case OO_Greater:
6863 case OO_LessEqual:
6864 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006865 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006866 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6867 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006868
Douglas Gregora11693b2008-11-12 17:17:38 +00006869 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006870 case OO_Caret:
6871 case OO_Pipe:
6872 case OO_LessLess:
6873 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006874 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006875 break;
6876
Chandler Carruth5184de02010-12-12 08:51:33 +00006877 case OO_Amp: // '&' is either unary or binary
6878 if (NumArgs == 1)
6879 // C++ [over.match.oper]p3:
6880 // -- For the operator ',', the unary operator '&', or the
6881 // operator '->', the built-in candidates set is empty.
6882 break;
6883
6884 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6885 break;
6886
6887 case OO_Tilde:
6888 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6889 break;
6890
Douglas Gregora11693b2008-11-12 17:17:38 +00006891 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006892 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006893 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006894
6895 case OO_PlusEqual:
6896 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006897 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006898 // Fall through.
6899
6900 case OO_StarEqual:
6901 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006902 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006903 break;
6904
6905 case OO_PercentEqual:
6906 case OO_LessLessEqual:
6907 case OO_GreaterGreaterEqual:
6908 case OO_AmpEqual:
6909 case OO_CaretEqual:
6910 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006911 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006912 break;
6913
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006914 case OO_Exclaim:
6915 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006916 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006917
Douglas Gregora11693b2008-11-12 17:17:38 +00006918 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006919 case OO_PipePipe:
6920 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006921 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006922
6923 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006924 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006925 break;
6926
6927 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006928 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006929 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006930
6931 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006932 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006933 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6934 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006935 }
6936}
6937
Douglas Gregore254f902009-02-04 00:32:51 +00006938/// \brief Add function candidates found via argument-dependent lookup
6939/// to the set of overloading candidates.
6940///
6941/// This routine performs argument-dependent name lookup based on the
6942/// given function name (which may also be an operator name) and adds
6943/// all of the overload candidates found by ADL to the overload
6944/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006945void
Douglas Gregore254f902009-02-04 00:32:51 +00006946Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006947 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006948 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006949 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006950 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006951 bool PartialOverloading,
6952 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006953 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006954
John McCall91f61fc2010-01-26 06:04:06 +00006955 // FIXME: This approach for uniquing ADL results (and removing
6956 // redundant candidates from the set) relies on pointer-equality,
6957 // which means we need to key off the canonical decl. However,
6958 // always going back to the canonical decl might not get us the
6959 // right set of default arguments. What default arguments are
6960 // we supposed to consider on ADL candidates, anyway?
6961
Douglas Gregorcabea402009-09-22 15:41:20 +00006962 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006963 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6964 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006965
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006966 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006967 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6968 CandEnd = CandidateSet.end();
6969 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006970 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006971 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006972 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006973 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006974 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006975
6976 // For each of the ADL candidates we found, add it to the overload
6977 // set.
John McCall8fe68082010-01-26 07:16:45 +00006978 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006979 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006980 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006981 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006982 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006983
John McCalla0296f72010-03-19 07:35:19 +00006984 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006985 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006986 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006987 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006988 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006989 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006990 }
Douglas Gregore254f902009-02-04 00:32:51 +00006991}
6992
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006993/// isBetterOverloadCandidate - Determines whether the first overload
6994/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006995bool
John McCall5c32be02010-08-24 20:38:10 +00006996isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006997 const OverloadCandidate &Cand1,
6998 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006999 SourceLocation Loc,
7000 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007001 // Define viable functions to be better candidates than non-viable
7002 // functions.
7003 if (!Cand2.Viable)
7004 return Cand1.Viable;
7005 else if (!Cand1.Viable)
7006 return false;
7007
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007008 // C++ [over.match.best]p1:
7009 //
7010 // -- if F is a static member function, ICS1(F) is defined such
7011 // that ICS1(F) is neither better nor worse than ICS1(G) for
7012 // any function G, and, symmetrically, ICS1(G) is neither
7013 // better nor worse than ICS1(F).
7014 unsigned StartArg = 0;
7015 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7016 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007017
Douglas Gregord3cb3562009-07-07 23:38:56 +00007018 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007019 // A viable function F1 is defined to be a better function than another
7020 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007021 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00007022 unsigned NumArgs = Cand1.NumConversions;
7023 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007024 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007025 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007026 switch (CompareImplicitConversionSequences(S,
7027 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007028 Cand2.Conversions[ArgIdx])) {
7029 case ImplicitConversionSequence::Better:
7030 // Cand1 has a better conversion sequence.
7031 HasBetterConversion = true;
7032 break;
7033
7034 case ImplicitConversionSequence::Worse:
7035 // Cand1 can't be better than Cand2.
7036 return false;
7037
7038 case ImplicitConversionSequence::Indistinguishable:
7039 // Do nothing.
7040 break;
7041 }
7042 }
7043
Mike Stump11289f42009-09-09 15:08:12 +00007044 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007045 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007046 if (HasBetterConversion)
7047 return true;
7048
Mike Stump11289f42009-09-09 15:08:12 +00007049 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007050 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007051 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007052 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7053 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007054
7055 // -- F1 and F2 are function template specializations, and the function
7056 // template for F1 is more specialized than the template for F2
7057 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007058 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007059 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007060 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007061 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007062 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7063 Cand2.Function->getPrimaryTemplate(),
7064 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007065 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007066 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007067 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007068 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007070
Douglas Gregora1f013e2008-11-07 22:36:19 +00007071 // -- the context is an initialization by user-defined conversion
7072 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7073 // from the return type of F1 to the destination type (i.e.,
7074 // the type of the entity being initialized) is a better
7075 // conversion sequence than the standard conversion sequence
7076 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007077 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007078 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007079 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00007080 switch (CompareStandardConversionSequences(S,
7081 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007082 Cand2.FinalConversion)) {
7083 case ImplicitConversionSequence::Better:
7084 // Cand1 has a better conversion sequence.
7085 return true;
7086
7087 case ImplicitConversionSequence::Worse:
7088 // Cand1 can't be better than Cand2.
7089 return false;
7090
7091 case ImplicitConversionSequence::Indistinguishable:
7092 // Do nothing
7093 break;
7094 }
7095 }
7096
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007097 return false;
7098}
7099
Mike Stump11289f42009-09-09 15:08:12 +00007100/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007101/// within an overload candidate set.
7102///
7103/// \param CandidateSet the set of candidate functions.
7104///
7105/// \param Loc the location of the function name (or operator symbol) for
7106/// which overload resolution occurs.
7107///
Mike Stump11289f42009-09-09 15:08:12 +00007108/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007109/// function, Best points to the candidate function found.
7110///
7111/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007112OverloadingResult
7113OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007114 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007115 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007116 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007117 Best = end();
7118 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7119 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007120 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007121 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007122 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007123 }
7124
7125 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007126 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007127 return OR_No_Viable_Function;
7128
7129 // Make sure that this function is better than every other viable
7130 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007131 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007132 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007133 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007134 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007135 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007136 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007137 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007138 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007139 }
Mike Stump11289f42009-09-09 15:08:12 +00007140
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007141 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007142 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007143 (Best->Function->isDeleted() ||
7144 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007145 return OR_Deleted;
7146
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007147 return OR_Success;
7148}
7149
John McCall53262c92010-01-12 02:15:36 +00007150namespace {
7151
7152enum OverloadCandidateKind {
7153 oc_function,
7154 oc_method,
7155 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007156 oc_function_template,
7157 oc_method_template,
7158 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007159 oc_implicit_default_constructor,
7160 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007161 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007162 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007163 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007164 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007165};
7166
John McCalle1ac8d12010-01-13 00:25:19 +00007167OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7168 FunctionDecl *Fn,
7169 std::string &Description) {
7170 bool isTemplate = false;
7171
7172 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7173 isTemplate = true;
7174 Description = S.getTemplateArgumentBindingsText(
7175 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7176 }
John McCallfd0b2f82010-01-06 09:43:14 +00007177
7178 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007179 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007180 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007181
Sebastian Redl08905022011-02-05 19:23:19 +00007182 if (Ctor->getInheritedConstructor())
7183 return oc_implicit_inherited_constructor;
7184
Alexis Hunt119c10e2011-05-25 23:16:36 +00007185 if (Ctor->isDefaultConstructor())
7186 return oc_implicit_default_constructor;
7187
7188 if (Ctor->isMoveConstructor())
7189 return oc_implicit_move_constructor;
7190
7191 assert(Ctor->isCopyConstructor() &&
7192 "unexpected sort of implicit constructor");
7193 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007194 }
7195
7196 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7197 // This actually gets spelled 'candidate function' for now, but
7198 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007199 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007200 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007201
Alexis Hunt119c10e2011-05-25 23:16:36 +00007202 if (Meth->isMoveAssignmentOperator())
7203 return oc_implicit_move_assignment;
7204
Douglas Gregorec3bec02010-09-27 22:37:28 +00007205 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007206 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007207 return oc_implicit_copy_assignment;
7208 }
7209
John McCalle1ac8d12010-01-13 00:25:19 +00007210 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007211}
7212
Sebastian Redl08905022011-02-05 19:23:19 +00007213void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7214 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7215 if (!Ctor) return;
7216
7217 Ctor = Ctor->getInheritedConstructor();
7218 if (!Ctor) return;
7219
7220 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7221}
7222
John McCall53262c92010-01-12 02:15:36 +00007223} // end anonymous namespace
7224
7225// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007226void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007227 std::string FnDesc;
7228 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007229 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7230 << (unsigned) K << FnDesc;
7231 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7232 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007233 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007234}
7235
Douglas Gregorb491ed32011-02-19 21:32:49 +00007236//Notes the location of all overload candidates designated through
7237// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007238void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007239 assert(OverloadedExpr->getType() == Context.OverloadTy);
7240
7241 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7242 OverloadExpr *OvlExpr = Ovl.Expression;
7243
7244 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7245 IEnd = OvlExpr->decls_end();
7246 I != IEnd; ++I) {
7247 if (FunctionTemplateDecl *FunTmpl =
7248 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007249 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007250 } else if (FunctionDecl *Fun
7251 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007252 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007253 }
7254 }
7255}
7256
John McCall0d1da222010-01-12 00:44:57 +00007257/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7258/// "lead" diagnostic; it will be given two arguments, the source and
7259/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007260void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7261 Sema &S,
7262 SourceLocation CaretLoc,
7263 const PartialDiagnostic &PDiag) const {
7264 S.Diag(CaretLoc, PDiag)
7265 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007266 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007267 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7268 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007269 }
John McCall12f97bc2010-01-08 04:41:39 +00007270}
7271
John McCall0d1da222010-01-12 00:44:57 +00007272namespace {
7273
John McCall6a61b522010-01-13 09:16:55 +00007274void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7275 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7276 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007277 assert(Cand->Function && "for now, candidate must be a function");
7278 FunctionDecl *Fn = Cand->Function;
7279
7280 // There's a conversion slot for the object argument if this is a
7281 // non-constructor method. Note that 'I' corresponds the
7282 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007283 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007284 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007285 if (I == 0)
7286 isObjectArgument = true;
7287 else
7288 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007289 }
7290
John McCalle1ac8d12010-01-13 00:25:19 +00007291 std::string FnDesc;
7292 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7293
John McCall6a61b522010-01-13 09:16:55 +00007294 Expr *FromExpr = Conv.Bad.FromExpr;
7295 QualType FromTy = Conv.Bad.getFromType();
7296 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007297
John McCallfb7ad0f2010-02-02 02:42:52 +00007298 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007299 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007300 Expr *E = FromExpr->IgnoreParens();
7301 if (isa<UnaryOperator>(E))
7302 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007303 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007304
7305 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7306 << (unsigned) FnKind << FnDesc
7307 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7308 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007309 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007310 return;
7311 }
7312
John McCall6d174642010-01-23 08:10:49 +00007313 // Do some hand-waving analysis to see if the non-viability is due
7314 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007315 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7316 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7317 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7318 CToTy = RT->getPointeeType();
7319 else {
7320 // TODO: detect and diagnose the full richness of const mismatches.
7321 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7322 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7323 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7324 }
7325
7326 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7327 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7328 // It is dumb that we have to do this here.
7329 while (isa<ArrayType>(CFromTy))
7330 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7331 while (isa<ArrayType>(CToTy))
7332 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7333
7334 Qualifiers FromQs = CFromTy.getQualifiers();
7335 Qualifiers ToQs = CToTy.getQualifiers();
7336
7337 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7338 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7339 << (unsigned) FnKind << FnDesc
7340 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7341 << FromTy
7342 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7343 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007344 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007345 return;
7346 }
7347
John McCall31168b02011-06-15 23:02:42 +00007348 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007349 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007350 << (unsigned) FnKind << FnDesc
7351 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7352 << FromTy
7353 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7354 << (unsigned) isObjectArgument << I+1;
7355 MaybeEmitInheritedConstructorNote(S, Fn);
7356 return;
7357 }
7358
Douglas Gregoraec25842011-04-26 23:16:46 +00007359 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7360 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7361 << (unsigned) FnKind << FnDesc
7362 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7363 << FromTy
7364 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7365 << (unsigned) isObjectArgument << I+1;
7366 MaybeEmitInheritedConstructorNote(S, Fn);
7367 return;
7368 }
7369
John McCall47000992010-01-14 03:28:57 +00007370 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7371 assert(CVR && "unexpected qualifiers mismatch");
7372
7373 if (isObjectArgument) {
7374 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7375 << (unsigned) FnKind << FnDesc
7376 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7377 << FromTy << (CVR - 1);
7378 } else {
7379 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7380 << (unsigned) FnKind << FnDesc
7381 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7382 << FromTy << (CVR - 1) << I+1;
7383 }
Sebastian Redl08905022011-02-05 19:23:19 +00007384 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007385 return;
7386 }
7387
Sebastian Redla72462c2011-09-24 17:48:32 +00007388 // Special diagnostic for failure to convert an initializer list, since
7389 // telling the user that it has type void is not useful.
7390 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7391 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7392 << (unsigned) FnKind << FnDesc
7393 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7394 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7395 MaybeEmitInheritedConstructorNote(S, Fn);
7396 return;
7397 }
7398
John McCall6d174642010-01-23 08:10:49 +00007399 // Diagnose references or pointers to incomplete types differently,
7400 // since it's far from impossible that the incompleteness triggered
7401 // the failure.
7402 QualType TempFromTy = FromTy.getNonReferenceType();
7403 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7404 TempFromTy = PTy->getPointeeType();
7405 if (TempFromTy->isIncompleteType()) {
7406 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7407 << (unsigned) FnKind << FnDesc
7408 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7409 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007410 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007411 return;
7412 }
7413
Douglas Gregor56f2e342010-06-30 23:01:39 +00007414 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007415 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007416 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7417 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7418 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7419 FromPtrTy->getPointeeType()) &&
7420 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7421 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007422 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007423 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007424 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007425 }
7426 } else if (const ObjCObjectPointerType *FromPtrTy
7427 = FromTy->getAs<ObjCObjectPointerType>()) {
7428 if (const ObjCObjectPointerType *ToPtrTy
7429 = ToTy->getAs<ObjCObjectPointerType>())
7430 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7431 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7432 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7433 FromPtrTy->getPointeeType()) &&
7434 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007435 BaseToDerivedConversion = 2;
7436 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7437 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7438 !FromTy->isIncompleteType() &&
7439 !ToRefTy->getPointeeType()->isIncompleteType() &&
7440 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7441 BaseToDerivedConversion = 3;
7442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007443
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007444 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007445 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007446 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007447 << (unsigned) FnKind << FnDesc
7448 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007449 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007450 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007451 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007452 return;
7453 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007454
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007455 if (isa<ObjCObjectPointerType>(CFromTy) &&
7456 isa<PointerType>(CToTy)) {
7457 Qualifiers FromQs = CFromTy.getQualifiers();
7458 Qualifiers ToQs = CToTy.getQualifiers();
7459 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7460 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7461 << (unsigned) FnKind << FnDesc
7462 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7463 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7464 MaybeEmitInheritedConstructorNote(S, Fn);
7465 return;
7466 }
7467 }
7468
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007469 // Emit the generic diagnostic and, optionally, add the hints to it.
7470 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7471 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007472 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007473 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7474 << (unsigned) (Cand->Fix.Kind);
7475
7476 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007477 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007478 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7479 HI != HE; ++HI)
7480 FDiag << *HI;
7481 S.Diag(Fn->getLocation(), FDiag);
7482
Sebastian Redl08905022011-02-05 19:23:19 +00007483 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007484}
7485
7486void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7487 unsigned NumFormalArgs) {
7488 // TODO: treat calls to a missing default constructor as a special case
7489
7490 FunctionDecl *Fn = Cand->Function;
7491 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7492
7493 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007494
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007495 // With invalid overloaded operators, it's possible that we think we
7496 // have an arity mismatch when it fact it looks like we have the
7497 // right number of arguments, because only overloaded operators have
7498 // the weird behavior of overloading member and non-member functions.
7499 // Just don't report anything.
7500 if (Fn->isInvalidDecl() &&
7501 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7502 return;
7503
John McCall6a61b522010-01-13 09:16:55 +00007504 // at least / at most / exactly
7505 unsigned mode, modeCount;
7506 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007507 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7508 (Cand->FailureKind == ovl_fail_bad_deduction &&
7509 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007510 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007511 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007512 mode = 0; // "at least"
7513 else
7514 mode = 2; // "exactly"
7515 modeCount = MinParams;
7516 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007517 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7518 (Cand->FailureKind == ovl_fail_bad_deduction &&
7519 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007520 if (MinParams != FnTy->getNumArgs())
7521 mode = 1; // "at most"
7522 else
7523 mode = 2; // "exactly"
7524 modeCount = FnTy->getNumArgs();
7525 }
7526
7527 std::string Description;
7528 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7529
7530 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007531 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007532 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007533 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007534}
7535
John McCall8b9ed552010-02-01 18:53:26 +00007536/// Diagnose a failed template-argument deduction.
7537void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7538 Expr **Args, unsigned NumArgs) {
7539 FunctionDecl *Fn = Cand->Function; // pattern
7540
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007541 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007542 NamedDecl *ParamD;
7543 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7544 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7545 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007546 switch (Cand->DeductionFailure.Result) {
7547 case Sema::TDK_Success:
7548 llvm_unreachable("TDK_success while diagnosing bad deduction");
7549
7550 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007551 assert(ParamD && "no parameter found for incomplete deduction result");
7552 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7553 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007554 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007555 return;
7556 }
7557
John McCall42d7d192010-08-05 09:05:08 +00007558 case Sema::TDK_Underqualified: {
7559 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7560 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7561
7562 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7563
7564 // Param will have been canonicalized, but it should just be a
7565 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007566 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007567 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007568 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007569 assert(S.Context.hasSameType(Param, NonCanonParam));
7570
7571 // Arg has also been canonicalized, but there's nothing we can do
7572 // about that. It also doesn't matter as much, because it won't
7573 // have any template parameters in it (because deduction isn't
7574 // done on dependent types).
7575 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7576
7577 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7578 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007579 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007580 return;
7581 }
7582
7583 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007584 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007585 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007586 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007587 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007588 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007589 which = 1;
7590 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007591 which = 2;
7592 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007593
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007594 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007595 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007596 << *Cand->DeductionFailure.getFirstArg()
7597 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007598 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007599 return;
7600 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007601
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007602 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007603 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007604 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007605 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007606 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7607 << ParamD->getDeclName();
7608 else {
7609 int index = 0;
7610 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7611 index = TTP->getIndex();
7612 else if (NonTypeTemplateParmDecl *NTTP
7613 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7614 index = NTTP->getIndex();
7615 else
7616 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007617 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007618 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7619 << (index + 1);
7620 }
Sebastian Redl08905022011-02-05 19:23:19 +00007621 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007622 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007623
Douglas Gregor02eb4832010-05-08 18:13:28 +00007624 case Sema::TDK_TooManyArguments:
7625 case Sema::TDK_TooFewArguments:
7626 DiagnoseArityMismatch(S, Cand, NumArgs);
7627 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007628
7629 case Sema::TDK_InstantiationDepth:
7630 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007631 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007632 return;
7633
7634 case Sema::TDK_SubstitutionFailure: {
7635 std::string ArgString;
7636 if (TemplateArgumentList *Args
7637 = Cand->DeductionFailure.getTemplateArgumentList())
7638 ArgString = S.getTemplateArgumentBindingsText(
7639 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7640 *Args);
7641 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7642 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007643 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007644 return;
7645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007646
John McCall8b9ed552010-02-01 18:53:26 +00007647 // TODO: diagnose these individually, then kill off
7648 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007649 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007650 case Sema::TDK_FailedOverloadResolution:
7651 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007652 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007653 return;
7654 }
7655}
7656
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007657/// CUDA: diagnose an invalid call across targets.
7658void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7659 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7660 FunctionDecl *Callee = Cand->Function;
7661
7662 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7663 CalleeTarget = S.IdentifyCUDATarget(Callee);
7664
7665 std::string FnDesc;
7666 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7667
7668 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7669 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7670}
7671
John McCall8b9ed552010-02-01 18:53:26 +00007672/// Generates a 'note' diagnostic for an overload candidate. We've
7673/// already generated a primary error at the call site.
7674///
7675/// It really does need to be a single diagnostic with its caret
7676/// pointed at the candidate declaration. Yes, this creates some
7677/// major challenges of technical writing. Yes, this makes pointing
7678/// out problems with specific arguments quite awkward. It's still
7679/// better than generating twenty screens of text for every failed
7680/// overload.
7681///
7682/// It would be great to be able to express per-candidate problems
7683/// more richly for those diagnostic clients that cared, but we'd
7684/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007685void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7686 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007687 FunctionDecl *Fn = Cand->Function;
7688
John McCall12f97bc2010-01-08 04:41:39 +00007689 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007690 if (Cand->Viable && (Fn->isDeleted() ||
7691 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007692 std::string FnDesc;
7693 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007694
7695 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007696 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007697 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007698 return;
John McCall12f97bc2010-01-08 04:41:39 +00007699 }
7700
John McCalle1ac8d12010-01-13 00:25:19 +00007701 // We don't really have anything else to say about viable candidates.
7702 if (Cand->Viable) {
7703 S.NoteOverloadCandidate(Fn);
7704 return;
7705 }
John McCall0d1da222010-01-12 00:44:57 +00007706
John McCall6a61b522010-01-13 09:16:55 +00007707 switch (Cand->FailureKind) {
7708 case ovl_fail_too_many_arguments:
7709 case ovl_fail_too_few_arguments:
7710 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007711
John McCall6a61b522010-01-13 09:16:55 +00007712 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007713 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7714
John McCallfe796dd2010-01-23 05:17:32 +00007715 case ovl_fail_trivial_conversion:
7716 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007717 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007718 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007719
John McCall65eb8792010-02-25 01:37:24 +00007720 case ovl_fail_bad_conversion: {
7721 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007722 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007723 if (Cand->Conversions[I].isBad())
7724 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007725
John McCall6a61b522010-01-13 09:16:55 +00007726 // FIXME: this currently happens when we're called from SemaInit
7727 // when user-conversion overload fails. Figure out how to handle
7728 // those conditions and diagnose them well.
7729 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007730 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007731
7732 case ovl_fail_bad_target:
7733 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007734 }
John McCalld3224162010-01-08 00:58:21 +00007735}
7736
7737void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7738 // Desugar the type of the surrogate down to a function type,
7739 // retaining as many typedefs as possible while still showing
7740 // the function type (and, therefore, its parameter types).
7741 QualType FnType = Cand->Surrogate->getConversionType();
7742 bool isLValueReference = false;
7743 bool isRValueReference = false;
7744 bool isPointer = false;
7745 if (const LValueReferenceType *FnTypeRef =
7746 FnType->getAs<LValueReferenceType>()) {
7747 FnType = FnTypeRef->getPointeeType();
7748 isLValueReference = true;
7749 } else if (const RValueReferenceType *FnTypeRef =
7750 FnType->getAs<RValueReferenceType>()) {
7751 FnType = FnTypeRef->getPointeeType();
7752 isRValueReference = true;
7753 }
7754 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7755 FnType = FnTypePtr->getPointeeType();
7756 isPointer = true;
7757 }
7758 // Desugar down to a function type.
7759 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7760 // Reconstruct the pointer/reference as appropriate.
7761 if (isPointer) FnType = S.Context.getPointerType(FnType);
7762 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7763 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7764
7765 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7766 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007767 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007768}
7769
7770void NoteBuiltinOperatorCandidate(Sema &S,
7771 const char *Opc,
7772 SourceLocation OpLoc,
7773 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00007774 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00007775 std::string TypeStr("operator");
7776 TypeStr += Opc;
7777 TypeStr += "(";
7778 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00007779 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00007780 TypeStr += ")";
7781 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7782 } else {
7783 TypeStr += ", ";
7784 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7785 TypeStr += ")";
7786 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7787 }
7788}
7789
7790void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7791 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00007792 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00007793 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7794 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007795 if (ICS.isBad()) break; // all meaningless after first invalid
7796 if (!ICS.isAmbiguous()) continue;
7797
John McCall5c32be02010-08-24 20:38:10 +00007798 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007799 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007800 }
7801}
7802
John McCall3712d9e2010-01-15 23:32:50 +00007803SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7804 if (Cand->Function)
7805 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007806 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007807 return Cand->Surrogate->getLocation();
7808 return SourceLocation();
7809}
7810
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007811static unsigned
7812RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007813 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007814 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007815 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007816
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007817 case Sema::TDK_Incomplete:
7818 return 1;
7819
7820 case Sema::TDK_Underqualified:
7821 case Sema::TDK_Inconsistent:
7822 return 2;
7823
7824 case Sema::TDK_SubstitutionFailure:
7825 case Sema::TDK_NonDeducedMismatch:
7826 return 3;
7827
7828 case Sema::TDK_InstantiationDepth:
7829 case Sema::TDK_FailedOverloadResolution:
7830 return 4;
7831
7832 case Sema::TDK_InvalidExplicitArguments:
7833 return 5;
7834
7835 case Sema::TDK_TooManyArguments:
7836 case Sema::TDK_TooFewArguments:
7837 return 6;
7838 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007839 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007840}
7841
John McCallad2587a2010-01-12 00:48:53 +00007842struct CompareOverloadCandidatesForDisplay {
7843 Sema &S;
7844 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007845
7846 bool operator()(const OverloadCandidate *L,
7847 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007848 // Fast-path this check.
7849 if (L == R) return false;
7850
John McCall12f97bc2010-01-08 04:41:39 +00007851 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007852 if (L->Viable) {
7853 if (!R->Viable) return true;
7854
7855 // TODO: introduce a tri-valued comparison for overload
7856 // candidates. Would be more worthwhile if we had a sort
7857 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007858 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7859 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007860 } else if (R->Viable)
7861 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007862
John McCall3712d9e2010-01-15 23:32:50 +00007863 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007864
John McCall3712d9e2010-01-15 23:32:50 +00007865 // Criteria by which we can sort non-viable candidates:
7866 if (!L->Viable) {
7867 // 1. Arity mismatches come after other candidates.
7868 if (L->FailureKind == ovl_fail_too_many_arguments ||
7869 L->FailureKind == ovl_fail_too_few_arguments)
7870 return false;
7871 if (R->FailureKind == ovl_fail_too_many_arguments ||
7872 R->FailureKind == ovl_fail_too_few_arguments)
7873 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007874
John McCallfe796dd2010-01-23 05:17:32 +00007875 // 2. Bad conversions come first and are ordered by the number
7876 // of bad conversions and quality of good conversions.
7877 if (L->FailureKind == ovl_fail_bad_conversion) {
7878 if (R->FailureKind != ovl_fail_bad_conversion)
7879 return true;
7880
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007881 // The conversion that can be fixed with a smaller number of changes,
7882 // comes first.
7883 unsigned numLFixes = L->Fix.NumConversionsFixed;
7884 unsigned numRFixes = R->Fix.NumConversionsFixed;
7885 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7886 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007887 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007888 if (numLFixes < numRFixes)
7889 return true;
7890 else
7891 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007892 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007893
John McCallfe796dd2010-01-23 05:17:32 +00007894 // If there's any ordering between the defined conversions...
7895 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00007896 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00007897
7898 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007899 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007900 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007901 switch (CompareImplicitConversionSequences(S,
7902 L->Conversions[I],
7903 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007904 case ImplicitConversionSequence::Better:
7905 leftBetter++;
7906 break;
7907
7908 case ImplicitConversionSequence::Worse:
7909 leftBetter--;
7910 break;
7911
7912 case ImplicitConversionSequence::Indistinguishable:
7913 break;
7914 }
7915 }
7916 if (leftBetter > 0) return true;
7917 if (leftBetter < 0) return false;
7918
7919 } else if (R->FailureKind == ovl_fail_bad_conversion)
7920 return false;
7921
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007922 if (L->FailureKind == ovl_fail_bad_deduction) {
7923 if (R->FailureKind != ovl_fail_bad_deduction)
7924 return true;
7925
7926 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7927 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007928 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007929 } else if (R->FailureKind == ovl_fail_bad_deduction)
7930 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007931
John McCall3712d9e2010-01-15 23:32:50 +00007932 // TODO: others?
7933 }
7934
7935 // Sort everything else by location.
7936 SourceLocation LLoc = GetLocationForCandidate(L);
7937 SourceLocation RLoc = GetLocationForCandidate(R);
7938
7939 // Put candidates without locations (e.g. builtins) at the end.
7940 if (LLoc.isInvalid()) return false;
7941 if (RLoc.isInvalid()) return true;
7942
7943 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007944 }
7945};
7946
John McCallfe796dd2010-01-23 05:17:32 +00007947/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007948/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007949void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7950 Expr **Args, unsigned NumArgs) {
7951 assert(!Cand->Viable);
7952
7953 // Don't do anything on failures other than bad conversion.
7954 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7955
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007956 // We only want the FixIts if all the arguments can be corrected.
7957 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007958 // Use a implicit copy initialization to check conversion fixes.
7959 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007960
John McCallfe796dd2010-01-23 05:17:32 +00007961 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007962 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00007963 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00007964 while (true) {
7965 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7966 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007967 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007968 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007969 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007970 }
John McCallfe796dd2010-01-23 05:17:32 +00007971 }
7972
7973 if (ConvIdx == ConvCount)
7974 return;
7975
John McCall65eb8792010-02-25 01:37:24 +00007976 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7977 "remaining conversion is initialized?");
7978
Douglas Gregoradc7a702010-04-16 17:45:54 +00007979 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007980 // operation somehow.
7981 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007982
7983 const FunctionProtoType* Proto;
7984 unsigned ArgIdx = ConvIdx;
7985
7986 if (Cand->IsSurrogate) {
7987 QualType ConvType
7988 = Cand->Surrogate->getConversionType().getNonReferenceType();
7989 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7990 ConvType = ConvPtrType->getPointeeType();
7991 Proto = ConvType->getAs<FunctionProtoType>();
7992 ArgIdx--;
7993 } else if (Cand->Function) {
7994 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7995 if (isa<CXXMethodDecl>(Cand->Function) &&
7996 !isa<CXXConstructorDecl>(Cand->Function))
7997 ArgIdx--;
7998 } else {
7999 // Builtin binary operator with a bad first conversion.
8000 assert(ConvCount <= 3);
8001 for (; ConvIdx != ConvCount; ++ConvIdx)
8002 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008003 = TryCopyInitialization(S, Args[ConvIdx],
8004 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008005 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008006 /*InOverloadResolution*/ true,
8007 /*AllowObjCWritebackConversion=*/
8008 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008009 return;
8010 }
8011
8012 // Fill in the rest of the conversions.
8013 unsigned NumArgsInProto = Proto->getNumArgs();
8014 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008015 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008016 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008017 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008018 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008019 /*InOverloadResolution=*/true,
8020 /*AllowObjCWritebackConversion=*/
8021 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008022 // Store the FixIt in the candidate if it exists.
8023 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008024 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008025 }
John McCallfe796dd2010-01-23 05:17:32 +00008026 else
8027 Cand->Conversions[ConvIdx].setEllipsis();
8028 }
8029}
8030
John McCalld3224162010-01-08 00:58:21 +00008031} // end anonymous namespace
8032
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008033/// PrintOverloadCandidates - When overload resolution fails, prints
8034/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008035/// set.
John McCall5c32be02010-08-24 20:38:10 +00008036void OverloadCandidateSet::NoteCandidates(Sema &S,
8037 OverloadCandidateDisplayKind OCD,
8038 Expr **Args, unsigned NumArgs,
8039 const char *Opc,
8040 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008041 // Sort the candidates by viability and position. Sorting directly would
8042 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008043 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008044 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8045 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008046 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008047 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008048 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008049 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008050 if (Cand->Function || Cand->IsSurrogate)
8051 Cands.push_back(Cand);
8052 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8053 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008054 }
8055 }
8056
John McCallad2587a2010-01-12 00:48:53 +00008057 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008058 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008059
John McCall0d1da222010-01-12 00:44:57 +00008060 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008061
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008062 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008063 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8064 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008065 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008066 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8067 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008068
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008069 // Set an arbitrary limit on the number of candidate functions we'll spam
8070 // the user with. FIXME: This limit should depend on details of the
8071 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008072 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008073 break;
8074 }
8075 ++CandsShown;
8076
John McCalld3224162010-01-08 00:58:21 +00008077 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008078 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008079 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008080 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008081 else {
8082 assert(Cand->Viable &&
8083 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008084 // Generally we only see ambiguities including viable builtin
8085 // operators if overload resolution got screwed up by an
8086 // ambiguous user-defined conversion.
8087 //
8088 // FIXME: It's quite possible for different conversions to see
8089 // different ambiguities, though.
8090 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008091 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008092 ReportedAmbiguousConversions = true;
8093 }
John McCalld3224162010-01-08 00:58:21 +00008094
John McCall0d1da222010-01-12 00:44:57 +00008095 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008096 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008097 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008098 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008099
8100 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008101 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008102}
8103
Douglas Gregorb491ed32011-02-19 21:32:49 +00008104// [PossiblyAFunctionType] --> [Return]
8105// NonFunctionType --> NonFunctionType
8106// R (A) --> R(A)
8107// R (*)(A) --> R (A)
8108// R (&)(A) --> R (A)
8109// R (S::*)(A) --> R (A)
8110QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8111 QualType Ret = PossiblyAFunctionType;
8112 if (const PointerType *ToTypePtr =
8113 PossiblyAFunctionType->getAs<PointerType>())
8114 Ret = ToTypePtr->getPointeeType();
8115 else if (const ReferenceType *ToTypeRef =
8116 PossiblyAFunctionType->getAs<ReferenceType>())
8117 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008118 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008119 PossiblyAFunctionType->getAs<MemberPointerType>())
8120 Ret = MemTypePtr->getPointeeType();
8121 Ret =
8122 Context.getCanonicalType(Ret).getUnqualifiedType();
8123 return Ret;
8124}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008125
Douglas Gregorb491ed32011-02-19 21:32:49 +00008126// A helper class to help with address of function resolution
8127// - allows us to avoid passing around all those ugly parameters
8128class AddressOfFunctionResolver
8129{
8130 Sema& S;
8131 Expr* SourceExpr;
8132 const QualType& TargetType;
8133 QualType TargetFunctionType; // Extracted function type from target type
8134
8135 bool Complain;
8136 //DeclAccessPair& ResultFunctionAccessPair;
8137 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008138
Douglas Gregorb491ed32011-02-19 21:32:49 +00008139 bool TargetTypeIsNonStaticMemberFunction;
8140 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008141
Douglas Gregorb491ed32011-02-19 21:32:49 +00008142 OverloadExpr::FindResult OvlExprInfo;
8143 OverloadExpr *OvlExpr;
8144 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008145 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008146
Douglas Gregorb491ed32011-02-19 21:32:49 +00008147public:
8148 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8149 const QualType& TargetType, bool Complain)
8150 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8151 Complain(Complain), Context(S.getASTContext()),
8152 TargetTypeIsNonStaticMemberFunction(
8153 !!TargetType->getAs<MemberPointerType>()),
8154 FoundNonTemplateFunction(false),
8155 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8156 OvlExpr(OvlExprInfo.Expression)
8157 {
8158 ExtractUnqualifiedFunctionTypeFromTargetType();
8159
8160 if (!TargetFunctionType->isFunctionType()) {
8161 if (OvlExpr->hasExplicitTemplateArgs()) {
8162 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008163 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008164 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008165
8166 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8167 if (!Method->isStatic()) {
8168 // If the target type is a non-function type and the function
8169 // found is a non-static member function, pretend as if that was
8170 // the target, it's the only possible type to end up with.
8171 TargetTypeIsNonStaticMemberFunction = true;
8172
8173 // And skip adding the function if its not in the proper form.
8174 // We'll diagnose this due to an empty set of functions.
8175 if (!OvlExprInfo.HasFormOfMemberPointer)
8176 return;
8177 }
8178 }
8179
Douglas Gregorb491ed32011-02-19 21:32:49 +00008180 Matches.push_back(std::make_pair(dap,Fn));
8181 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008182 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008183 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008184 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008185
8186 if (OvlExpr->hasExplicitTemplateArgs())
8187 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008188
Douglas Gregorb491ed32011-02-19 21:32:49 +00008189 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8190 // C++ [over.over]p4:
8191 // If more than one function is selected, [...]
8192 if (Matches.size() > 1) {
8193 if (FoundNonTemplateFunction)
8194 EliminateAllTemplateMatches();
8195 else
8196 EliminateAllExceptMostSpecializedTemplate();
8197 }
8198 }
8199 }
8200
8201private:
8202 bool isTargetTypeAFunction() const {
8203 return TargetFunctionType->isFunctionType();
8204 }
8205
8206 // [ToType] [Return]
8207
8208 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8209 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8210 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8211 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8212 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8213 }
8214
8215 // return true if any matching specializations were found
8216 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8217 const DeclAccessPair& CurAccessFunPair) {
8218 if (CXXMethodDecl *Method
8219 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8220 // Skip non-static function templates when converting to pointer, and
8221 // static when converting to member pointer.
8222 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8223 return false;
8224 }
8225 else if (TargetTypeIsNonStaticMemberFunction)
8226 return false;
8227
8228 // C++ [over.over]p2:
8229 // If the name is a function template, template argument deduction is
8230 // done (14.8.2.2), and if the argument deduction succeeds, the
8231 // resulting template argument list is used to generate a single
8232 // function template specialization, which is added to the set of
8233 // overloaded functions considered.
8234 FunctionDecl *Specialization = 0;
8235 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8236 if (Sema::TemplateDeductionResult Result
8237 = S.DeduceTemplateArguments(FunctionTemplate,
8238 &OvlExplicitTemplateArgs,
8239 TargetFunctionType, Specialization,
8240 Info)) {
8241 // FIXME: make a note of the failed deduction for diagnostics.
8242 (void)Result;
8243 return false;
8244 }
8245
8246 // Template argument deduction ensures that we have an exact match.
8247 // This function template specicalization works.
8248 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8249 assert(TargetFunctionType
8250 == Context.getCanonicalType(Specialization->getType()));
8251 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8252 return true;
8253 }
8254
8255 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8256 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008257 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008258 // Skip non-static functions when converting to pointer, and static
8259 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008260 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8261 return false;
8262 }
8263 else if (TargetTypeIsNonStaticMemberFunction)
8264 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008265
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008266 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008267 if (S.getLangOptions().CUDA)
8268 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8269 if (S.CheckCUDATarget(Caller, FunDecl))
8270 return false;
8271
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008272 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008273 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8274 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008275 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8276 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008277 Matches.push_back(std::make_pair(CurAccessFunPair,
8278 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008279 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008280 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008281 }
Mike Stump11289f42009-09-09 15:08:12 +00008282 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008283
8284 return false;
8285 }
8286
8287 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8288 bool Ret = false;
8289
8290 // If the overload expression doesn't have the form of a pointer to
8291 // member, don't try to convert it to a pointer-to-member type.
8292 if (IsInvalidFormOfPointerToMemberFunction())
8293 return false;
8294
8295 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8296 E = OvlExpr->decls_end();
8297 I != E; ++I) {
8298 // Look through any using declarations to find the underlying function.
8299 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8300
8301 // C++ [over.over]p3:
8302 // Non-member functions and static member functions match
8303 // targets of type "pointer-to-function" or "reference-to-function."
8304 // Nonstatic member functions match targets of
8305 // type "pointer-to-member-function."
8306 // Note that according to DR 247, the containing class does not matter.
8307 if (FunctionTemplateDecl *FunctionTemplate
8308 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8309 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8310 Ret = true;
8311 }
8312 // If we have explicit template arguments supplied, skip non-templates.
8313 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8314 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8315 Ret = true;
8316 }
8317 assert(Ret || Matches.empty());
8318 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008319 }
8320
Douglas Gregorb491ed32011-02-19 21:32:49 +00008321 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008322 // [...] and any given function template specialization F1 is
8323 // eliminated if the set contains a second function template
8324 // specialization whose function template is more specialized
8325 // than the function template of F1 according to the partial
8326 // ordering rules of 14.5.5.2.
8327
8328 // The algorithm specified above is quadratic. We instead use a
8329 // two-pass algorithm (similar to the one used to identify the
8330 // best viable function in an overload set) that identifies the
8331 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008332
8333 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8334 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8335 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008336
John McCall58cc69d2010-01-27 01:50:18 +00008337 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008338 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8339 TPOC_Other, 0, SourceExpr->getLocStart(),
8340 S.PDiag(),
8341 S.PDiag(diag::err_addr_ovl_ambiguous)
8342 << Matches[0].second->getDeclName(),
8343 S.PDiag(diag::note_ovl_candidate)
8344 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008345 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008346
Douglas Gregorb491ed32011-02-19 21:32:49 +00008347 if (Result != MatchesCopy.end()) {
8348 // Make it the first and only element
8349 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8350 Matches[0].second = cast<FunctionDecl>(*Result);
8351 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008352 }
8353 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008354
Douglas Gregorb491ed32011-02-19 21:32:49 +00008355 void EliminateAllTemplateMatches() {
8356 // [...] any function template specializations in the set are
8357 // eliminated if the set also contains a non-template function, [...]
8358 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8359 if (Matches[I].second->getPrimaryTemplate() == 0)
8360 ++I;
8361 else {
8362 Matches[I] = Matches[--N];
8363 Matches.set_size(N);
8364 }
8365 }
8366 }
8367
8368public:
8369 void ComplainNoMatchesFound() const {
8370 assert(Matches.empty());
8371 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8372 << OvlExpr->getName() << TargetFunctionType
8373 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008374 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008375 }
8376
8377 bool IsInvalidFormOfPointerToMemberFunction() const {
8378 return TargetTypeIsNonStaticMemberFunction &&
8379 !OvlExprInfo.HasFormOfMemberPointer;
8380 }
8381
8382 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8383 // TODO: Should we condition this on whether any functions might
8384 // have matched, or is it more appropriate to do that in callers?
8385 // TODO: a fixit wouldn't hurt.
8386 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8387 << TargetType << OvlExpr->getSourceRange();
8388 }
8389
8390 void ComplainOfInvalidConversion() const {
8391 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8392 << OvlExpr->getName() << TargetType;
8393 }
8394
8395 void ComplainMultipleMatchesFound() const {
8396 assert(Matches.size() > 1);
8397 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8398 << OvlExpr->getName()
8399 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008400 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008401 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008402
8403 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8404
Douglas Gregorb491ed32011-02-19 21:32:49 +00008405 int getNumMatches() const { return Matches.size(); }
8406
8407 FunctionDecl* getMatchingFunctionDecl() const {
8408 if (Matches.size() != 1) return 0;
8409 return Matches[0].second;
8410 }
8411
8412 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8413 if (Matches.size() != 1) return 0;
8414 return &Matches[0].first;
8415 }
8416};
8417
8418/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8419/// an overloaded function (C++ [over.over]), where @p From is an
8420/// expression with overloaded function type and @p ToType is the type
8421/// we're trying to resolve to. For example:
8422///
8423/// @code
8424/// int f(double);
8425/// int f(int);
8426///
8427/// int (*pfd)(double) = f; // selects f(double)
8428/// @endcode
8429///
8430/// This routine returns the resulting FunctionDecl if it could be
8431/// resolved, and NULL otherwise. When @p Complain is true, this
8432/// routine will emit diagnostics if there is an error.
8433FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008434Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8435 QualType TargetType,
8436 bool Complain,
8437 DeclAccessPair &FoundResult,
8438 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008439 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008440
8441 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8442 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008443 int NumMatches = Resolver.getNumMatches();
8444 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008445 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008446 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8447 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8448 else
8449 Resolver.ComplainNoMatchesFound();
8450 }
8451 else if (NumMatches > 1 && Complain)
8452 Resolver.ComplainMultipleMatchesFound();
8453 else if (NumMatches == 1) {
8454 Fn = Resolver.getMatchingFunctionDecl();
8455 assert(Fn);
8456 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8457 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008458 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008459 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008460 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008461
8462 if (pHadMultipleCandidates)
8463 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008464 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008465}
8466
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008467/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008468/// resolve that overloaded function expression down to a single function.
8469///
8470/// This routine can only resolve template-ids that refer to a single function
8471/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008472/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008473/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008474FunctionDecl *
8475Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8476 bool Complain,
8477 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008478 // C++ [over.over]p1:
8479 // [...] [Note: any redundant set of parentheses surrounding the
8480 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008481 // C++ [over.over]p1:
8482 // [...] The overloaded function name can be preceded by the &
8483 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008484
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008485 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008486 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008487 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008488
8489 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008490 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008491
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008492 // Look through all of the overloaded functions, searching for one
8493 // whose type matches exactly.
8494 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008495 for (UnresolvedSetIterator I = ovl->decls_begin(),
8496 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008497 // C++0x [temp.arg.explicit]p3:
8498 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008499 // where deduction is not done, if a template argument list is
8500 // specified and it, along with any default template arguments,
8501 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008502 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008503 FunctionTemplateDecl *FunctionTemplate
8504 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008505
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008506 // C++ [over.over]p2:
8507 // If the name is a function template, template argument deduction is
8508 // done (14.8.2.2), and if the argument deduction succeeds, the
8509 // resulting template argument list is used to generate a single
8510 // function template specialization, which is added to the set of
8511 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008512 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008513 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008514 if (TemplateDeductionResult Result
8515 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8516 Specialization, Info)) {
8517 // FIXME: make a note of the failed deduction for diagnostics.
8518 (void)Result;
8519 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008520 }
8521
John McCall0009fcc2011-04-26 20:42:42 +00008522 assert(Specialization && "no specialization and no error?");
8523
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008524 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008525 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008526 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008527 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8528 << ovl->getName();
8529 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008530 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008531 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008532 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008533
John McCall0009fcc2011-04-26 20:42:42 +00008534 Matched = Specialization;
8535 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008536 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008537
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008538 return Matched;
8539}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008540
Douglas Gregor1beec452011-03-12 01:48:56 +00008541
8542
8543
John McCall50a2c2c2011-10-11 23:14:30 +00008544// Resolve and fix an overloaded expression that can be resolved
8545// because it identifies a single function template specialization.
8546//
Douglas Gregor1beec452011-03-12 01:48:56 +00008547// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008548//
8549// Return true if it was logically possible to so resolve the
8550// expression, regardless of whether or not it succeeded. Always
8551// returns true if 'complain' is set.
8552bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8553 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8554 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008555 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008556 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008557 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008558
John McCall50a2c2c2011-10-11 23:14:30 +00008559 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008560
John McCall0009fcc2011-04-26 20:42:42 +00008561 DeclAccessPair found;
8562 ExprResult SingleFunctionExpression;
8563 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8564 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008565 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8566 SrcExpr = ExprError();
8567 return true;
8568 }
John McCall0009fcc2011-04-26 20:42:42 +00008569
8570 // It is only correct to resolve to an instance method if we're
8571 // resolving a form that's permitted to be a pointer to member.
8572 // Otherwise we'll end up making a bound member expression, which
8573 // is illegal in all the contexts we resolve like this.
8574 if (!ovl.HasFormOfMemberPointer &&
8575 isa<CXXMethodDecl>(fn) &&
8576 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008577 if (!complain) return false;
8578
8579 Diag(ovl.Expression->getExprLoc(),
8580 diag::err_bound_member_function)
8581 << 0 << ovl.Expression->getSourceRange();
8582
8583 // TODO: I believe we only end up here if there's a mix of
8584 // static and non-static candidates (otherwise the expression
8585 // would have 'bound member' type, not 'overload' type).
8586 // Ideally we would note which candidate was chosen and why
8587 // the static candidates were rejected.
8588 SrcExpr = ExprError();
8589 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008590 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008591
John McCall0009fcc2011-04-26 20:42:42 +00008592 // Fix the expresion to refer to 'fn'.
8593 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008594 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008595
8596 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008597 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008598 SingleFunctionExpression =
8599 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008600 if (SingleFunctionExpression.isInvalid()) {
8601 SrcExpr = ExprError();
8602 return true;
8603 }
8604 }
John McCall0009fcc2011-04-26 20:42:42 +00008605 }
8606
8607 if (!SingleFunctionExpression.isUsable()) {
8608 if (complain) {
8609 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8610 << ovl.Expression->getName()
8611 << DestTypeForComplaining
8612 << OpRangeForComplaining
8613 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008614 NoteAllOverloadCandidates(SrcExpr.get());
8615
8616 SrcExpr = ExprError();
8617 return true;
8618 }
8619
8620 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008621 }
8622
John McCall50a2c2c2011-10-11 23:14:30 +00008623 SrcExpr = SingleFunctionExpression;
8624 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008625}
8626
Douglas Gregorcabea402009-09-22 15:41:20 +00008627/// \brief Add a single candidate to the overload set.
8628static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008629 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008630 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008631 Expr **Args, unsigned NumArgs,
8632 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008633 bool PartialOverloading,
8634 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008635 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008636 if (isa<UsingShadowDecl>(Callee))
8637 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8638
Douglas Gregorcabea402009-09-22 15:41:20 +00008639 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008640 if (ExplicitTemplateArgs) {
8641 assert(!KnownValid && "Explicit template arguments?");
8642 return;
8643 }
John McCalla0296f72010-03-19 07:35:19 +00008644 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008645 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008646 return;
John McCalld14a8642009-11-21 08:51:07 +00008647 }
8648
8649 if (FunctionTemplateDecl *FuncTemplate
8650 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008651 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8652 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008653 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008654 return;
8655 }
8656
Richard Smith95ce4f62011-06-26 22:19:54 +00008657 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008658}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008659
Douglas Gregorcabea402009-09-22 15:41:20 +00008660/// \brief Add the overload candidates named by callee and/or found by argument
8661/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008662void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008663 Expr **Args, unsigned NumArgs,
8664 OverloadCandidateSet &CandidateSet,
8665 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008666
8667#ifndef NDEBUG
8668 // Verify that ArgumentDependentLookup is consistent with the rules
8669 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008670 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008671 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8672 // and let Y be the lookup set produced by argument dependent
8673 // lookup (defined as follows). If X contains
8674 //
8675 // -- a declaration of a class member, or
8676 //
8677 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008678 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008679 //
8680 // -- a declaration that is neither a function or a function
8681 // template
8682 //
8683 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008684
John McCall57500772009-12-16 12:17:52 +00008685 if (ULE->requiresADL()) {
8686 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8687 E = ULE->decls_end(); I != E; ++I) {
8688 assert(!(*I)->getDeclContext()->isRecord());
8689 assert(isa<UsingShadowDecl>(*I) ||
8690 !(*I)->getDeclContext()->isFunctionOrMethod());
8691 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008692 }
8693 }
8694#endif
8695
John McCall57500772009-12-16 12:17:52 +00008696 // It would be nice to avoid this copy.
8697 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008698 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008699 if (ULE->hasExplicitTemplateArgs()) {
8700 ULE->copyTemplateArgumentsInto(TABuffer);
8701 ExplicitTemplateArgs = &TABuffer;
8702 }
8703
8704 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8705 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008706 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008707 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008708 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008709
John McCall57500772009-12-16 12:17:52 +00008710 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008711 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8712 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008713 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008714 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008715 PartialOverloading,
8716 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008717}
John McCalld681c392009-12-16 08:11:27 +00008718
Richard Smith998a5912011-06-05 22:42:48 +00008719/// Attempt to recover from an ill-formed use of a non-dependent name in a
8720/// template, where the non-dependent name was declared after the template
8721/// was defined. This is common in code written for a compilers which do not
8722/// correctly implement two-stage name lookup.
8723///
8724/// Returns true if a viable candidate was found and a diagnostic was issued.
8725static bool
8726DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8727 const CXXScopeSpec &SS, LookupResult &R,
8728 TemplateArgumentListInfo *ExplicitTemplateArgs,
8729 Expr **Args, unsigned NumArgs) {
8730 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8731 return false;
8732
8733 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8734 SemaRef.LookupQualifiedName(R, DC);
8735
8736 if (!R.empty()) {
8737 R.suppressDiagnostics();
8738
8739 if (isa<CXXRecordDecl>(DC)) {
8740 // Don't diagnose names we find in classes; we get much better
8741 // diagnostics for these from DiagnoseEmptyLookup.
8742 R.clear();
8743 return false;
8744 }
8745
8746 OverloadCandidateSet Candidates(FnLoc);
8747 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8748 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8749 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008750 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008751
8752 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008753 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008754 // No viable functions. Don't bother the user with notes for functions
8755 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008756 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008757 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008758 }
Richard Smith998a5912011-06-05 22:42:48 +00008759
8760 // Find the namespaces where ADL would have looked, and suggest
8761 // declaring the function there instead.
8762 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8763 Sema::AssociatedClassSet AssociatedClasses;
8764 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8765 AssociatedNamespaces,
8766 AssociatedClasses);
8767 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008768 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008769 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008770 for (Sema::AssociatedNamespaceSet::iterator
8771 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008772 end = AssociatedNamespaces.end(); it != end; ++it) {
8773 if (!Std->Encloses(*it))
8774 SuggestedNamespaces.insert(*it);
8775 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008776 } else {
8777 // Lacking the 'std::' namespace, use all of the associated namespaces.
8778 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008779 }
8780
8781 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8782 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008783 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008784 SemaRef.Diag(Best->Function->getLocation(),
8785 diag::note_not_found_by_two_phase_lookup)
8786 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008787 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008788 SemaRef.Diag(Best->Function->getLocation(),
8789 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008790 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008791 } else {
8792 // FIXME: It would be useful to list the associated namespaces here,
8793 // but the diagnostics infrastructure doesn't provide a way to produce
8794 // a localized representation of a list of items.
8795 SemaRef.Diag(Best->Function->getLocation(),
8796 diag::note_not_found_by_two_phase_lookup)
8797 << R.getLookupName() << 2;
8798 }
8799
8800 // Try to recover by calling this function.
8801 return true;
8802 }
8803
8804 R.clear();
8805 }
8806
8807 return false;
8808}
8809
8810/// Attempt to recover from ill-formed use of a non-dependent operator in a
8811/// template, where the non-dependent operator was declared after the template
8812/// was defined.
8813///
8814/// Returns true if a viable candidate was found and a diagnostic was issued.
8815static bool
8816DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8817 SourceLocation OpLoc,
8818 Expr **Args, unsigned NumArgs) {
8819 DeclarationName OpName =
8820 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8821 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8822 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8823 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8824}
8825
John McCalld681c392009-12-16 08:11:27 +00008826/// Attempts to recover from a call where no functions were found.
8827///
8828/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008829static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008830BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008831 UnresolvedLookupExpr *ULE,
8832 SourceLocation LParenLoc,
8833 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008834 SourceLocation RParenLoc,
8835 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008836
8837 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008838 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008839
John McCall57500772009-12-16 12:17:52 +00008840 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008841 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008842 if (ULE->hasExplicitTemplateArgs()) {
8843 ULE->copyTemplateArgumentsInto(TABuffer);
8844 ExplicitTemplateArgs = &TABuffer;
8845 }
8846
John McCalld681c392009-12-16 08:11:27 +00008847 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8848 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008849 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8850 ExplicitTemplateArgs, Args, NumArgs) &&
8851 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008852 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008853 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008854 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008855
John McCall57500772009-12-16 12:17:52 +00008856 assert(!R.empty() && "lookup results empty despite recovery");
8857
8858 // Build an implicit member call if appropriate. Just drop the
8859 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008860 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008861 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008862 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8863 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008864 else if (ExplicitTemplateArgs)
8865 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8866 else
8867 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8868
8869 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008870 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008871
8872 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008873 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008874 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008875 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008876 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008877}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008878
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008879/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008880/// (which eventually refers to the declaration Func) and the call
8881/// arguments Args/NumArgs, attempt to resolve the function call down
8882/// to a specific function. If overload resolution succeeds, returns
8883/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008884/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008885/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008886ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008887Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008888 SourceLocation LParenLoc,
8889 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008890 SourceLocation RParenLoc,
8891 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008892#ifndef NDEBUG
8893 if (ULE->requiresADL()) {
8894 // To do ADL, we must have found an unqualified name.
8895 assert(!ULE->getQualifier() && "qualified name with ADL");
8896
8897 // We don't perform ADL for implicit declarations of builtins.
8898 // Verify that this was correctly set up.
8899 FunctionDecl *F;
8900 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8901 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8902 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008903 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008904
John McCall57500772009-12-16 12:17:52 +00008905 // We don't perform ADL in C.
8906 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008907 } else
8908 assert(!ULE->isStdAssociatedNamespace() &&
8909 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008910#endif
8911
John McCall4124c492011-10-17 18:40:02 +00008912 UnbridgedCastsSet UnbridgedCasts;
8913 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8914 return ExprError();
8915
John McCallbc077cf2010-02-08 23:07:23 +00008916 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008917
John McCall57500772009-12-16 12:17:52 +00008918 // Add the functions denoted by the callee to the set of candidate
8919 // functions, including those from argument-dependent lookup.
8920 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008921
8922 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008923 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8924 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008925 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008926 // In Microsoft mode, if we are inside a template class member function then
8927 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008928 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008929 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00008930 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00008931 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008932 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8933 Context.DependentTy, VK_RValue,
8934 RParenLoc);
8935 CE->setTypeDependent(true);
8936 return Owned(CE);
8937 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008938 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008939 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008940 }
John McCalld681c392009-12-16 08:11:27 +00008941
John McCall4124c492011-10-17 18:40:02 +00008942 UnbridgedCasts.restore();
8943
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008944 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008945 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008946 case OR_Success: {
8947 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008948 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008949 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008950 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008951 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008952 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8953 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008954 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008955
Richard Smith998a5912011-06-05 22:42:48 +00008956 case OR_No_Viable_Function: {
8957 // Try to recover by looking for viable functions which the user might
8958 // have meant to call.
8959 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8960 Args, NumArgs, RParenLoc,
8961 /*EmptyLookup=*/false);
8962 if (!Recovery.isInvalid())
8963 return Recovery;
8964
Chris Lattner45d9d602009-02-17 07:29:20 +00008965 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008966 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008967 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008968 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008969 break;
Richard Smith998a5912011-06-05 22:42:48 +00008970 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008971
8972 case OR_Ambiguous:
8973 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008974 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008975 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008976 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008977
8978 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008979 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008980 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8981 << Best->Function->isDeleted()
8982 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008983 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008984 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008985 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00008986
8987 // We emitted an error for the unvailable/deleted function call but keep
8988 // the call in the AST.
8989 FunctionDecl *FDecl = Best->Function;
8990 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8991 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8992 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008993 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008994 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008995 }
8996
Douglas Gregorb412e172010-07-25 18:17:45 +00008997 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008998 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008999}
9000
John McCall4c4c1df2010-01-26 03:27:55 +00009001static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009002 return Functions.size() > 1 ||
9003 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9004}
9005
Douglas Gregor084d8552009-03-13 23:49:33 +00009006/// \brief Create a unary operation that may resolve to an overloaded
9007/// operator.
9008///
9009/// \param OpLoc The location of the operator itself (e.g., '*').
9010///
9011/// \param OpcIn The UnaryOperator::Opcode that describes this
9012/// operator.
9013///
9014/// \param Functions The set of non-member functions that will be
9015/// considered by overload resolution. The caller needs to build this
9016/// set based on the context using, e.g.,
9017/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9018/// set should not contain any member functions; those will be added
9019/// by CreateOverloadedUnaryOp().
9020///
9021/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009022ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009023Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9024 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009025 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009026 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009027
9028 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9029 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9030 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009031 // TODO: provide better source location info.
9032 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009033
John McCall4124c492011-10-17 18:40:02 +00009034 if (checkPlaceholderForOverload(*this, Input))
9035 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009036
Douglas Gregor084d8552009-03-13 23:49:33 +00009037 Expr *Args[2] = { Input, 0 };
9038 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009039
Douglas Gregor084d8552009-03-13 23:49:33 +00009040 // For post-increment and post-decrement, add the implicit '0' as
9041 // the second argument, so that we know this is a post-increment or
9042 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009043 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009044 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009045 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9046 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009047 NumArgs = 2;
9048 }
9049
9050 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009051 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009052 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009053 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009054 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009055 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009056 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009057
John McCall58cc69d2010-01-27 01:50:18 +00009058 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009059 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009060 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009061 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009062 /*ADL*/ true, IsOverloaded(Fns),
9063 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009064 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009065 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009066 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009067 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009068 OpLoc));
9069 }
9070
9071 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009072 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009073
9074 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009075 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009076
9077 // Add operator candidates that are member functions.
9078 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9079
John McCall4c4c1df2010-01-26 03:27:55 +00009080 // Add candidates from ADL.
9081 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009082 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009083 /*ExplicitTemplateArgs*/ 0,
9084 CandidateSet);
9085
Douglas Gregor084d8552009-03-13 23:49:33 +00009086 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009087 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009088
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009089 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9090
Douglas Gregor084d8552009-03-13 23:49:33 +00009091 // Perform overload resolution.
9092 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009093 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009094 case OR_Success: {
9095 // We found a built-in operator or an overloaded operator.
9096 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009097
Douglas Gregor084d8552009-03-13 23:49:33 +00009098 if (FnDecl) {
9099 // We matched an overloaded operator. Build a call to that
9100 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009101
Chandler Carruth30141632011-02-25 19:41:05 +00009102 MarkDeclarationReferenced(OpLoc, FnDecl);
9103
Douglas Gregor084d8552009-03-13 23:49:33 +00009104 // Convert the arguments.
9105 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009106 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009107
John Wiegley01296292011-04-08 18:41:53 +00009108 ExprResult InputRes =
9109 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9110 Best->FoundDecl, Method);
9111 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009112 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009113 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009114 } else {
9115 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009116 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009117 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009118 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009119 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009120 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009121 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009122 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009123 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009124 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009125 }
9126
John McCall4fa0d5f2010-05-06 18:15:07 +00009127 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9128
John McCall7decc9e2010-11-18 06:31:45 +00009129 // Determine the result type.
9130 QualType ResultTy = FnDecl->getResultType();
9131 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9132 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009133
Douglas Gregor084d8552009-03-13 23:49:33 +00009134 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009135 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9136 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009137 if (FnExpr.isInvalid())
9138 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009139
Eli Friedman030eee42009-11-18 03:58:17 +00009140 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009141 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009142 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009143 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009144
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009145 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009146 FnDecl))
9147 return ExprError();
9148
John McCallb268a282010-08-23 23:25:46 +00009149 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009150 } else {
9151 // We matched a built-in operator. Convert the arguments, then
9152 // break out so that we will build the appropriate built-in
9153 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009154 ExprResult InputRes =
9155 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9156 Best->Conversions[0], AA_Passing);
9157 if (InputRes.isInvalid())
9158 return ExprError();
9159 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009160 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009161 }
John Wiegley01296292011-04-08 18:41:53 +00009162 }
9163
9164 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009165 // This is an erroneous use of an operator which can be overloaded by
9166 // a non-member function. Check for non-member operators which were
9167 // defined too late to be candidates.
9168 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9169 // FIXME: Recover by calling the found function.
9170 return ExprError();
9171
John Wiegley01296292011-04-08 18:41:53 +00009172 // No viable function; fall through to handling this as a
9173 // built-in operator, which will produce an error message for us.
9174 break;
9175
9176 case OR_Ambiguous:
9177 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9178 << UnaryOperator::getOpcodeStr(Opc)
9179 << Input->getType()
9180 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009181 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009182 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9183 return ExprError();
9184
9185 case OR_Deleted:
9186 Diag(OpLoc, diag::err_ovl_deleted_oper)
9187 << Best->Function->isDeleted()
9188 << UnaryOperator::getOpcodeStr(Opc)
9189 << getDeletedOrUnavailableSuffix(Best->Function)
9190 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009191 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9192 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009193 return ExprError();
9194 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009195
9196 // Either we found no viable overloaded operator or we matched a
9197 // built-in operator. In either case, fall through to trying to
9198 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009199 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009200}
9201
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009202/// \brief Create a binary operation that may resolve to an overloaded
9203/// operator.
9204///
9205/// \param OpLoc The location of the operator itself (e.g., '+').
9206///
9207/// \param OpcIn The BinaryOperator::Opcode that describes this
9208/// operator.
9209///
9210/// \param Functions The set of non-member functions that will be
9211/// considered by overload resolution. The caller needs to build this
9212/// set based on the context using, e.g.,
9213/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9214/// set should not contain any member functions; those will be added
9215/// by CreateOverloadedBinOp().
9216///
9217/// \param LHS Left-hand argument.
9218/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009219ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009220Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009221 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009222 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009223 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009224 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009225 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009226
9227 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9228 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9229 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9230
9231 // If either side is type-dependent, create an appropriate dependent
9232 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009233 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009234 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009235 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009236 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009237 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009238 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009239 Context.DependentTy,
9240 VK_RValue, OK_Ordinary,
9241 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009242
Douglas Gregor5287f092009-11-05 00:51:44 +00009243 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9244 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009245 VK_LValue,
9246 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009247 Context.DependentTy,
9248 Context.DependentTy,
9249 OpLoc));
9250 }
John McCall4c4c1df2010-01-26 03:27:55 +00009251
9252 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009253 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009254 // TODO: provide better source location info in DNLoc component.
9255 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009256 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009257 = UnresolvedLookupExpr::Create(Context, NamingClass,
9258 NestedNameSpecifierLoc(), OpNameInfo,
9259 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009260 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009261 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009262 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009263 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009264 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009265 OpLoc));
9266 }
9267
John McCall4124c492011-10-17 18:40:02 +00009268 // Always do placeholder-like conversions on the RHS.
9269 if (checkPlaceholderForOverload(*this, Args[1]))
9270 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009271
John McCall526ab472011-10-25 17:37:35 +00009272 // Do placeholder-like conversion on the LHS; note that we should
9273 // not get here with a PseudoObject LHS.
9274 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009275 if (checkPlaceholderForOverload(*this, Args[0]))
9276 return ExprError();
9277
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009278 // If this is the assignment operator, we only perform overload resolution
9279 // if the left-hand side is a class or enumeration type. This is actually
9280 // a hack. The standard requires that we do overload resolution between the
9281 // various built-in candidates, but as DR507 points out, this can lead to
9282 // problems. So we do it this way, which pretty much follows what GCC does.
9283 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009284 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009285 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009286
John McCalle26a8722010-12-04 08:14:53 +00009287 // If this is the .* operator, which is not overloadable, just
9288 // create a built-in binary operator.
9289 if (Opc == BO_PtrMemD)
9290 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9291
Douglas Gregor084d8552009-03-13 23:49:33 +00009292 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009293 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009294
9295 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009296 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009297
9298 // Add operator candidates that are member functions.
9299 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9300
John McCall4c4c1df2010-01-26 03:27:55 +00009301 // Add candidates from ADL.
9302 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9303 Args, 2,
9304 /*ExplicitTemplateArgs*/ 0,
9305 CandidateSet);
9306
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009307 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009308 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009309
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009310 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9311
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009312 // Perform overload resolution.
9313 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009314 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009315 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009316 // We found a built-in operator or an overloaded operator.
9317 FunctionDecl *FnDecl = Best->Function;
9318
9319 if (FnDecl) {
9320 // We matched an overloaded operator. Build a call to that
9321 // operator.
9322
Chandler Carruth30141632011-02-25 19:41:05 +00009323 MarkDeclarationReferenced(OpLoc, FnDecl);
9324
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009325 // Convert the arguments.
9326 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009327 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009328 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009329
Chandler Carruth8e543b32010-12-12 08:17:55 +00009330 ExprResult Arg1 =
9331 PerformCopyInitialization(
9332 InitializedEntity::InitializeParameter(Context,
9333 FnDecl->getParamDecl(0)),
9334 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009335 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009336 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009337
John Wiegley01296292011-04-08 18:41:53 +00009338 ExprResult Arg0 =
9339 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9340 Best->FoundDecl, Method);
9341 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009342 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009343 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009344 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009345 } else {
9346 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009347 ExprResult Arg0 = PerformCopyInitialization(
9348 InitializedEntity::InitializeParameter(Context,
9349 FnDecl->getParamDecl(0)),
9350 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009351 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009352 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009353
Chandler Carruth8e543b32010-12-12 08:17:55 +00009354 ExprResult Arg1 =
9355 PerformCopyInitialization(
9356 InitializedEntity::InitializeParameter(Context,
9357 FnDecl->getParamDecl(1)),
9358 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009359 if (Arg1.isInvalid())
9360 return ExprError();
9361 Args[0] = LHS = Arg0.takeAs<Expr>();
9362 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009363 }
9364
John McCall4fa0d5f2010-05-06 18:15:07 +00009365 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9366
John McCall7decc9e2010-11-18 06:31:45 +00009367 // Determine the result type.
9368 QualType ResultTy = FnDecl->getResultType();
9369 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9370 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009371
9372 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009373 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9374 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009375 if (FnExpr.isInvalid())
9376 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009377
John McCallb268a282010-08-23 23:25:46 +00009378 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009379 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009380 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009381
9382 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009383 FnDecl))
9384 return ExprError();
9385
John McCallb268a282010-08-23 23:25:46 +00009386 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009387 } else {
9388 // We matched a built-in operator. Convert the arguments, then
9389 // break out so that we will build the appropriate built-in
9390 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009391 ExprResult ArgsRes0 =
9392 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9393 Best->Conversions[0], AA_Passing);
9394 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009395 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009396 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009397
John Wiegley01296292011-04-08 18:41:53 +00009398 ExprResult ArgsRes1 =
9399 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9400 Best->Conversions[1], AA_Passing);
9401 if (ArgsRes1.isInvalid())
9402 return ExprError();
9403 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009404 break;
9405 }
9406 }
9407
Douglas Gregor66950a32009-09-30 21:46:01 +00009408 case OR_No_Viable_Function: {
9409 // C++ [over.match.oper]p9:
9410 // If the operator is the operator , [...] and there are no
9411 // viable functions, then the operator is assumed to be the
9412 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009413 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009414 break;
9415
Chandler Carruth8e543b32010-12-12 08:17:55 +00009416 // For class as left operand for assignment or compound assigment
9417 // operator do not fall through to handling in built-in, but report that
9418 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009419 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009420 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009421 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009422 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9423 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009424 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009425 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009426 // This is an erroneous use of an operator which can be overloaded by
9427 // a non-member function. Check for non-member operators which were
9428 // defined too late to be candidates.
9429 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9430 // FIXME: Recover by calling the found function.
9431 return ExprError();
9432
Douglas Gregor66950a32009-09-30 21:46:01 +00009433 // No viable function; try to create a built-in operation, which will
9434 // produce an error. Then, show the non-viable candidates.
9435 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009436 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009437 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009438 "C++ binary operator overloading is missing candidates!");
9439 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009440 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9441 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009442 return move(Result);
9443 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009444
9445 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009446 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009447 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009448 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009449 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009450 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9451 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009452 return ExprError();
9453
9454 case OR_Deleted:
9455 Diag(OpLoc, diag::err_ovl_deleted_oper)
9456 << Best->Function->isDeleted()
9457 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009458 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009459 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009460 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9461 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009462 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009463 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009464
Douglas Gregor66950a32009-09-30 21:46:01 +00009465 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009466 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009467}
9468
John McCalldadc5752010-08-24 06:29:42 +00009469ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009470Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9471 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009472 Expr *Base, Expr *Idx) {
9473 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009474 DeclarationName OpName =
9475 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9476
9477 // If either side is type-dependent, create an appropriate dependent
9478 // expression.
9479 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9480
John McCall58cc69d2010-01-27 01:50:18 +00009481 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009482 // CHECKME: no 'operator' keyword?
9483 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9484 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009485 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009486 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009487 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009488 /*ADL*/ true, /*Overloaded*/ false,
9489 UnresolvedSetIterator(),
9490 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009491 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009492
Sebastian Redladba46e2009-10-29 20:17:01 +00009493 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9494 Args, 2,
9495 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009496 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009497 RLoc));
9498 }
9499
John McCall4124c492011-10-17 18:40:02 +00009500 // Handle placeholders on both operands.
9501 if (checkPlaceholderForOverload(*this, Args[0]))
9502 return ExprError();
9503 if (checkPlaceholderForOverload(*this, Args[1]))
9504 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009505
Sebastian Redladba46e2009-10-29 20:17:01 +00009506 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009507 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009508
9509 // Subscript can only be overloaded as a member function.
9510
9511 // Add operator candidates that are member functions.
9512 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9513
9514 // Add builtin operator candidates.
9515 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9516
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009517 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9518
Sebastian Redladba46e2009-10-29 20:17:01 +00009519 // Perform overload resolution.
9520 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009521 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009522 case OR_Success: {
9523 // We found a built-in operator or an overloaded operator.
9524 FunctionDecl *FnDecl = Best->Function;
9525
9526 if (FnDecl) {
9527 // We matched an overloaded operator. Build a call to that
9528 // operator.
9529
Chandler Carruth30141632011-02-25 19:41:05 +00009530 MarkDeclarationReferenced(LLoc, FnDecl);
9531
John McCalla0296f72010-03-19 07:35:19 +00009532 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009533 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009534
Sebastian Redladba46e2009-10-29 20:17:01 +00009535 // Convert the arguments.
9536 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009537 ExprResult Arg0 =
9538 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9539 Best->FoundDecl, Method);
9540 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009541 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009542 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009543
Anders Carlssona68e51e2010-01-29 18:37:50 +00009544 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009545 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009546 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009547 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009548 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009549 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009550 Owned(Args[1]));
9551 if (InputInit.isInvalid())
9552 return ExprError();
9553
9554 Args[1] = InputInit.takeAs<Expr>();
9555
Sebastian Redladba46e2009-10-29 20:17:01 +00009556 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009557 QualType ResultTy = FnDecl->getResultType();
9558 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9559 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009560
9561 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009562 DeclarationNameLoc LocInfo;
9563 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9564 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009565 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9566 HadMultipleCandidates,
9567 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009568 if (FnExpr.isInvalid())
9569 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009570
John McCallb268a282010-08-23 23:25:46 +00009571 CXXOperatorCallExpr *TheCall =
9572 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009573 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009574 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009575
John McCallb268a282010-08-23 23:25:46 +00009576 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009577 FnDecl))
9578 return ExprError();
9579
John McCallb268a282010-08-23 23:25:46 +00009580 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009581 } else {
9582 // We matched a built-in operator. Convert the arguments, then
9583 // break out so that we will build the appropriate built-in
9584 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009585 ExprResult ArgsRes0 =
9586 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9587 Best->Conversions[0], AA_Passing);
9588 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009589 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009590 Args[0] = ArgsRes0.take();
9591
9592 ExprResult ArgsRes1 =
9593 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9594 Best->Conversions[1], AA_Passing);
9595 if (ArgsRes1.isInvalid())
9596 return ExprError();
9597 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009598
9599 break;
9600 }
9601 }
9602
9603 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009604 if (CandidateSet.empty())
9605 Diag(LLoc, diag::err_ovl_no_oper)
9606 << Args[0]->getType() << /*subscript*/ 0
9607 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9608 else
9609 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9610 << Args[0]->getType()
9611 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009612 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9613 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009614 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009615 }
9616
9617 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009618 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009619 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009620 << Args[0]->getType() << Args[1]->getType()
9621 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009622 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9623 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009624 return ExprError();
9625
9626 case OR_Deleted:
9627 Diag(LLoc, diag::err_ovl_deleted_oper)
9628 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009629 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009630 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009631 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9632 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009633 return ExprError();
9634 }
9635
9636 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009637 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009638}
9639
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009640/// BuildCallToMemberFunction - Build a call to a member
9641/// function. MemExpr is the expression that refers to the member
9642/// function (and includes the object parameter), Args/NumArgs are the
9643/// arguments to the function call (not including the object
9644/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009645/// expression refers to a non-static member function or an overloaded
9646/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009647ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009648Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9649 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009650 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009651 assert(MemExprE->getType() == Context.BoundMemberTy ||
9652 MemExprE->getType() == Context.OverloadTy);
9653
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009654 // Dig out the member expression. This holds both the object
9655 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009656 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009657
John McCall0009fcc2011-04-26 20:42:42 +00009658 // Determine whether this is a call to a pointer-to-member function.
9659 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9660 assert(op->getType() == Context.BoundMemberTy);
9661 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9662
9663 QualType fnType =
9664 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9665
9666 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9667 QualType resultType = proto->getCallResultType(Context);
9668 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9669
9670 // Check that the object type isn't more qualified than the
9671 // member function we're calling.
9672 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9673
9674 QualType objectType = op->getLHS()->getType();
9675 if (op->getOpcode() == BO_PtrMemI)
9676 objectType = objectType->castAs<PointerType>()->getPointeeType();
9677 Qualifiers objectQuals = objectType.getQualifiers();
9678
9679 Qualifiers difference = objectQuals - funcQuals;
9680 difference.removeObjCGCAttr();
9681 difference.removeAddressSpace();
9682 if (difference) {
9683 std::string qualsString = difference.getAsString();
9684 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9685 << fnType.getUnqualifiedType()
9686 << qualsString
9687 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9688 }
9689
9690 CXXMemberCallExpr *call
9691 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9692 resultType, valueKind, RParenLoc);
9693
9694 if (CheckCallReturnType(proto->getResultType(),
9695 op->getRHS()->getSourceRange().getBegin(),
9696 call, 0))
9697 return ExprError();
9698
9699 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9700 return ExprError();
9701
9702 return MaybeBindToTemporary(call);
9703 }
9704
John McCall4124c492011-10-17 18:40:02 +00009705 UnbridgedCastsSet UnbridgedCasts;
9706 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9707 return ExprError();
9708
John McCall10eae182009-11-30 22:42:35 +00009709 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009710 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009711 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009712 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009713 if (isa<MemberExpr>(NakedMemExpr)) {
9714 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009715 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009716 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009717 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009718 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009719 } else {
9720 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009721 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009722
John McCall6e9f8f62009-12-03 04:06:58 +00009723 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009724 Expr::Classification ObjectClassification
9725 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9726 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009727
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009728 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009729 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009730
John McCall2d74de92009-12-01 22:10:20 +00009731 // FIXME: avoid copy.
9732 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9733 if (UnresExpr->hasExplicitTemplateArgs()) {
9734 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9735 TemplateArgs = &TemplateArgsBuffer;
9736 }
9737
John McCall10eae182009-11-30 22:42:35 +00009738 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9739 E = UnresExpr->decls_end(); I != E; ++I) {
9740
John McCall6e9f8f62009-12-03 04:06:58 +00009741 NamedDecl *Func = *I;
9742 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9743 if (isa<UsingShadowDecl>(Func))
9744 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9745
Douglas Gregor02824322011-01-26 19:30:28 +00009746
Francois Pichet64225792011-01-18 05:04:39 +00009747 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009748 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009749 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9750 CandidateSet);
9751 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009752 // If explicit template arguments were provided, we can't call a
9753 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009754 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009755 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009756
John McCalla0296f72010-03-19 07:35:19 +00009757 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009758 ObjectClassification,
9759 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009760 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009761 } else {
John McCall10eae182009-11-30 22:42:35 +00009762 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009763 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009764 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009765 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009766 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009767 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009768 }
Mike Stump11289f42009-09-09 15:08:12 +00009769
John McCall10eae182009-11-30 22:42:35 +00009770 DeclarationName DeclName = UnresExpr->getMemberName();
9771
John McCall4124c492011-10-17 18:40:02 +00009772 UnbridgedCasts.restore();
9773
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009774 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009775 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009776 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009777 case OR_Success:
9778 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009779 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009780 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009781 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009782 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009783 break;
9784
9785 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009786 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009787 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009788 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009789 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009790 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009791 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009792
9793 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009794 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009795 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009796 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009797 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009798 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009799
9800 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009801 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009802 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009803 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009804 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009805 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009806 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009807 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009808 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009809 }
9810
John McCall16df1e52010-03-30 21:47:33 +00009811 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009812
John McCall2d74de92009-12-01 22:10:20 +00009813 // If overload resolution picked a static member, build a
9814 // non-member call based on that function.
9815 if (Method->isStatic()) {
9816 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9817 Args, NumArgs, RParenLoc);
9818 }
9819
John McCall10eae182009-11-30 22:42:35 +00009820 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009821 }
9822
John McCall7decc9e2010-11-18 06:31:45 +00009823 QualType ResultType = Method->getResultType();
9824 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9825 ResultType = ResultType.getNonLValueExprType(Context);
9826
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009827 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009828 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009829 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009830 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009831
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009832 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009833 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009834 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009835 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009836
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009837 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009838 // We only need to do this if there was actually an overload; otherwise
9839 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009840 if (!Method->isStatic()) {
9841 ExprResult ObjectArg =
9842 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9843 FoundDecl, Method);
9844 if (ObjectArg.isInvalid())
9845 return ExprError();
9846 MemExpr->setBase(ObjectArg.take());
9847 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009848
9849 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009850 const FunctionProtoType *Proto =
9851 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009852 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009853 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009854 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009855
John McCallb268a282010-08-23 23:25:46 +00009856 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009857 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009858
Anders Carlsson47061ee2011-05-06 14:25:31 +00009859 if ((isa<CXXConstructorDecl>(CurContext) ||
9860 isa<CXXDestructorDecl>(CurContext)) &&
9861 TheCall->getMethodDecl()->isPure()) {
9862 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9863
Chandler Carruth59259262011-06-27 08:31:58 +00009864 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009865 Diag(MemExpr->getLocStart(),
9866 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9867 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9868 << MD->getParent()->getDeclName();
9869
9870 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009871 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009872 }
John McCallb268a282010-08-23 23:25:46 +00009873 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009874}
9875
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009876/// BuildCallToObjectOfClassType - Build a call to an object of class
9877/// type (C++ [over.call.object]), which can end up invoking an
9878/// overloaded function call operator (@c operator()) or performing a
9879/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009880ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009881Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009882 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009883 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009884 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009885 if (checkPlaceholderForOverload(*this, Obj))
9886 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009887 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009888
9889 UnbridgedCastsSet UnbridgedCasts;
9890 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9891 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009892
John Wiegley01296292011-04-08 18:41:53 +00009893 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9894 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009895
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009896 // C++ [over.call.object]p1:
9897 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009898 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009899 // candidate functions includes at least the function call
9900 // operators of T. The function call operators of T are obtained by
9901 // ordinary lookup of the name operator() in the context of
9902 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009903 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009904 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009905
John Wiegley01296292011-04-08 18:41:53 +00009906 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009907 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009908 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009909 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009910
John McCall27b18f82009-11-17 02:14:36 +00009911 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9912 LookupQualifiedName(R, Record->getDecl());
9913 R.suppressDiagnostics();
9914
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009915 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009916 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009917 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9918 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009919 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009920 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009921
Douglas Gregorab7897a2008-11-19 22:57:39 +00009922 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009923 // In addition, for each (non-explicit in C++0x) conversion function
9924 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009925 //
9926 // operator conversion-type-id () cv-qualifier;
9927 //
9928 // where cv-qualifier is the same cv-qualification as, or a
9929 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009930 // denotes the type "pointer to function of (P1,...,Pn) returning
9931 // R", or the type "reference to pointer to function of
9932 // (P1,...,Pn) returning R", or the type "reference to function
9933 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009934 // is also considered as a candidate function. Similarly,
9935 // surrogate call functions are added to the set of candidate
9936 // functions for each conversion function declared in an
9937 // accessible base class provided the function is not hidden
9938 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009939 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009940 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009941 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009942 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009943 NamedDecl *D = *I;
9944 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9945 if (isa<UsingShadowDecl>(D))
9946 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009947
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009948 // Skip over templated conversion functions; they aren't
9949 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009950 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009951 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009952
John McCall6e9f8f62009-12-03 04:06:58 +00009953 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009954 if (!Conv->isExplicit()) {
9955 // Strip the reference type (if any) and then the pointer type (if
9956 // any) to get down to what might be a function type.
9957 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9958 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9959 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009960
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009961 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9962 {
9963 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9964 Object.get(), Args, NumArgs, CandidateSet);
9965 }
9966 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009967 }
Mike Stump11289f42009-09-09 15:08:12 +00009968
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009969 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9970
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009971 // Perform overload resolution.
9972 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009973 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009974 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009975 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009976 // Overload resolution succeeded; we'll build the appropriate call
9977 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009978 break;
9979
9980 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009981 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009982 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9983 << Object.get()->getType() << /*call*/ 1
9984 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009985 else
John Wiegley01296292011-04-08 18:41:53 +00009986 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009987 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009988 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009989 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009990 break;
9991
9992 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009993 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009994 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009995 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009996 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009997 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009998
9999 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +000010000 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010001 diag::err_ovl_deleted_object_call)
10002 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010003 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010004 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010005 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010006 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010007 break;
Mike Stump11289f42009-09-09 15:08:12 +000010008 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010009
Douglas Gregorb412e172010-07-25 18:17:45 +000010010 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010011 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010012
John McCall4124c492011-10-17 18:40:02 +000010013 UnbridgedCasts.restore();
10014
Douglas Gregorab7897a2008-11-19 22:57:39 +000010015 if (Best->Function == 0) {
10016 // Since there is no function declaration, this is one of the
10017 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010018 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010019 = cast<CXXConversionDecl>(
10020 Best->Conversions[0].UserDefined.ConversionFunction);
10021
John Wiegley01296292011-04-08 18:41:53 +000010022 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010023 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010024
Douglas Gregorab7897a2008-11-19 22:57:39 +000010025 // We selected one of the surrogate functions that converts the
10026 // object parameter to a function pointer. Perform the conversion
10027 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010028
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010029 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010030 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010031 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10032 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010033 if (Call.isInvalid())
10034 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010035 // Record usage of conversion in an implicit cast.
10036 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10037 CK_UserDefinedConversion,
10038 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010039
Douglas Gregor668443e2011-01-20 00:18:04 +000010040 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010041 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010042 }
10043
Chandler Carruth30141632011-02-25 19:41:05 +000010044 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010045 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010046 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010047
Douglas Gregorab7897a2008-11-19 22:57:39 +000010048 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10049 // that calls this method, using Object for the implicit object
10050 // parameter and passing along the remaining arguments.
10051 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010052 const FunctionProtoType *Proto =
10053 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010054
10055 unsigned NumArgsInProto = Proto->getNumArgs();
10056 unsigned NumArgsToCheck = NumArgs;
10057
10058 // Build the full argument list for the method call (the
10059 // implicit object parameter is placed at the beginning of the
10060 // list).
10061 Expr **MethodArgs;
10062 if (NumArgs < NumArgsInProto) {
10063 NumArgsToCheck = NumArgsInProto;
10064 MethodArgs = new Expr*[NumArgsInProto + 1];
10065 } else {
10066 MethodArgs = new Expr*[NumArgs + 1];
10067 }
John Wiegley01296292011-04-08 18:41:53 +000010068 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010069 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10070 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010071
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010072 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10073 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010074 if (NewFn.isInvalid())
10075 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010076
10077 // Once we've built TheCall, all of the expressions are properly
10078 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010079 QualType ResultTy = Method->getResultType();
10080 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10081 ResultTy = ResultTy.getNonLValueExprType(Context);
10082
John McCallb268a282010-08-23 23:25:46 +000010083 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010084 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010085 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010086 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010087 delete [] MethodArgs;
10088
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010089 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010090 Method))
10091 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010092
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010093 // We may have default arguments. If so, we need to allocate more
10094 // slots in the call for them.
10095 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010096 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010097 else if (NumArgs > NumArgsInProto)
10098 NumArgsToCheck = NumArgsInProto;
10099
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010100 bool IsError = false;
10101
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010102 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010103 ExprResult ObjRes =
10104 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10105 Best->FoundDecl, Method);
10106 if (ObjRes.isInvalid())
10107 IsError = true;
10108 else
10109 Object = move(ObjRes);
10110 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010111
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010112 // Check the argument types.
10113 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010114 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010115 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010116 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010117
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010118 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010119
John McCalldadc5752010-08-24 06:29:42 +000010120 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010121 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010122 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010123 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010124 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010125
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010126 IsError |= InputInit.isInvalid();
10127 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010128 } else {
John McCalldadc5752010-08-24 06:29:42 +000010129 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010130 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10131 if (DefArg.isInvalid()) {
10132 IsError = true;
10133 break;
10134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010135
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010136 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010137 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010138
10139 TheCall->setArg(i + 1, Arg);
10140 }
10141
10142 // If this is a variadic call, handle args passed through "...".
10143 if (Proto->isVariadic()) {
10144 // Promote the arguments (C99 6.5.2.2p7).
10145 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010146 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10147 IsError |= Arg.isInvalid();
10148 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010149 }
10150 }
10151
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010152 if (IsError) return true;
10153
John McCallb268a282010-08-23 23:25:46 +000010154 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010155 return true;
10156
John McCalle172be52010-08-24 06:09:16 +000010157 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010158}
10159
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010160/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010161/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010162/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010163ExprResult
John McCallb268a282010-08-23 23:25:46 +000010164Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010165 assert(Base->getType()->isRecordType() &&
10166 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010167
John McCall4124c492011-10-17 18:40:02 +000010168 if (checkPlaceholderForOverload(*this, Base))
10169 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010170
John McCallbc077cf2010-02-08 23:07:23 +000010171 SourceLocation Loc = Base->getExprLoc();
10172
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010173 // C++ [over.ref]p1:
10174 //
10175 // [...] An expression x->m is interpreted as (x.operator->())->m
10176 // for a class object x of type T if T::operator->() exists and if
10177 // the operator is selected as the best match function by the
10178 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010179 DeclarationName OpName =
10180 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010181 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010182 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010183
John McCallbc077cf2010-02-08 23:07:23 +000010184 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010185 PDiag(diag::err_typecheck_incomplete_tag)
10186 << Base->getSourceRange()))
10187 return ExprError();
10188
John McCall27b18f82009-11-17 02:14:36 +000010189 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10190 LookupQualifiedName(R, BaseRecord->getDecl());
10191 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010192
10193 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010194 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010195 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10196 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010197 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010198
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010199 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10200
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010201 // Perform overload resolution.
10202 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010203 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010204 case OR_Success:
10205 // Overload resolution succeeded; we'll build the call below.
10206 break;
10207
10208 case OR_No_Viable_Function:
10209 if (CandidateSet.empty())
10210 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010211 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010212 else
10213 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010214 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010215 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010216 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010217
10218 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010219 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10220 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010221 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010222 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010223
10224 case OR_Deleted:
10225 Diag(OpLoc, diag::err_ovl_deleted_oper)
10226 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010227 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010228 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010229 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010230 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010231 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010232 }
10233
Chandler Carruth30141632011-02-25 19:41:05 +000010234 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010235 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010236 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010237
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010238 // Convert the object parameter.
10239 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010240 ExprResult BaseResult =
10241 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10242 Best->FoundDecl, Method);
10243 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010244 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010245 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010246
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010247 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010248 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10249 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010250 if (FnExpr.isInvalid())
10251 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010252
John McCall7decc9e2010-11-18 06:31:45 +000010253 QualType ResultTy = Method->getResultType();
10254 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10255 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010256 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010257 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010258 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010259
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010260 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010261 Method))
10262 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010263
10264 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010265}
10266
Douglas Gregorcd695e52008-11-10 20:40:00 +000010267/// FixOverloadedFunctionReference - E is an expression that refers to
10268/// a C++ overloaded function (possibly with some parentheses and
10269/// perhaps a '&' around it). We have resolved the overloaded function
10270/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010271/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010272Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010273 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010274 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010275 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10276 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010277 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010278 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010279
Douglas Gregor51c538b2009-11-20 19:42:02 +000010280 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010281 }
10282
Douglas Gregor51c538b2009-11-20 19:42:02 +000010283 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010284 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10285 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010286 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010287 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010288 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010289 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010290 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010291 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010292
10293 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010294 ICE->getCastKind(),
10295 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010296 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010297 }
10298
Douglas Gregor51c538b2009-11-20 19:42:02 +000010299 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010300 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010301 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010302 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10303 if (Method->isStatic()) {
10304 // Do nothing: static member functions aren't any different
10305 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010306 } else {
John McCalle66edc12009-11-24 19:00:30 +000010307 // Fix the sub expression, which really has to be an
10308 // UnresolvedLookupExpr holding an overloaded member function
10309 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010310 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10311 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010312 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010313 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010314
John McCalld14a8642009-11-21 08:51:07 +000010315 assert(isa<DeclRefExpr>(SubExpr)
10316 && "fixed to something other than a decl ref");
10317 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10318 && "fixed to a member ref with no nested name qualifier");
10319
10320 // We have taken the address of a pointer to member
10321 // function. Perform the computation here so that we get the
10322 // appropriate pointer to member type.
10323 QualType ClassType
10324 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10325 QualType MemPtrType
10326 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10327
John McCall7decc9e2010-11-18 06:31:45 +000010328 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10329 VK_RValue, OK_Ordinary,
10330 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010331 }
10332 }
John McCall16df1e52010-03-30 21:47:33 +000010333 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10334 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010335 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010336 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010337
John McCalle3027922010-08-25 11:45:40 +000010338 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010339 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010340 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010341 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010342 }
John McCalld14a8642009-11-21 08:51:07 +000010343
10344 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010345 // FIXME: avoid copy.
10346 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010347 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010348 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10349 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010350 }
10351
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010352 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10353 ULE->getQualifierLoc(),
10354 Fn,
10355 ULE->getNameLoc(),
10356 Fn->getType(),
10357 VK_LValue,
10358 Found.getDecl(),
10359 TemplateArgs);
10360 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10361 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010362 }
10363
John McCall10eae182009-11-30 22:42:35 +000010364 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010365 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010366 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10367 if (MemExpr->hasExplicitTemplateArgs()) {
10368 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10369 TemplateArgs = &TemplateArgsBuffer;
10370 }
John McCall6b51f282009-11-23 01:53:49 +000010371
John McCall2d74de92009-12-01 22:10:20 +000010372 Expr *Base;
10373
John McCall7decc9e2010-11-18 06:31:45 +000010374 // If we're filling in a static method where we used to have an
10375 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010376 if (MemExpr->isImplicitAccess()) {
10377 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010378 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10379 MemExpr->getQualifierLoc(),
10380 Fn,
10381 MemExpr->getMemberLoc(),
10382 Fn->getType(),
10383 VK_LValue,
10384 Found.getDecl(),
10385 TemplateArgs);
10386 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10387 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010388 } else {
10389 SourceLocation Loc = MemExpr->getMemberLoc();
10390 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010391 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000010392 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000010393 Base = new (Context) CXXThisExpr(Loc,
10394 MemExpr->getBaseType(),
10395 /*isImplicit=*/true);
10396 }
John McCall2d74de92009-12-01 22:10:20 +000010397 } else
John McCallc3007a22010-10-26 07:05:15 +000010398 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010399
John McCall4adb38c2011-04-27 00:36:17 +000010400 ExprValueKind valueKind;
10401 QualType type;
10402 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10403 valueKind = VK_LValue;
10404 type = Fn->getType();
10405 } else {
10406 valueKind = VK_RValue;
10407 type = Context.BoundMemberTy;
10408 }
10409
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010410 MemberExpr *ME = MemberExpr::Create(Context, Base,
10411 MemExpr->isArrow(),
10412 MemExpr->getQualifierLoc(),
10413 Fn,
10414 Found,
10415 MemExpr->getMemberNameInfo(),
10416 TemplateArgs,
10417 type, valueKind, OK_Ordinary);
10418 ME->setHadMultipleCandidates(true);
10419 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010420 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010421
John McCallc3007a22010-10-26 07:05:15 +000010422 llvm_unreachable("Invalid reference to overloaded function");
10423 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010424}
10425
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010426ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010427 DeclAccessPair Found,
10428 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010429 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010430}
10431
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010432} // end namespace clang