blob: 2f1daf24795f4142087dd37a069dfb73e28d52d4 [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();
546}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
John McCall4124c492011-10-17 18:40:02 +0000548namespace {
549 class UnbridgedCastsSet {
550 struct Entry {
551 Expr **Addr;
552 Expr *Saved;
553 };
554 SmallVector<Entry, 2> Entries;
555
556 public:
557 void save(Sema &S, Expr *&E) {
558 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
559 Entry entry = { &E, E };
560 Entries.push_back(entry);
561 E = S.stripARCUnbridgedCast(E);
562 }
563
564 void restore() {
565 for (SmallVectorImpl<Entry>::iterator
566 i = Entries.begin(), e = Entries.end(); i != e; ++i)
567 *i->Addr = i->Saved;
568 }
569 };
570}
571
572/// checkPlaceholderForOverload - Do any interesting placeholder-like
573/// preprocessing on the given expression.
574///
575/// \param unbridgedCasts a collection to which to add unbridged casts;
576/// without this, they will be immediately diagnosed as errors
577///
578/// Return true on unrecoverable error.
579static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
580 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000581 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
582 // We can't handle overloaded expressions here because overload
583 // resolution might reasonably tweak them.
584 if (placeholder->getKind() == BuiltinType::Overload) return false;
585
586 // If the context potentially accepts unbridged ARC casts, strip
587 // the unbridged cast and add it to the collection for later restoration.
588 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
589 unbridgedCasts) {
590 unbridgedCasts->save(S, E);
591 return false;
592 }
593
594 // Go ahead and check everything else.
595 ExprResult result = S.CheckPlaceholderExpr(E);
596 if (result.isInvalid())
597 return true;
598
599 E = result.take();
600 return false;
601 }
602
603 // Nothing to do.
604 return false;
605}
606
607/// checkArgPlaceholdersForOverload - Check a set of call operands for
608/// placeholders.
609static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
610 unsigned numArgs,
611 UnbridgedCastsSet &unbridged) {
612 for (unsigned i = 0; i != numArgs; ++i)
613 if (checkPlaceholderForOverload(S, args[i], &unbridged))
614 return true;
615
616 return false;
617}
618
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000619// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000620// overload of the declarations in Old. This routine returns false if
621// New and Old cannot be overloaded, e.g., if New has the same
622// signature as some function in Old (C++ 1.3.10) or if the Old
623// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000624// it does return false, MatchedDecl will point to the decl that New
625// cannot be overloaded with. This decl may be a UsingShadowDecl on
626// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000627//
628// Example: Given the following input:
629//
630// void f(int, float); // #1
631// void f(int, int); // #2
632// int f(int, int); // #3
633//
634// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000635// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000636//
John McCall3d988d92009-12-02 08:47:38 +0000637// When we process #2, Old contains only the FunctionDecl for #1. By
638// comparing the parameter types, we see that #1 and #2 are overloaded
639// (since they have different signatures), so this routine returns
640// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000641//
John McCall3d988d92009-12-02 08:47:38 +0000642// When we process #3, Old is an overload set containing #1 and #2. We
643// compare the signatures of #3 to #1 (they're overloaded, so we do
644// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
645// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646// signature), IsOverload returns false and MatchedDecl will be set to
647// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000648//
649// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
650// into a class by a using declaration. The rules for whether to hide
651// shadow declarations ignore some properties which otherwise figure
652// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000653Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000654Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
655 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000656 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000657 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000658 NamedDecl *OldD = *I;
659
660 bool OldIsUsingDecl = false;
661 if (isa<UsingShadowDecl>(OldD)) {
662 OldIsUsingDecl = true;
663
664 // We can always introduce two using declarations into the same
665 // context, even if they have identical signatures.
666 if (NewIsUsingDecl) continue;
667
668 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
669 }
670
671 // If either declaration was introduced by a using declaration,
672 // we'll need to use slightly different rules for matching.
673 // Essentially, these rules are the normal rules, except that
674 // function templates hide function templates with different
675 // return types or template parameter lists.
676 bool UseMemberUsingDeclRules =
677 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
678
John McCall3d988d92009-12-02 08:47:38 +0000679 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000680 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
681 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
682 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
683 continue;
684 }
685
John McCalldaa3d6b2009-12-09 03:35:25 +0000686 Match = *I;
687 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000688 }
John McCall3d988d92009-12-02 08:47:38 +0000689 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000690 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
691 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
692 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
693 continue;
694 }
695
John McCalldaa3d6b2009-12-09 03:35:25 +0000696 Match = *I;
697 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000698 }
John McCalla8987a2942010-11-10 03:01:53 +0000699 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000700 // We can overload with these, which can show up when doing
701 // redeclaration checks for UsingDecls.
702 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000703 } else if (isa<TagDecl>(OldD)) {
704 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000705 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
706 // Optimistically assume that an unresolved using decl will
707 // overload; if it doesn't, we'll have to diagnose during
708 // template instantiation.
709 } else {
John McCall1f82f242009-11-18 22:49:29 +0000710 // (C++ 13p1):
711 // Only function declarations can be overloaded; object and type
712 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000713 Match = *I;
714 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000715 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000716 }
John McCall1f82f242009-11-18 22:49:29 +0000717
John McCalldaa3d6b2009-12-09 03:35:25 +0000718 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000719}
720
John McCalle9cccd82010-06-16 08:42:20 +0000721bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
722 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000723 // If both of the functions are extern "C", then they are not
724 // overloads.
725 if (Old->isExternC() && New->isExternC())
726 return false;
727
John McCall1f82f242009-11-18 22:49:29 +0000728 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
729 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
730
731 // C++ [temp.fct]p2:
732 // A function template can be overloaded with other function templates
733 // and with normal (non-template) functions.
734 if ((OldTemplate == 0) != (NewTemplate == 0))
735 return true;
736
737 // Is the function New an overload of the function Old?
738 QualType OldQType = Context.getCanonicalType(Old->getType());
739 QualType NewQType = Context.getCanonicalType(New->getType());
740
741 // Compare the signatures (C++ 1.3.10) of the two functions to
742 // determine whether they are overloads. If we find any mismatch
743 // in the signature, they are overloads.
744
745 // If either of these functions is a K&R-style function (no
746 // prototype), then we consider them to have matching signatures.
747 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
748 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
749 return false;
750
John McCall424cec92011-01-19 06:33:43 +0000751 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
752 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000753
754 // The signature of a function includes the types of its
755 // parameters (C++ 1.3.10), which includes the presence or absence
756 // of the ellipsis; see C++ DR 357).
757 if (OldQType != NewQType &&
758 (OldType->getNumArgs() != NewType->getNumArgs() ||
759 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000760 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000761 return true;
762
763 // C++ [temp.over.link]p4:
764 // The signature of a function template consists of its function
765 // signature, its return type and its template parameter list. The names
766 // of the template parameters are significant only for establishing the
767 // relationship between the template parameters and the rest of the
768 // signature.
769 //
770 // We check the return type and template parameter lists for function
771 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000772 //
773 // However, we don't consider either of these when deciding whether
774 // a member introduced by a shadow declaration is hidden.
775 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000776 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
777 OldTemplate->getTemplateParameters(),
778 false, TPL_TemplateMatch) ||
779 OldType->getResultType() != NewType->getResultType()))
780 return true;
781
782 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000783 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000784 //
785 // As part of this, also check whether one of the member functions
786 // is static, in which case they are not overloads (C++
787 // 13.1p2). While not part of the definition of the signature,
788 // this check is important to determine whether these functions
789 // can be overloaded.
790 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
791 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
792 if (OldMethod && NewMethod &&
793 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000794 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000795 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
796 if (!UseUsingDeclRules &&
797 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
798 (OldMethod->getRefQualifier() == RQ_None ||
799 NewMethod->getRefQualifier() == RQ_None)) {
800 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 // - Member function declarations with the same name and the same
802 // parameter-type-list as well as member function template
803 // declarations with the same name, the same parameter-type-list, and
804 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000805 // them, but not all, have a ref-qualifier (8.3.5).
806 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
807 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
808 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
John McCall1f82f242009-11-18 22:49:29 +0000811 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813
John McCall1f82f242009-11-18 22:49:29 +0000814 // The signatures match; this is not an overload.
815 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816}
817
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000818/// \brief Checks availability of the function depending on the current
819/// function context. Inside an unavailable function, unavailability is ignored.
820///
821/// \returns true if \arg FD is unavailable and current context is inside
822/// an available function, false otherwise.
823bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
824 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
825}
826
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000827/// \brief Tries a user-defined conversion from From to ToType.
828///
829/// Produces an implicit conversion sequence for when a standard conversion
830/// is not an option. See TryImplicitConversion for more information.
831static ImplicitConversionSequence
832TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
833 bool SuppressUserConversions,
834 bool AllowExplicit,
835 bool InOverloadResolution,
836 bool CStyle,
837 bool AllowObjCWritebackConversion) {
838 ImplicitConversionSequence ICS;
839
840 if (SuppressUserConversions) {
841 // We're not in the case above, so there is no conversion that
842 // we can perform.
843 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
844 return ICS;
845 }
846
847 // Attempt user-defined conversion.
848 OverloadCandidateSet Conversions(From->getExprLoc());
849 OverloadingResult UserDefResult
850 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
851 AllowExplicit);
852
853 if (UserDefResult == OR_Success) {
854 ICS.setUserDefined();
855 // C++ [over.ics.user]p4:
856 // A conversion of an expression of class type to the same class
857 // type is given Exact Match rank, and a conversion of an
858 // expression of class type to a base class of that type is
859 // given Conversion rank, in spite of the fact that a copy
860 // constructor (i.e., a user-defined conversion function) is
861 // called for those cases.
862 if (CXXConstructorDecl *Constructor
863 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
864 QualType FromCanon
865 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
866 QualType ToCanon
867 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
868 if (Constructor->isCopyConstructor() &&
869 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
870 // Turn this into a "standard" conversion sequence, so that it
871 // gets ranked with standard conversion sequences.
872 ICS.setStandard();
873 ICS.Standard.setAsIdentityConversion();
874 ICS.Standard.setFromType(From->getType());
875 ICS.Standard.setAllToTypes(ToType);
876 ICS.Standard.CopyConstructor = Constructor;
877 if (ToCanon != FromCanon)
878 ICS.Standard.Second = ICK_Derived_To_Base;
879 }
880 }
881
882 // C++ [over.best.ics]p4:
883 // However, when considering the argument of a user-defined
884 // conversion function that is a candidate by 13.3.1.3 when
885 // invoked for the copying of the temporary in the second step
886 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
887 // 13.3.1.6 in all cases, only standard conversion sequences and
888 // ellipsis conversion sequences are allowed.
889 if (SuppressUserConversions && ICS.isUserDefined()) {
890 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
891 }
892 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
893 ICS.setAmbiguous();
894 ICS.Ambiguous.setFromType(From->getType());
895 ICS.Ambiguous.setToType(ToType);
896 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
897 Cand != Conversions.end(); ++Cand)
898 if (Cand->Viable)
899 ICS.Ambiguous.addConversion(Cand->Function);
900 } else {
901 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
902 }
903
904 return ICS;
905}
906
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000907/// TryImplicitConversion - Attempt to perform an implicit conversion
908/// from the given expression (Expr) to the given type (ToType). This
909/// function returns an implicit conversion sequence that can be used
910/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911///
912/// void f(float f);
913/// void g(int i) { f(i); }
914///
915/// this routine would produce an implicit conversion sequence to
916/// describe the initialization of f from i, which will be a standard
917/// conversion sequence containing an lvalue-to-rvalue conversion (C++
918/// 4.1) followed by a floating-integral conversion (C++ 4.9).
919//
920/// Note that this routine only determines how the conversion can be
921/// performed; it does not actually perform the conversion. As such,
922/// it will not produce any diagnostics if no conversion is available,
923/// but will instead return an implicit conversion sequence of kind
924/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000925///
926/// If @p SuppressUserConversions, then user-defined conversions are
927/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000928/// If @p AllowExplicit, then explicit user-defined conversions are
929/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000930///
931/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
932/// writeback conversion, which allows __autoreleasing id* parameters to
933/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000934static ImplicitConversionSequence
935TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
936 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000937 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000938 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000939 bool CStyle,
940 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000941 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000942 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000943 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000944 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000945 return ICS;
946 }
947
John McCall5c32be02010-08-24 20:38:10 +0000948 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000949 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000950 return ICS;
951 }
952
Douglas Gregor836a7e82010-08-11 02:15:33 +0000953 // C++ [over.ics.user]p4:
954 // A conversion of an expression of class type to the same class
955 // type is given Exact Match rank, and a conversion of an
956 // expression of class type to a base class of that type is
957 // given Conversion rank, in spite of the fact that a copy/move
958 // constructor (i.e., a user-defined conversion function) is
959 // called for those cases.
960 QualType FromType = From->getType();
961 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000962 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
963 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000964 ICS.setStandard();
965 ICS.Standard.setAsIdentityConversion();
966 ICS.Standard.setFromType(FromType);
967 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000968
Douglas Gregor5ab11652010-04-17 22:01:05 +0000969 // We don't actually check at this point whether there is a valid
970 // copy/move constructor, since overloading just assumes that it
971 // exists. When we actually perform initialization, we'll find the
972 // appropriate constructor to copy the returned object, if needed.
973 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000974
Douglas Gregor5ab11652010-04-17 22:01:05 +0000975 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000976 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000977 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000978
Douglas Gregor836a7e82010-08-11 02:15:33 +0000979 return ICS;
980 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000981
Sebastian Redl6901c0d2011-12-22 18:58:38 +0000982 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
983 AllowExplicit, InOverloadResolution, CStyle,
984 AllowObjCWritebackConversion);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000985}
986
John McCall31168b02011-06-15 23:02:42 +0000987ImplicitConversionSequence
988Sema::TryImplicitConversion(Expr *From, QualType ToType,
989 bool SuppressUserConversions,
990 bool AllowExplicit,
991 bool InOverloadResolution,
992 bool CStyle,
993 bool AllowObjCWritebackConversion) {
994 return clang::TryImplicitConversion(*this, From, ToType,
995 SuppressUserConversions, AllowExplicit,
996 InOverloadResolution, CStyle,
997 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000998}
999
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001000/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001001/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001002/// converted expression. Flavor is the kind of conversion we're
1003/// performing, used in the error message. If @p AllowExplicit,
1004/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001005ExprResult
1006Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001007 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001008 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001009 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001010}
1011
John Wiegley01296292011-04-08 18:41:53 +00001012ExprResult
1013Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001014 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001015 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001016 if (checkPlaceholderForOverload(*this, From))
1017 return ExprError();
1018
John McCall31168b02011-06-15 23:02:42 +00001019 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1020 bool AllowObjCWritebackConversion
1021 = getLangOptions().ObjCAutoRefCount &&
1022 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001023
John McCall5c32be02010-08-24 20:38:10 +00001024 ICS = clang::TryImplicitConversion(*this, From, ToType,
1025 /*SuppressUserConversions=*/false,
1026 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001027 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001028 /*CStyle=*/false,
1029 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001030 return PerformImplicitConversion(From, ToType, ICS, Action);
1031}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001032
1033/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001034/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001035bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1036 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001037 if (Context.hasSameUnqualifiedType(FromType, ToType))
1038 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001039
John McCall991eb4b2010-12-21 00:44:39 +00001040 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1041 // where F adds one of the following at most once:
1042 // - a pointer
1043 // - a member pointer
1044 // - a block pointer
1045 CanQualType CanTo = Context.getCanonicalType(ToType);
1046 CanQualType CanFrom = Context.getCanonicalType(FromType);
1047 Type::TypeClass TyClass = CanTo->getTypeClass();
1048 if (TyClass != CanFrom->getTypeClass()) return false;
1049 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1050 if (TyClass == Type::Pointer) {
1051 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1052 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1053 } else if (TyClass == Type::BlockPointer) {
1054 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1055 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1056 } else if (TyClass == Type::MemberPointer) {
1057 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1058 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1059 } else {
1060 return false;
1061 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001062
John McCall991eb4b2010-12-21 00:44:39 +00001063 TyClass = CanTo->getTypeClass();
1064 if (TyClass != CanFrom->getTypeClass()) return false;
1065 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1066 return false;
1067 }
1068
1069 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1070 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1071 if (!EInfo.getNoReturn()) return false;
1072
1073 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1074 assert(QualType(FromFn, 0).isCanonical());
1075 if (QualType(FromFn, 0) != CanTo) return false;
1076
1077 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001078 return true;
1079}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001080
Douglas Gregor46188682010-05-18 22:42:18 +00001081/// \brief Determine whether the conversion from FromType to ToType is a valid
1082/// vector conversion.
1083///
1084/// \param ICK Will be set to the vector conversion kind, if this is a vector
1085/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1087 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001088 // We need at least one of these types to be a vector type to have a vector
1089 // conversion.
1090 if (!ToType->isVectorType() && !FromType->isVectorType())
1091 return false;
1092
1093 // Identical types require no conversions.
1094 if (Context.hasSameUnqualifiedType(FromType, ToType))
1095 return false;
1096
1097 // There are no conversions between extended vector types, only identity.
1098 if (ToType->isExtVectorType()) {
1099 // There are no conversions between extended vector types other than the
1100 // identity conversion.
1101 if (FromType->isExtVectorType())
1102 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001103
Douglas Gregor46188682010-05-18 22:42:18 +00001104 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001105 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001106 ICK = ICK_Vector_Splat;
1107 return true;
1108 }
1109 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001110
1111 // We can perform the conversion between vector types in the following cases:
1112 // 1)vector types are equivalent AltiVec and GCC vector types
1113 // 2)lax vector conversions are permitted and the vector types are of the
1114 // same size
1115 if (ToType->isVectorType() && FromType->isVectorType()) {
1116 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001117 (Context.getLangOptions().LaxVectorConversions &&
1118 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001119 ICK = ICK_Vector_Conversion;
1120 return true;
1121 }
Douglas Gregor46188682010-05-18 22:42:18 +00001122 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001123
Douglas Gregor46188682010-05-18 22:42:18 +00001124 return false;
1125}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001126
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001127/// IsStandardConversion - Determines whether there is a standard
1128/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1129/// expression From to the type ToType. Standard conversion sequences
1130/// only consider non-class types; for conversions that involve class
1131/// types, use TryImplicitConversion. If a conversion exists, SCS will
1132/// contain the standard conversion sequence required to perform this
1133/// conversion and this routine will return true. Otherwise, this
1134/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001135static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1136 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001137 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001138 bool CStyle,
1139 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001141
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001142 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001143 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001144 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001145 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001146 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001147 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001148
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001149 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001150 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001151 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001152 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001153 return false;
1154
Mike Stump11289f42009-09-09 15:08:12 +00001155 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001156 }
1157
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158 // The first conversion can be an lvalue-to-rvalue conversion,
1159 // array-to-pointer conversion, or function-to-pointer conversion
1160 // (C++ 4p1).
1161
John McCall5c32be02010-08-24 20:38:10 +00001162 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001163 DeclAccessPair AccessPair;
1164 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001166 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001167 // We were able to resolve the address of the overloaded function,
1168 // so we can convert to the type of that function.
1169 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001170
1171 // we can sometimes resolve &foo<int> regardless of ToType, so check
1172 // if the type matches (identity) or we are converting to bool
1173 if (!S.Context.hasSameUnqualifiedType(
1174 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1175 QualType resultTy;
1176 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001177 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001178 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1179 // otherwise, only a boolean conversion is standard
1180 if (!ToType->isBooleanType())
1181 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001183
Chandler Carruthffce2452011-03-29 08:08:18 +00001184 // Check if the "from" expression is taking the address of an overloaded
1185 // function and recompute the FromType accordingly. Take advantage of the
1186 // fact that non-static member functions *must* have such an address-of
1187 // expression.
1188 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1189 if (Method && !Method->isStatic()) {
1190 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1191 "Non-unary operator on non-static member address");
1192 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1193 == UO_AddrOf &&
1194 "Non-address-of operator on non-static member address");
1195 const Type *ClassType
1196 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1197 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001198 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1199 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1200 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001201 "Non-address-of operator for overloaded function expression");
1202 FromType = S.Context.getPointerType(FromType);
1203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001204
Douglas Gregor980fb162010-04-29 18:24:40 +00001205 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001206 assert(S.Context.hasSameType(
1207 FromType,
1208 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001209 } else {
1210 return false;
1211 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001212 }
John McCall154a2fd2011-08-30 00:57:29 +00001213 // Lvalue-to-rvalue conversion (C++11 4.1):
1214 // A glvalue (3.10) of a non-function, non-array type T can
1215 // be converted to a prvalue.
1216 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001217 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001218 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001219 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001220 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001221
1222 // If T is a non-class type, the type of the rvalue is the
1223 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001224 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1225 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001226 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001227 } else if (FromType->isArrayType()) {
1228 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001229 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001230
1231 // An lvalue or rvalue of type "array of N T" or "array of unknown
1232 // bound of T" can be converted to an rvalue of type "pointer to
1233 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001234 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235
John McCall5c32be02010-08-24 20:38:10 +00001236 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001237 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001238 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001239
1240 // For the purpose of ranking in overload resolution
1241 // (13.3.3.1.1), this conversion is considered an
1242 // array-to-pointer conversion followed by a qualification
1243 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001244 SCS.Second = ICK_Identity;
1245 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001246 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001247 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001248 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001249 }
John McCall086a4642010-11-24 05:12:34 +00001250 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001251 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001252 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001253
1254 // An lvalue of function type T can be converted to an rvalue of
1255 // type "pointer to T." The result is a pointer to the
1256 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001257 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001258 } else {
1259 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001260 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001261 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001262 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001263
1264 // The second conversion can be an integral promotion, floating
1265 // point promotion, integral conversion, floating point conversion,
1266 // floating-integral conversion, pointer conversion,
1267 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001268 // For overloading in C, this can also be a "compatible-type"
1269 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001270 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001271 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001272 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001273 // The unqualified versions of the types are the same: there's no
1274 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001275 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001276 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001277 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001278 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001279 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001280 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001281 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001282 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001283 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001284 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001285 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001286 SCS.Second = ICK_Complex_Promotion;
1287 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001288 } else if (ToType->isBooleanType() &&
1289 (FromType->isArithmeticType() ||
1290 FromType->isAnyPointerType() ||
1291 FromType->isBlockPointerType() ||
1292 FromType->isMemberPointerType() ||
1293 FromType->isNullPtrType())) {
1294 // Boolean conversions (C++ 4.12).
1295 SCS.Second = ICK_Boolean_Conversion;
1296 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001297 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001298 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001299 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001300 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001301 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001302 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001303 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001304 SCS.Second = ICK_Complex_Conversion;
1305 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001306 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1307 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001308 // Complex-real conversions (C99 6.3.1.7)
1309 SCS.Second = ICK_Complex_Real;
1310 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001311 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001312 // Floating point conversions (C++ 4.8).
1313 SCS.Second = ICK_Floating_Conversion;
1314 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001316 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001317 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001318 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001319 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001320 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001321 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001322 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001323 SCS.Second = ICK_Block_Pointer_Conversion;
1324 } else if (AllowObjCWritebackConversion &&
1325 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1326 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001327 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1328 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001329 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001330 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001331 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001332 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001333 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001334 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001335 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001336 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001337 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001338 SCS.Second = SecondICK;
1339 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001340 } else if (!S.getLangOptions().CPlusPlus &&
1341 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001342 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001343 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001344 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001345 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001346 // Treat a conversion that strips "noreturn" as an identity conversion.
1347 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001348 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1349 InOverloadResolution,
1350 SCS, CStyle)) {
1351 SCS.Second = ICK_TransparentUnionConversion;
1352 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001353 } else {
1354 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001355 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001356 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001357 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001358
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001359 QualType CanonFrom;
1360 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001361 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001362 bool ObjCLifetimeConversion;
1363 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1364 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001365 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001366 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001367 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001368 CanonFrom = S.Context.getCanonicalType(FromType);
1369 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001370 } else {
1371 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001372 SCS.Third = ICK_Identity;
1373
Mike Stump11289f42009-09-09 15:08:12 +00001374 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001375 // [...] Any difference in top-level cv-qualification is
1376 // subsumed by the initialization itself and does not constitute
1377 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001378 CanonFrom = S.Context.getCanonicalType(FromType);
1379 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001381 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001382 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001383 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1384 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001385 FromType = ToType;
1386 CanonFrom = CanonTo;
1387 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001388 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001389 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001390
1391 // If we have not converted the argument type to the parameter type,
1392 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001393 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001394 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001395
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001396 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001397}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001398
1399static bool
1400IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1401 QualType &ToType,
1402 bool InOverloadResolution,
1403 StandardConversionSequence &SCS,
1404 bool CStyle) {
1405
1406 const RecordType *UT = ToType->getAsUnionType();
1407 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1408 return false;
1409 // The field to initialize within the transparent union.
1410 RecordDecl *UD = UT->getDecl();
1411 // It's compatible if the expression matches any of the fields.
1412 for (RecordDecl::field_iterator it = UD->field_begin(),
1413 itend = UD->field_end();
1414 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001415 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1416 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001417 ToType = it->getType();
1418 return true;
1419 }
1420 }
1421 return false;
1422}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001423
1424/// IsIntegralPromotion - Determines whether the conversion from the
1425/// expression From (whose potentially-adjusted type is FromType) to
1426/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1427/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001428bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001429 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001430 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001431 if (!To) {
1432 return false;
1433 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001434
1435 // An rvalue of type char, signed char, unsigned char, short int, or
1436 // unsigned short int can be converted to an rvalue of type int if
1437 // int can represent all the values of the source type; otherwise,
1438 // the source rvalue can be converted to an rvalue of type unsigned
1439 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001440 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1441 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001442 if (// We can promote any signed, promotable integer type to an int
1443 (FromType->isSignedIntegerType() ||
1444 // We can promote any unsigned integer type whose size is
1445 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001446 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001447 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001448 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001449 }
1450
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001451 return To->getKind() == BuiltinType::UInt;
1452 }
1453
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001454 // C++0x [conv.prom]p3:
1455 // A prvalue of an unscoped enumeration type whose underlying type is not
1456 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1457 // following types that can represent all the values of the enumeration
1458 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1459 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001460 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001461 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001462 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001463 // with lowest integer conversion rank (4.13) greater than the rank of long
1464 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001465 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001466 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1467 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1468 // provided for a scoped enumeration.
1469 if (FromEnumType->getDecl()->isScoped())
1470 return false;
1471
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001472 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001474 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001475 return Context.hasSameUnqualifiedType(ToType,
1476 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001477 }
John McCall56774992009-12-09 09:09:27 +00001478
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001479 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001480 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1481 // to an rvalue a prvalue of the first of the following types that can
1482 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001483 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001485 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001486 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001487 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001488 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001489 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001490 // Determine whether the type we're converting from is signed or
1491 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001492 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001493 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001494
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001495 // The types we'll try to promote to, in the appropriate
1496 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001497 QualType PromoteTypes[6] = {
1498 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001499 Context.LongTy, Context.UnsignedLongTy ,
1500 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001501 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001502 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001503 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1504 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001505 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001506 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1507 // We found the type that we can promote to. If this is the
1508 // type we wanted, we have a promotion. Otherwise, no
1509 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001510 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001511 }
1512 }
1513 }
1514
1515 // An rvalue for an integral bit-field (9.6) can be converted to an
1516 // rvalue of type int if int can represent all the values of the
1517 // bit-field; otherwise, it can be converted to unsigned int if
1518 // unsigned int can represent all the values of the bit-field. If
1519 // the bit-field is larger yet, no integral promotion applies to
1520 // it. If the bit-field has an enumerated type, it is treated as any
1521 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001522 // FIXME: We should delay checking of bit-fields until we actually perform the
1523 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001524 using llvm::APSInt;
1525 if (From)
1526 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001527 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001528 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001529 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1530 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1531 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001532
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001533 // Are we promoting to an int from a bitfield that fits in an int?
1534 if (BitWidth < ToSize ||
1535 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1536 return To->getKind() == BuiltinType::Int;
1537 }
Mike Stump11289f42009-09-09 15:08:12 +00001538
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001539 // Are we promoting to an unsigned int from an unsigned bitfield
1540 // that fits into an unsigned int?
1541 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1542 return To->getKind() == BuiltinType::UInt;
1543 }
Mike Stump11289f42009-09-09 15:08:12 +00001544
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001545 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001546 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547 }
Mike Stump11289f42009-09-09 15:08:12 +00001548
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549 // An rvalue of type bool can be converted to an rvalue of type int,
1550 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001551 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001552 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001553 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001554
1555 return false;
1556}
1557
1558/// IsFloatingPointPromotion - Determines whether the conversion from
1559/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1560/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001561bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001562 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1563 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001564 /// An rvalue of type float can be converted to an rvalue of type
1565 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001566 if (FromBuiltin->getKind() == BuiltinType::Float &&
1567 ToBuiltin->getKind() == BuiltinType::Double)
1568 return true;
1569
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001570 // C99 6.3.1.5p1:
1571 // When a float is promoted to double or long double, or a
1572 // double is promoted to long double [...].
1573 if (!getLangOptions().CPlusPlus &&
1574 (FromBuiltin->getKind() == BuiltinType::Float ||
1575 FromBuiltin->getKind() == BuiltinType::Double) &&
1576 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1577 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001578
1579 // Half can be promoted to float.
1580 if (FromBuiltin->getKind() == BuiltinType::Half &&
1581 ToBuiltin->getKind() == BuiltinType::Float)
1582 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001583 }
1584
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585 return false;
1586}
1587
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001588/// \brief Determine if a conversion is a complex promotion.
1589///
1590/// A complex promotion is defined as a complex -> complex conversion
1591/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001592/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001593bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001594 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001595 if (!FromComplex)
1596 return false;
1597
John McCall9dd450b2009-09-21 23:43:11 +00001598 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001599 if (!ToComplex)
1600 return false;
1601
1602 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001603 ToComplex->getElementType()) ||
1604 IsIntegralPromotion(0, FromComplex->getElementType(),
1605 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001606}
1607
Douglas Gregor237f96c2008-11-26 23:31:11 +00001608/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1609/// the pointer type FromPtr to a pointer to type ToPointee, with the
1610/// same type qualifiers as FromPtr has on its pointee type. ToType,
1611/// if non-empty, will be a pointer to ToType that may or may not have
1612/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001613///
Mike Stump11289f42009-09-09 15:08:12 +00001614static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001615BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001616 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001617 ASTContext &Context,
1618 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001619 assert((FromPtr->getTypeClass() == Type::Pointer ||
1620 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1621 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001622
John McCall31168b02011-06-15 23:02:42 +00001623 /// Conversions to 'id' subsume cv-qualifier conversions.
1624 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001625 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001626
1627 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001628 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001629 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001630 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001631
John McCall31168b02011-06-15 23:02:42 +00001632 if (StripObjCLifetime)
1633 Quals.removeObjCLifetime();
1634
Mike Stump11289f42009-09-09 15:08:12 +00001635 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001636 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001637 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001638 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001639 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001640
1641 // Build a pointer to ToPointee. It has the right qualifiers
1642 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001643 if (isa<ObjCObjectPointerType>(ToType))
1644 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001645 return Context.getPointerType(ToPointee);
1646 }
1647
1648 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001649 QualType QualifiedCanonToPointee
1650 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001651
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001652 if (isa<ObjCObjectPointerType>(ToType))
1653 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1654 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001655}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001656
Mike Stump11289f42009-09-09 15:08:12 +00001657static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001658 bool InOverloadResolution,
1659 ASTContext &Context) {
1660 // Handle value-dependent integral null pointer constants correctly.
1661 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1662 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001663 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001664 return !InOverloadResolution;
1665
Douglas Gregor56751b52009-09-25 04:25:58 +00001666 return Expr->isNullPointerConstant(Context,
1667 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1668 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001669}
Mike Stump11289f42009-09-09 15:08:12 +00001670
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671/// IsPointerConversion - Determines whether the conversion of the
1672/// expression From, which has the (possibly adjusted) type FromType,
1673/// can be converted to the type ToType via a pointer conversion (C++
1674/// 4.10). If so, returns true and places the converted type (that
1675/// might differ from ToType in its cv-qualifiers at some level) into
1676/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001677///
Douglas Gregora29dc052008-11-27 01:19:21 +00001678/// This routine also supports conversions to and from block pointers
1679/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1680/// pointers to interfaces. FIXME: Once we've determined the
1681/// appropriate overloading rules for Objective-C, we may want to
1682/// split the Objective-C checks into a different routine; however,
1683/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001684/// conversions, so for now they live here. IncompatibleObjC will be
1685/// set if the conversion is an allowed Objective-C conversion that
1686/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001688 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001689 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001690 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001691 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001692 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1693 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001694 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001695
Mike Stump11289f42009-09-09 15:08:12 +00001696 // Conversion from a null pointer constant to any Objective-C pointer type.
1697 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001698 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001699 ConvertedType = ToType;
1700 return true;
1701 }
1702
Douglas Gregor231d1c62008-11-27 00:15:41 +00001703 // Blocks: Block pointers can be converted to void*.
1704 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001705 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001706 ConvertedType = ToType;
1707 return true;
1708 }
1709 // Blocks: A null pointer constant can be converted to a block
1710 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001711 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001712 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001713 ConvertedType = ToType;
1714 return true;
1715 }
1716
Sebastian Redl576fd422009-05-10 18:38:11 +00001717 // If the left-hand-side is nullptr_t, the right side can be a null
1718 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001719 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001720 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001721 ConvertedType = ToType;
1722 return true;
1723 }
1724
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001725 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001726 if (!ToTypePtr)
1727 return false;
1728
1729 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001730 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001731 ConvertedType = ToType;
1732 return true;
1733 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001734
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001736 // , including objective-c pointers.
1737 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001738 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1739 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001740 ConvertedType = BuildSimilarlyQualifiedPointerType(
1741 FromType->getAs<ObjCObjectPointerType>(),
1742 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001743 ToType, Context);
1744 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001745 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001746 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001747 if (!FromTypePtr)
1748 return false;
1749
1750 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001751
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001752 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001753 // pointer conversion, so don't do all of the work below.
1754 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1755 return false;
1756
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757 // An rvalue of type "pointer to cv T," where T is an object type,
1758 // can be converted to an rvalue of type "pointer to cv void" (C++
1759 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001760 if (FromPointeeType->isIncompleteOrObjectType() &&
1761 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001762 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001763 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001764 ToType, Context,
1765 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001766 return true;
1767 }
1768
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001769 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001770 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001771 ToPointeeType->isVoidType()) {
1772 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1773 ToPointeeType,
1774 ToType, Context);
1775 return true;
1776 }
1777
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001778 // When we're overloading in C, we allow a special kind of pointer
1779 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001780 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001781 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001782 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001783 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001784 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001785 return true;
1786 }
1787
Douglas Gregor5c407d92008-10-23 00:40:37 +00001788 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001789 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001790 // An rvalue of type "pointer to cv D," where D is a class type,
1791 // can be converted to an rvalue of type "pointer to cv B," where
1792 // B is a base class (clause 10) of D. If B is an inaccessible
1793 // (clause 11) or ambiguous (10.2) base class of D, a program that
1794 // necessitates this conversion is ill-formed. The result of the
1795 // conversion is a pointer to the base class sub-object of the
1796 // derived class object. The null pointer value is converted to
1797 // the null pointer value of the destination type.
1798 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001799 // Note that we do not check for ambiguity or inaccessibility
1800 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001801 if (getLangOptions().CPlusPlus &&
1802 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001803 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001804 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001805 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001806 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001807 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001808 ToType, Context);
1809 return true;
1810 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001811
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001812 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1813 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1814 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1815 ToPointeeType,
1816 ToType, Context);
1817 return true;
1818 }
1819
Douglas Gregora119f102008-12-19 19:13:09 +00001820 return false;
1821}
Douglas Gregoraec25842011-04-26 23:16:46 +00001822
1823/// \brief Adopt the given qualifiers for the given type.
1824static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1825 Qualifiers TQs = T.getQualifiers();
1826
1827 // Check whether qualifiers already match.
1828 if (TQs == Qs)
1829 return T;
1830
1831 if (Qs.compatiblyIncludes(TQs))
1832 return Context.getQualifiedType(T, Qs);
1833
1834 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1835}
Douglas Gregora119f102008-12-19 19:13:09 +00001836
1837/// isObjCPointerConversion - Determines whether this is an
1838/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1839/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001840bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001841 QualType& ConvertedType,
1842 bool &IncompatibleObjC) {
1843 if (!getLangOptions().ObjC1)
1844 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001845
Douglas Gregoraec25842011-04-26 23:16:46 +00001846 // The set of qualifiers on the type we're converting from.
1847 Qualifiers FromQualifiers = FromType.getQualifiers();
1848
Steve Naroff7cae42b2009-07-10 23:34:53 +00001849 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001850 const ObjCObjectPointerType* ToObjCPtr =
1851 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001852 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001853 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001854
Steve Naroff7cae42b2009-07-10 23:34:53 +00001855 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001856 // If the pointee types are the same (ignoring qualifications),
1857 // then this is not a pointer conversion.
1858 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1859 FromObjCPtr->getPointeeType()))
1860 return false;
1861
Douglas Gregoraec25842011-04-26 23:16:46 +00001862 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001863 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001864 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001865 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001866 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001867 return true;
1868 }
1869 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001870 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001871 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001872 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001873 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001874 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001875 return true;
1876 }
1877 // Objective C++: We're able to convert from a pointer to an
1878 // interface to a pointer to a different interface.
1879 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001880 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1881 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1882 if (getLangOptions().CPlusPlus && LHS && RHS &&
1883 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1884 FromObjCPtr->getPointeeType()))
1885 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001887 ToObjCPtr->getPointeeType(),
1888 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001889 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001890 return true;
1891 }
1892
1893 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1894 // Okay: this is some kind of implicit downcast of Objective-C
1895 // interfaces, which is permitted. However, we're going to
1896 // complain about it.
1897 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001898 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001899 ToObjCPtr->getPointeeType(),
1900 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001901 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001902 return true;
1903 }
Mike Stump11289f42009-09-09 15:08:12 +00001904 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001905 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001906 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001907 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001908 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001909 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001910 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001911 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001912 // to a block pointer type.
1913 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001914 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001915 return true;
1916 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001917 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001919 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001920 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001921 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001922 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001923 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001924 return true;
1925 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001926 else
Douglas Gregora119f102008-12-19 19:13:09 +00001927 return false;
1928
Douglas Gregor033f56d2008-12-23 00:53:59 +00001929 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001930 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001931 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001932 else if (const BlockPointerType *FromBlockPtr =
1933 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001934 FromPointeeType = FromBlockPtr->getPointeeType();
1935 else
Douglas Gregora119f102008-12-19 19:13:09 +00001936 return false;
1937
Douglas Gregora119f102008-12-19 19:13:09 +00001938 // If we have pointers to pointers, recursively check whether this
1939 // is an Objective-C conversion.
1940 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1941 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1942 IncompatibleObjC)) {
1943 // We always complain about this conversion.
1944 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001945 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001946 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001947 return true;
1948 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001949 // Allow conversion of pointee being objective-c pointer to another one;
1950 // as in I* to id.
1951 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1952 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1953 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1954 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001955
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001956 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001957 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001958 return true;
1959 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001960
Douglas Gregor033f56d2008-12-23 00:53:59 +00001961 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001962 // differences in the argument and result types are in Objective-C
1963 // pointer conversions. If so, we permit the conversion (but
1964 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001965 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001966 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001967 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001968 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001969 if (FromFunctionType && ToFunctionType) {
1970 // If the function types are exactly the same, this isn't an
1971 // Objective-C pointer conversion.
1972 if (Context.getCanonicalType(FromPointeeType)
1973 == Context.getCanonicalType(ToPointeeType))
1974 return false;
1975
1976 // Perform the quick checks that will tell us whether these
1977 // function types are obviously different.
1978 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1979 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1980 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1981 return false;
1982
1983 bool HasObjCConversion = false;
1984 if (Context.getCanonicalType(FromFunctionType->getResultType())
1985 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1986 // Okay, the types match exactly. Nothing to do.
1987 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1988 ToFunctionType->getResultType(),
1989 ConvertedType, IncompatibleObjC)) {
1990 // Okay, we have an Objective-C pointer conversion.
1991 HasObjCConversion = true;
1992 } else {
1993 // Function types are too different. Abort.
1994 return false;
1995 }
Mike Stump11289f42009-09-09 15:08:12 +00001996
Douglas Gregora119f102008-12-19 19:13:09 +00001997 // Check argument types.
1998 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1999 ArgIdx != NumArgs; ++ArgIdx) {
2000 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2001 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2002 if (Context.getCanonicalType(FromArgType)
2003 == Context.getCanonicalType(ToArgType)) {
2004 // Okay, the types match exactly. Nothing to do.
2005 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2006 ConvertedType, IncompatibleObjC)) {
2007 // Okay, we have an Objective-C pointer conversion.
2008 HasObjCConversion = true;
2009 } else {
2010 // Argument types are too different. Abort.
2011 return false;
2012 }
2013 }
2014
2015 if (HasObjCConversion) {
2016 // We had an Objective-C conversion. Allow this pointer
2017 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002018 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002019 IncompatibleObjC = true;
2020 return true;
2021 }
2022 }
2023
Sebastian Redl72b597d2009-01-25 19:43:20 +00002024 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002025}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002026
John McCall31168b02011-06-15 23:02:42 +00002027/// \brief Determine whether this is an Objective-C writeback conversion,
2028/// used for parameter passing when performing automatic reference counting.
2029///
2030/// \param FromType The type we're converting form.
2031///
2032/// \param ToType The type we're converting to.
2033///
2034/// \param ConvertedType The type that will be produced after applying
2035/// this conversion.
2036bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2037 QualType &ConvertedType) {
2038 if (!getLangOptions().ObjCAutoRefCount ||
2039 Context.hasSameUnqualifiedType(FromType, ToType))
2040 return false;
2041
2042 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2043 QualType ToPointee;
2044 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2045 ToPointee = ToPointer->getPointeeType();
2046 else
2047 return false;
2048
2049 Qualifiers ToQuals = ToPointee.getQualifiers();
2050 if (!ToPointee->isObjCLifetimeType() ||
2051 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2052 !ToQuals.withoutObjCGLifetime().empty())
2053 return false;
2054
2055 // Argument must be a pointer to __strong to __weak.
2056 QualType FromPointee;
2057 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2058 FromPointee = FromPointer->getPointeeType();
2059 else
2060 return false;
2061
2062 Qualifiers FromQuals = FromPointee.getQualifiers();
2063 if (!FromPointee->isObjCLifetimeType() ||
2064 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2065 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2066 return false;
2067
2068 // Make sure that we have compatible qualifiers.
2069 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2070 if (!ToQuals.compatiblyIncludes(FromQuals))
2071 return false;
2072
2073 // Remove qualifiers from the pointee type we're converting from; they
2074 // aren't used in the compatibility check belong, and we'll be adding back
2075 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2076 FromPointee = FromPointee.getUnqualifiedType();
2077
2078 // The unqualified form of the pointee types must be compatible.
2079 ToPointee = ToPointee.getUnqualifiedType();
2080 bool IncompatibleObjC;
2081 if (Context.typesAreCompatible(FromPointee, ToPointee))
2082 FromPointee = ToPointee;
2083 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2084 IncompatibleObjC))
2085 return false;
2086
2087 /// \brief Construct the type we're converting to, which is a pointer to
2088 /// __autoreleasing pointee.
2089 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2090 ConvertedType = Context.getPointerType(FromPointee);
2091 return true;
2092}
2093
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002094bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2095 QualType& ConvertedType) {
2096 QualType ToPointeeType;
2097 if (const BlockPointerType *ToBlockPtr =
2098 ToType->getAs<BlockPointerType>())
2099 ToPointeeType = ToBlockPtr->getPointeeType();
2100 else
2101 return false;
2102
2103 QualType FromPointeeType;
2104 if (const BlockPointerType *FromBlockPtr =
2105 FromType->getAs<BlockPointerType>())
2106 FromPointeeType = FromBlockPtr->getPointeeType();
2107 else
2108 return false;
2109 // We have pointer to blocks, check whether the only
2110 // differences in the argument and result types are in Objective-C
2111 // pointer conversions. If so, we permit the conversion.
2112
2113 const FunctionProtoType *FromFunctionType
2114 = FromPointeeType->getAs<FunctionProtoType>();
2115 const FunctionProtoType *ToFunctionType
2116 = ToPointeeType->getAs<FunctionProtoType>();
2117
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002118 if (!FromFunctionType || !ToFunctionType)
2119 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002120
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002121 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002122 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002123
2124 // Perform the quick checks that will tell us whether these
2125 // function types are obviously different.
2126 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2127 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2128 return false;
2129
2130 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2131 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2132 if (FromEInfo != ToEInfo)
2133 return false;
2134
2135 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002136 if (Context.hasSameType(FromFunctionType->getResultType(),
2137 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002138 // Okay, the types match exactly. Nothing to do.
2139 } else {
2140 QualType RHS = FromFunctionType->getResultType();
2141 QualType LHS = ToFunctionType->getResultType();
2142 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2143 !RHS.hasQualifiers() && LHS.hasQualifiers())
2144 LHS = LHS.getUnqualifiedType();
2145
2146 if (Context.hasSameType(RHS,LHS)) {
2147 // OK exact match.
2148 } else if (isObjCPointerConversion(RHS, LHS,
2149 ConvertedType, IncompatibleObjC)) {
2150 if (IncompatibleObjC)
2151 return false;
2152 // Okay, we have an Objective-C pointer conversion.
2153 }
2154 else
2155 return false;
2156 }
2157
2158 // Check argument types.
2159 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2160 ArgIdx != NumArgs; ++ArgIdx) {
2161 IncompatibleObjC = false;
2162 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2163 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2164 if (Context.hasSameType(FromArgType, ToArgType)) {
2165 // Okay, the types match exactly. Nothing to do.
2166 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2167 ConvertedType, IncompatibleObjC)) {
2168 if (IncompatibleObjC)
2169 return false;
2170 // Okay, we have an Objective-C pointer conversion.
2171 } else
2172 // Argument types are too different. Abort.
2173 return false;
2174 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002175 if (LangOpts.ObjCAutoRefCount &&
2176 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2177 ToFunctionType))
2178 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002179
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002180 ConvertedType = ToType;
2181 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002182}
2183
Richard Trieucaff2472011-11-23 22:32:32 +00002184enum {
2185 ft_default,
2186 ft_different_class,
2187 ft_parameter_arity,
2188 ft_parameter_mismatch,
2189 ft_return_type,
2190 ft_qualifer_mismatch
2191};
2192
2193/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2194/// function types. Catches different number of parameter, mismatch in
2195/// parameter types, and different return types.
2196void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2197 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002198 // If either type is not valid, include no extra info.
2199 if (FromType.isNull() || ToType.isNull()) {
2200 PDiag << ft_default;
2201 return;
2202 }
2203
Richard Trieucaff2472011-11-23 22:32:32 +00002204 // Get the function type from the pointers.
2205 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2206 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2207 *ToMember = ToType->getAs<MemberPointerType>();
2208 if (FromMember->getClass() != ToMember->getClass()) {
2209 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2210 << QualType(FromMember->getClass(), 0);
2211 return;
2212 }
2213 FromType = FromMember->getPointeeType();
2214 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002215 }
2216
Richard Trieu96ed5b62011-12-13 23:19:45 +00002217 if (FromType->isPointerType())
2218 FromType = FromType->getPointeeType();
2219 if (ToType->isPointerType())
2220 ToType = ToType->getPointeeType();
2221
2222 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002223 FromType = FromType.getNonReferenceType();
2224 ToType = ToType.getNonReferenceType();
2225
Richard Trieucaff2472011-11-23 22:32:32 +00002226 // Don't print extra info for non-specialized template functions.
2227 if (FromType->isInstantiationDependentType() &&
2228 !FromType->getAs<TemplateSpecializationType>()) {
2229 PDiag << ft_default;
2230 return;
2231 }
2232
Richard Trieu96ed5b62011-12-13 23:19:45 +00002233 // No extra info for same types.
2234 if (Context.hasSameType(FromType, ToType)) {
2235 PDiag << ft_default;
2236 return;
2237 }
2238
Richard Trieucaff2472011-11-23 22:32:32 +00002239 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2240 *ToFunction = ToType->getAs<FunctionProtoType>();
2241
2242 // Both types need to be function types.
2243 if (!FromFunction || !ToFunction) {
2244 PDiag << ft_default;
2245 return;
2246 }
2247
2248 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2249 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2250 << FromFunction->getNumArgs();
2251 return;
2252 }
2253
2254 // Handle different parameter types.
2255 unsigned ArgPos;
2256 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2257 PDiag << ft_parameter_mismatch << ArgPos + 1
2258 << ToFunction->getArgType(ArgPos)
2259 << FromFunction->getArgType(ArgPos);
2260 return;
2261 }
2262
2263 // Handle different return type.
2264 if (!Context.hasSameType(FromFunction->getResultType(),
2265 ToFunction->getResultType())) {
2266 PDiag << ft_return_type << ToFunction->getResultType()
2267 << FromFunction->getResultType();
2268 return;
2269 }
2270
2271 unsigned FromQuals = FromFunction->getTypeQuals(),
2272 ToQuals = ToFunction->getTypeQuals();
2273 if (FromQuals != ToQuals) {
2274 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2275 return;
2276 }
2277
2278 // Unable to find a difference, so add no extra info.
2279 PDiag << ft_default;
2280}
2281
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002282/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002283/// for equality of their argument types. Caller has already checked that
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002284/// they have same number of arguments. This routine assumes that Objective-C
2285/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002286/// If the parameters are different, ArgPos will have the the parameter index
2287/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002288bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002289 const FunctionProtoType *NewType,
2290 unsigned *ArgPos) {
2291 if (!getLangOptions().ObjC1) {
2292 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2293 N = NewType->arg_type_begin(),
2294 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2295 if (!Context.hasSameType(*O, *N)) {
2296 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2297 return false;
2298 }
2299 }
2300 return true;
2301 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002302
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002303 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2304 N = NewType->arg_type_begin(),
2305 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2306 QualType ToType = (*O);
2307 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002308 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002309 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2310 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002311 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2312 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2313 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2314 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002315 continue;
2316 }
John McCall8b07ec22010-05-15 11:32:37 +00002317 else if (const ObjCObjectPointerType *PTTo =
2318 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002319 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002320 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregor2039ca02011-12-15 17:15:07 +00002321 if (Context.hasSameUnqualifiedType(
2322 PTTo->getObjectType()->getBaseType(),
2323 PTFr->getObjectType()->getBaseType()))
John McCall8b07ec22010-05-15 11:32:37 +00002324 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002325 }
Richard Trieucaff2472011-11-23 22:32:32 +00002326 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002327 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002328 }
2329 }
2330 return true;
2331}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002332
Douglas Gregor39c16d42008-10-24 04:54:22 +00002333/// CheckPointerConversion - Check the pointer conversion from the
2334/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002335/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002336/// conversions for which IsPointerConversion has already returned
2337/// true. It returns true and produces a diagnostic if there was an
2338/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002339bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002340 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002341 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002342 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002343 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002344 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002345
John McCall8cb679e2010-11-15 09:13:47 +00002346 Kind = CK_BitCast;
2347
Chandler Carruthffab8732011-04-09 07:32:05 +00002348 if (!IsCStyleOrFunctionalCast &&
2349 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2350 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2351 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002352 PDiag(diag::warn_impcast_bool_to_null_pointer)
2353 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002354
John McCall9320b872011-09-09 05:25:32 +00002355 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2356 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002357 QualType FromPointeeType = FromPtrType->getPointeeType(),
2358 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002359
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002360 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2361 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002362 // We must have a derived-to-base conversion. Check an
2363 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002364 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2365 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002366 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002367 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002368 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002369
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002370 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002371 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002372 }
2373 }
John McCall9320b872011-09-09 05:25:32 +00002374 } else if (const ObjCObjectPointerType *ToPtrType =
2375 ToType->getAs<ObjCObjectPointerType>()) {
2376 if (const ObjCObjectPointerType *FromPtrType =
2377 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002378 // Objective-C++ conversions are always okay.
2379 // FIXME: We should have a different class of conversions for the
2380 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002381 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002382 return false;
John McCall9320b872011-09-09 05:25:32 +00002383 } else if (FromType->isBlockPointerType()) {
2384 Kind = CK_BlockPointerToObjCPointerCast;
2385 } else {
2386 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002387 }
John McCall9320b872011-09-09 05:25:32 +00002388 } else if (ToType->isBlockPointerType()) {
2389 if (!FromType->isBlockPointerType())
2390 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002391 }
John McCall8cb679e2010-11-15 09:13:47 +00002392
2393 // We shouldn't fall into this case unless it's valid for other
2394 // reasons.
2395 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2396 Kind = CK_NullToPointer;
2397
Douglas Gregor39c16d42008-10-24 04:54:22 +00002398 return false;
2399}
2400
Sebastian Redl72b597d2009-01-25 19:43:20 +00002401/// IsMemberPointerConversion - Determines whether the conversion of the
2402/// expression From, which has the (possibly adjusted) type FromType, can be
2403/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2404/// If so, returns true and places the converted type (that might differ from
2405/// ToType in its cv-qualifiers at some level) into ConvertedType.
2406bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002407 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002408 bool InOverloadResolution,
2409 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002410 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002411 if (!ToTypePtr)
2412 return false;
2413
2414 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002415 if (From->isNullPointerConstant(Context,
2416 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2417 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002418 ConvertedType = ToType;
2419 return true;
2420 }
2421
2422 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002423 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002424 if (!FromTypePtr)
2425 return false;
2426
2427 // A pointer to member of B can be converted to a pointer to member of D,
2428 // where D is derived from B (C++ 4.11p2).
2429 QualType FromClass(FromTypePtr->getClass(), 0);
2430 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002431
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002432 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2433 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2434 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002435 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2436 ToClass.getTypePtr());
2437 return true;
2438 }
2439
2440 return false;
2441}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002442
Sebastian Redl72b597d2009-01-25 19:43:20 +00002443/// CheckMemberPointerConversion - Check the member pointer conversion from the
2444/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002445/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002446/// for which IsMemberPointerConversion has already returned true. It returns
2447/// true and produces a diagnostic if there was an error, or returns false
2448/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002449bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002450 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002451 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002452 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002453 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002454 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002455 if (!FromPtrType) {
2456 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002457 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002458 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002459 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002460 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002461 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002462 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002463
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002464 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002465 assert(ToPtrType && "No member pointer cast has a target type "
2466 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002467
Sebastian Redled8f2002009-01-28 18:33:18 +00002468 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2469 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002470
Sebastian Redled8f2002009-01-28 18:33:18 +00002471 // FIXME: What about dependent types?
2472 assert(FromClass->isRecordType() && "Pointer into non-class.");
2473 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002474
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002475 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002476 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002477 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2478 assert(DerivationOkay &&
2479 "Should not have been called if derivation isn't OK.");
2480 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002481
Sebastian Redled8f2002009-01-28 18:33:18 +00002482 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2483 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002484 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2485 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2486 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2487 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002488 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002489
Douglas Gregor89ee6822009-02-28 01:32:25 +00002490 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002491 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2492 << FromClass << ToClass << QualType(VBase, 0)
2493 << From->getSourceRange();
2494 return true;
2495 }
2496
John McCall5b0829a2010-02-10 09:31:12 +00002497 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002498 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2499 Paths.front(),
2500 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002501
Anders Carlssond7923c62009-08-22 23:33:40 +00002502 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002503 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002504 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002505 return false;
2506}
2507
Douglas Gregor9a657932008-10-21 23:43:52 +00002508/// IsQualificationConversion - Determines whether the conversion from
2509/// an rvalue of type FromType to ToType is a qualification conversion
2510/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002511///
2512/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2513/// when the qualification conversion involves a change in the Objective-C
2514/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002515bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002516Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002517 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002518 FromType = Context.getCanonicalType(FromType);
2519 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002520 ObjCLifetimeConversion = false;
2521
Douglas Gregor9a657932008-10-21 23:43:52 +00002522 // If FromType and ToType are the same type, this is not a
2523 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002524 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002525 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002526
Douglas Gregor9a657932008-10-21 23:43:52 +00002527 // (C++ 4.4p4):
2528 // A conversion can add cv-qualifiers at levels other than the first
2529 // in multi-level pointers, subject to the following rules: [...]
2530 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002531 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002532 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002533 // Within each iteration of the loop, we check the qualifiers to
2534 // determine if this still looks like a qualification
2535 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002536 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002537 // until there are no more pointers or pointers-to-members left to
2538 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002539 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002540
Douglas Gregor90609aa2011-04-25 18:40:17 +00002541 Qualifiers FromQuals = FromType.getQualifiers();
2542 Qualifiers ToQuals = ToType.getQualifiers();
2543
John McCall31168b02011-06-15 23:02:42 +00002544 // Objective-C ARC:
2545 // Check Objective-C lifetime conversions.
2546 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2547 UnwrappedAnyPointer) {
2548 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2549 ObjCLifetimeConversion = true;
2550 FromQuals.removeObjCLifetime();
2551 ToQuals.removeObjCLifetime();
2552 } else {
2553 // Qualification conversions cannot cast between different
2554 // Objective-C lifetime qualifiers.
2555 return false;
2556 }
2557 }
2558
Douglas Gregorf30053d2011-05-08 06:09:53 +00002559 // Allow addition/removal of GC attributes but not changing GC attributes.
2560 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2561 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2562 FromQuals.removeObjCGCAttr();
2563 ToQuals.removeObjCGCAttr();
2564 }
2565
Douglas Gregor9a657932008-10-21 23:43:52 +00002566 // -- for every j > 0, if const is in cv 1,j then const is in cv
2567 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002568 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002569 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002570
Douglas Gregor9a657932008-10-21 23:43:52 +00002571 // -- if the cv 1,j and cv 2,j are different, then const is in
2572 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002573 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002574 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002575 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002576
Douglas Gregor9a657932008-10-21 23:43:52 +00002577 // Keep track of whether all prior cv-qualifiers in the "to" type
2578 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002579 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002580 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002581 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002582
2583 // We are left with FromType and ToType being the pointee types
2584 // after unwrapping the original FromType and ToType the same number
2585 // of types. If we unwrapped any pointers, and if FromType and
2586 // ToType have the same unqualified type (since we checked
2587 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002588 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002589}
2590
Douglas Gregor576e98c2009-01-30 23:27:23 +00002591/// Determines whether there is a user-defined conversion sequence
2592/// (C++ [over.ics.user]) that converts expression From to the type
2593/// ToType. If such a conversion exists, User will contain the
2594/// user-defined conversion sequence that performs such a conversion
2595/// and this routine will return true. Otherwise, this routine returns
2596/// false and User is unspecified.
2597///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002598/// \param AllowExplicit true if the conversion should consider C++0x
2599/// "explicit" conversion functions as well as non-explicit conversion
2600/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002601static OverloadingResult
2602IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2603 UserDefinedConversionSequence& User,
2604 OverloadCandidateSet& CandidateSet,
2605 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002606 // Whether we will only visit constructors.
2607 bool ConstructorsOnly = false;
2608
2609 // If the type we are conversion to is a class type, enumerate its
2610 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002611 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002612 // C++ [over.match.ctor]p1:
2613 // When objects of class type are direct-initialized (8.5), or
2614 // copy-initialized from an expression of the same or a
2615 // derived class type (8.5), overload resolution selects the
2616 // constructor. [...] For copy-initialization, the candidate
2617 // functions are all the converting constructors (12.3.1) of
2618 // that class. The argument list is the expression-list within
2619 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002620 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002621 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002622 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002623 ConstructorsOnly = true;
2624
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002625 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2626 // RequireCompleteType may have returned true due to some invalid decl
2627 // during template instantiation, but ToType may be complete enough now
2628 // to try to recover.
2629 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002630 // We're not going to find any constructors.
2631 } else if (CXXRecordDecl *ToRecordDecl
2632 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002633
2634 Expr **Args = &From;
2635 unsigned NumArgs = 1;
2636 bool ListInitializing = false;
2637 // If we're list-initializing, we pass the individual elements as
2638 // arguments, not the entire list.
2639 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
2640 Args = InitList->getInits();
2641 NumArgs = InitList->getNumInits();
2642 ListInitializing = true;
2643 }
2644
Douglas Gregor89ee6822009-02-28 01:32:25 +00002645 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002646 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002647 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002648 NamedDecl *D = *Con;
2649 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2650
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002651 // Find the constructor (which may be a template).
2652 CXXConstructorDecl *Constructor = 0;
2653 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002654 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002655 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002656 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002657 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2658 else
John McCalla0296f72010-03-19 07:35:19 +00002659 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002660
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002661 bool Usable = !Constructor->isInvalidDecl();
2662 if (ListInitializing)
2663 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2664 else
2665 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2666 if (Usable) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002667 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002668 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2669 /*ExplicitArgs*/ 0,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002670 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002671 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002672 !ConstructorsOnly &&
2673 !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002674 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002675 // Allow one user-defined conversion when user specifies a
2676 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002677 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002678 Args, NumArgs, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002679 /*SuppressUserConversions=*/
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002680 !ConstructorsOnly && !ListInitializing);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002681 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002682 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002683 }
2684 }
2685
Douglas Gregor5ab11652010-04-17 22:01:05 +00002686 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002687 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall5c32be02010-08-24 20:38:10 +00002688 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2689 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002690 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002691 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002692 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002693 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002694 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2695 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002696 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002697 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002698 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002699 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002700 DeclAccessPair FoundDecl = I.getPair();
2701 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002702 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2703 if (isa<UsingShadowDecl>(D))
2704 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2705
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002706 CXXConversionDecl *Conv;
2707 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002708 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2709 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002710 else
John McCallda4458e2010-03-31 01:36:47 +00002711 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002712
2713 if (AllowExplicit || !Conv->isExplicit()) {
2714 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002715 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2716 ActingContext, From, ToType,
2717 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002718 else
John McCall5c32be02010-08-24 20:38:10 +00002719 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2720 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002721 }
2722 }
2723 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002724 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002725
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002726 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2727
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002728 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002729 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002730 case OR_Success:
2731 // Record the standard conversion we used and the conversion function.
2732 if (CXXConstructorDecl *Constructor
2733 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002734 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2735
John McCall5c32be02010-08-24 20:38:10 +00002736 // C++ [over.ics.user]p1:
2737 // If the user-defined conversion is specified by a
2738 // constructor (12.3.1), the initial standard conversion
2739 // sequence converts the source type to the type required by
2740 // the argument of the constructor.
2741 //
2742 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00002743 if (isa<InitListExpr>(From)) {
2744 // Initializer lists don't have conversions as such.
2745 User.Before.setAsIdentityConversion();
2746 } else {
2747 if (Best->Conversions[0].isEllipsis())
2748 User.EllipsisConversion = true;
2749 else {
2750 User.Before = Best->Conversions[0].Standard;
2751 User.EllipsisConversion = false;
2752 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002753 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002754 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002755 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002756 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002757 User.After.setAsIdentityConversion();
2758 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2759 User.After.setAllToTypes(ToType);
2760 return OR_Success;
2761 } else if (CXXConversionDecl *Conversion
2762 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002763 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2764
John McCall5c32be02010-08-24 20:38:10 +00002765 // C++ [over.ics.user]p1:
2766 //
2767 // [...] If the user-defined conversion is specified by a
2768 // conversion function (12.3.2), the initial standard
2769 // conversion sequence converts the source type to the
2770 // implicit object parameter of the conversion function.
2771 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002772 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002773 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002774 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002775 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002776
John McCall5c32be02010-08-24 20:38:10 +00002777 // C++ [over.ics.user]p2:
2778 // The second standard conversion sequence converts the
2779 // result of the user-defined conversion to the target type
2780 // for the sequence. Since an implicit conversion sequence
2781 // is an initialization, the special rules for
2782 // initialization by user-defined conversion apply when
2783 // selecting the best user-defined conversion for a
2784 // user-defined conversion sequence (see 13.3.3 and
2785 // 13.3.3.1).
2786 User.After = Best->FinalConversion;
2787 return OR_Success;
2788 } else {
2789 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002790 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002791 }
2792
John McCall5c32be02010-08-24 20:38:10 +00002793 case OR_No_Viable_Function:
2794 return OR_No_Viable_Function;
2795 case OR_Deleted:
2796 // No conversion here! We're done.
2797 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002798
John McCall5c32be02010-08-24 20:38:10 +00002799 case OR_Ambiguous:
2800 return OR_Ambiguous;
2801 }
2802
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002803 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002804}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002806bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002807Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002808 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002809 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002810 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002811 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002812 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002813 if (OvResult == OR_Ambiguous)
2814 Diag(From->getSourceRange().getBegin(),
2815 diag::err_typecheck_ambiguous_condition)
2816 << From->getType() << ToType << From->getSourceRange();
2817 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2818 Diag(From->getSourceRange().getBegin(),
2819 diag::err_typecheck_nonviable_condition)
2820 << From->getType() << ToType << From->getSourceRange();
2821 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002822 return false;
John McCall5c32be02010-08-24 20:38:10 +00002823 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002824 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002825}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002826
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002827/// CompareImplicitConversionSequences - Compare two implicit
2828/// conversion sequences to determine whether one is better than the
2829/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002830static ImplicitConversionSequence::CompareKind
2831CompareImplicitConversionSequences(Sema &S,
2832 const ImplicitConversionSequence& ICS1,
2833 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002834{
2835 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2836 // conversion sequences (as defined in 13.3.3.1)
2837 // -- a standard conversion sequence (13.3.3.1.1) is a better
2838 // conversion sequence than a user-defined conversion sequence or
2839 // an ellipsis conversion sequence, and
2840 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2841 // conversion sequence than an ellipsis conversion sequence
2842 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002843 //
John McCall0d1da222010-01-12 00:44:57 +00002844 // C++0x [over.best.ics]p10:
2845 // For the purpose of ranking implicit conversion sequences as
2846 // described in 13.3.3.2, the ambiguous conversion sequence is
2847 // treated as a user-defined sequence that is indistinguishable
2848 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002849 if (ICS1.getKindRank() < ICS2.getKindRank())
2850 return ImplicitConversionSequence::Better;
2851 else if (ICS2.getKindRank() < ICS1.getKindRank())
2852 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002853
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002854 // The following checks require both conversion sequences to be of
2855 // the same kind.
2856 if (ICS1.getKind() != ICS2.getKind())
2857 return ImplicitConversionSequence::Indistinguishable;
2858
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002859 ImplicitConversionSequence::CompareKind Result =
2860 ImplicitConversionSequence::Indistinguishable;
2861
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002862 // Two implicit conversion sequences of the same form are
2863 // indistinguishable conversion sequences unless one of the
2864 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002865 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002866 Result = CompareStandardConversionSequences(S,
2867 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002868 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002869 // User-defined conversion sequence U1 is a better conversion
2870 // sequence than another user-defined conversion sequence U2 if
2871 // they contain the same user-defined conversion function or
2872 // constructor and if the second standard conversion sequence of
2873 // U1 is better than the second standard conversion sequence of
2874 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002875 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002876 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002877 Result = CompareStandardConversionSequences(S,
2878 ICS1.UserDefined.After,
2879 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002880 }
2881
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002882 // List-initialization sequence L1 is a better conversion sequence than
2883 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2884 // for some X and L2 does not.
2885 if (Result == ImplicitConversionSequence::Indistinguishable &&
2886 ICS1.isListInitializationSequence() &&
2887 ICS2.isListInitializationSequence()) {
2888 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2889 }
2890
2891 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002892}
2893
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002894static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2895 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2896 Qualifiers Quals;
2897 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002898 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002900
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002901 return Context.hasSameUnqualifiedType(T1, T2);
2902}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002903
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002904// Per 13.3.3.2p3, compare the given standard conversion sequences to
2905// determine if one is a proper subset of the other.
2906static ImplicitConversionSequence::CompareKind
2907compareStandardConversionSubsets(ASTContext &Context,
2908 const StandardConversionSequence& SCS1,
2909 const StandardConversionSequence& SCS2) {
2910 ImplicitConversionSequence::CompareKind Result
2911 = ImplicitConversionSequence::Indistinguishable;
2912
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002913 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002914 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002915 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2916 return ImplicitConversionSequence::Better;
2917 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2918 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002920 if (SCS1.Second != SCS2.Second) {
2921 if (SCS1.Second == ICK_Identity)
2922 Result = ImplicitConversionSequence::Better;
2923 else if (SCS2.Second == ICK_Identity)
2924 Result = ImplicitConversionSequence::Worse;
2925 else
2926 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002927 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002928 return ImplicitConversionSequence::Indistinguishable;
2929
2930 if (SCS1.Third == SCS2.Third) {
2931 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2932 : ImplicitConversionSequence::Indistinguishable;
2933 }
2934
2935 if (SCS1.Third == ICK_Identity)
2936 return Result == ImplicitConversionSequence::Worse
2937 ? ImplicitConversionSequence::Indistinguishable
2938 : ImplicitConversionSequence::Better;
2939
2940 if (SCS2.Third == ICK_Identity)
2941 return Result == ImplicitConversionSequence::Better
2942 ? ImplicitConversionSequence::Indistinguishable
2943 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002944
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002945 return ImplicitConversionSequence::Indistinguishable;
2946}
2947
Douglas Gregore696ebb2011-01-26 14:52:12 +00002948/// \brief Determine whether one of the given reference bindings is better
2949/// than the other based on what kind of bindings they are.
2950static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2951 const StandardConversionSequence &SCS2) {
2952 // C++0x [over.ics.rank]p3b4:
2953 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2954 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002955 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002956 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002957 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002958 // reference*.
2959 //
2960 // FIXME: Rvalue references. We're going rogue with the above edits,
2961 // because the semantics in the current C++0x working paper (N3225 at the
2962 // time of this writing) break the standard definition of std::forward
2963 // and std::reference_wrapper when dealing with references to functions.
2964 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002965 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2966 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2967 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002968
Douglas Gregore696ebb2011-01-26 14:52:12 +00002969 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2970 SCS2.IsLvalueReference) ||
2971 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2972 !SCS2.IsLvalueReference);
2973}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002974
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002975/// CompareStandardConversionSequences - Compare two standard
2976/// conversion sequences to determine whether one is better than the
2977/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002978static ImplicitConversionSequence::CompareKind
2979CompareStandardConversionSequences(Sema &S,
2980 const StandardConversionSequence& SCS1,
2981 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002982{
2983 // Standard conversion sequence S1 is a better conversion sequence
2984 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2985
2986 // -- S1 is a proper subsequence of S2 (comparing the conversion
2987 // sequences in the canonical form defined by 13.3.3.1.1,
2988 // excluding any Lvalue Transformation; the identity conversion
2989 // sequence is considered to be a subsequence of any
2990 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002991 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002992 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002993 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002994
2995 // -- the rank of S1 is better than the rank of S2 (by the rules
2996 // defined below), or, if not that,
2997 ImplicitConversionRank Rank1 = SCS1.getRank();
2998 ImplicitConversionRank Rank2 = SCS2.getRank();
2999 if (Rank1 < Rank2)
3000 return ImplicitConversionSequence::Better;
3001 else if (Rank2 < Rank1)
3002 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003003
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003004 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3005 // are indistinguishable unless one of the following rules
3006 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003007
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003008 // A conversion that is not a conversion of a pointer, or
3009 // pointer to member, to bool is better than another conversion
3010 // that is such a conversion.
3011 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3012 return SCS2.isPointerConversionToBool()
3013 ? ImplicitConversionSequence::Better
3014 : ImplicitConversionSequence::Worse;
3015
Douglas Gregor5c407d92008-10-23 00:40:37 +00003016 // C++ [over.ics.rank]p4b2:
3017 //
3018 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003019 // conversion of B* to A* is better than conversion of B* to
3020 // void*, and conversion of A* to void* is better than conversion
3021 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003022 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003023 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003024 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003025 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003026 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3027 // Exactly one of the conversion sequences is a conversion to
3028 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003029 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3030 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003031 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3032 // Neither conversion sequence converts to a void pointer; compare
3033 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003034 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003035 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003036 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003037 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3038 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003039 // Both conversion sequences are conversions to void
3040 // pointers. Compare the source types to determine if there's an
3041 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003042 QualType FromType1 = SCS1.getFromType();
3043 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003044
3045 // Adjust the types we're converting from via the array-to-pointer
3046 // conversion, if we need to.
3047 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003048 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003049 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003050 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003051
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003052 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3053 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003054
John McCall5c32be02010-08-24 20:38:10 +00003055 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003056 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003057 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003058 return ImplicitConversionSequence::Worse;
3059
3060 // Objective-C++: If one interface is more specific than the
3061 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003062 const ObjCObjectPointerType* FromObjCPtr1
3063 = FromType1->getAs<ObjCObjectPointerType>();
3064 const ObjCObjectPointerType* FromObjCPtr2
3065 = FromType2->getAs<ObjCObjectPointerType>();
3066 if (FromObjCPtr1 && FromObjCPtr2) {
3067 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3068 FromObjCPtr2);
3069 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3070 FromObjCPtr1);
3071 if (AssignLeft != AssignRight) {
3072 return AssignLeft? ImplicitConversionSequence::Better
3073 : ImplicitConversionSequence::Worse;
3074 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003075 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003076 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003077
3078 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3079 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003080 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003081 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003082 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003083
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003084 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003085 // Check for a better reference binding based on the kind of bindings.
3086 if (isBetterReferenceBindingKind(SCS1, SCS2))
3087 return ImplicitConversionSequence::Better;
3088 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3089 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003090
Sebastian Redlb28b4072009-03-22 23:49:27 +00003091 // C++ [over.ics.rank]p3b4:
3092 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3093 // which the references refer are the same type except for
3094 // top-level cv-qualifiers, and the type to which the reference
3095 // initialized by S2 refers is more cv-qualified than the type
3096 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003097 QualType T1 = SCS1.getToType(2);
3098 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003099 T1 = S.Context.getCanonicalType(T1);
3100 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003101 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003102 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3103 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003104 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003105 // Objective-C++ ARC: If the references refer to objects with different
3106 // lifetimes, prefer bindings that don't change lifetime.
3107 if (SCS1.ObjCLifetimeConversionBinding !=
3108 SCS2.ObjCLifetimeConversionBinding) {
3109 return SCS1.ObjCLifetimeConversionBinding
3110 ? ImplicitConversionSequence::Worse
3111 : ImplicitConversionSequence::Better;
3112 }
3113
Chandler Carruth8e543b32010-12-12 08:17:55 +00003114 // If the type is an array type, promote the element qualifiers to the
3115 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003116 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003117 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003118 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003119 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003120 if (T2.isMoreQualifiedThan(T1))
3121 return ImplicitConversionSequence::Better;
3122 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003123 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003124 }
3125 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003126
Francois Pichet08d2fa02011-09-18 21:37:37 +00003127 // In Microsoft mode, prefer an integral conversion to a
3128 // floating-to-integral conversion if the integral conversion
3129 // is between types of the same size.
3130 // For example:
3131 // void f(float);
3132 // void f(int);
3133 // int main {
3134 // long a;
3135 // f(a);
3136 // }
3137 // Here, MSVC will call f(int) instead of generating a compile error
3138 // as clang will do in standard mode.
3139 if (S.getLangOptions().MicrosoftMode &&
3140 SCS1.Second == ICK_Integral_Conversion &&
3141 SCS2.Second == ICK_Floating_Integral &&
3142 S.Context.getTypeSize(SCS1.getFromType()) ==
3143 S.Context.getTypeSize(SCS1.getToType(2)))
3144 return ImplicitConversionSequence::Better;
3145
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003146 return ImplicitConversionSequence::Indistinguishable;
3147}
3148
3149/// CompareQualificationConversions - Compares two standard conversion
3150/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003151/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3152ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003153CompareQualificationConversions(Sema &S,
3154 const StandardConversionSequence& SCS1,
3155 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003156 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003157 // -- S1 and S2 differ only in their qualification conversion and
3158 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3159 // cv-qualification signature of type T1 is a proper subset of
3160 // the cv-qualification signature of type T2, and S1 is not the
3161 // deprecated string literal array-to-pointer conversion (4.2).
3162 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3163 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3164 return ImplicitConversionSequence::Indistinguishable;
3165
3166 // FIXME: the example in the standard doesn't use a qualification
3167 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003168 QualType T1 = SCS1.getToType(2);
3169 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003170 T1 = S.Context.getCanonicalType(T1);
3171 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003172 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003173 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3174 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003175
3176 // If the types are the same, we won't learn anything by unwrapped
3177 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003178 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003179 return ImplicitConversionSequence::Indistinguishable;
3180
Chandler Carruth607f38e2009-12-29 07:16:59 +00003181 // If the type is an array type, promote the element qualifiers to the type
3182 // for comparison.
3183 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003184 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003185 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003186 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003187
Mike Stump11289f42009-09-09 15:08:12 +00003188 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003189 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003190
3191 // Objective-C++ ARC:
3192 // Prefer qualification conversions not involving a change in lifetime
3193 // to qualification conversions that do not change lifetime.
3194 if (SCS1.QualificationIncludesObjCLifetime !=
3195 SCS2.QualificationIncludesObjCLifetime) {
3196 Result = SCS1.QualificationIncludesObjCLifetime
3197 ? ImplicitConversionSequence::Worse
3198 : ImplicitConversionSequence::Better;
3199 }
3200
John McCall5c32be02010-08-24 20:38:10 +00003201 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003202 // Within each iteration of the loop, we check the qualifiers to
3203 // determine if this still looks like a qualification
3204 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003205 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003206 // until there are no more pointers or pointers-to-members left
3207 // to unwrap. This essentially mimics what
3208 // IsQualificationConversion does, but here we're checking for a
3209 // strict subset of qualifiers.
3210 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3211 // The qualifiers are the same, so this doesn't tell us anything
3212 // about how the sequences rank.
3213 ;
3214 else if (T2.isMoreQualifiedThan(T1)) {
3215 // T1 has fewer qualifiers, so it could be the better sequence.
3216 if (Result == ImplicitConversionSequence::Worse)
3217 // Neither has qualifiers that are a subset of the other's
3218 // qualifiers.
3219 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003220
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003221 Result = ImplicitConversionSequence::Better;
3222 } else if (T1.isMoreQualifiedThan(T2)) {
3223 // T2 has fewer qualifiers, so it could be the better sequence.
3224 if (Result == ImplicitConversionSequence::Better)
3225 // Neither has qualifiers that are a subset of the other's
3226 // qualifiers.
3227 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003228
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003229 Result = ImplicitConversionSequence::Worse;
3230 } else {
3231 // Qualifiers are disjoint.
3232 return ImplicitConversionSequence::Indistinguishable;
3233 }
3234
3235 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003236 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003237 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003238 }
3239
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003240 // Check that the winning standard conversion sequence isn't using
3241 // the deprecated string literal array to pointer conversion.
3242 switch (Result) {
3243 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003244 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003245 Result = ImplicitConversionSequence::Indistinguishable;
3246 break;
3247
3248 case ImplicitConversionSequence::Indistinguishable:
3249 break;
3250
3251 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003252 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003253 Result = ImplicitConversionSequence::Indistinguishable;
3254 break;
3255 }
3256
3257 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003258}
3259
Douglas Gregor5c407d92008-10-23 00:40:37 +00003260/// CompareDerivedToBaseConversions - Compares two standard conversion
3261/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003262/// various kinds of derived-to-base conversions (C++
3263/// [over.ics.rank]p4b3). As part of these checks, we also look at
3264/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003265ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003266CompareDerivedToBaseConversions(Sema &S,
3267 const StandardConversionSequence& SCS1,
3268 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003269 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003270 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003271 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003272 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003273
3274 // Adjust the types we're converting from via the array-to-pointer
3275 // conversion, if we need to.
3276 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003277 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003278 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003279 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003280
3281 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003282 FromType1 = S.Context.getCanonicalType(FromType1);
3283 ToType1 = S.Context.getCanonicalType(ToType1);
3284 FromType2 = S.Context.getCanonicalType(FromType2);
3285 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003286
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003287 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003288 //
3289 // If class B is derived directly or indirectly from class A and
3290 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003291 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003292 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003293 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003294 SCS2.Second == ICK_Pointer_Conversion &&
3295 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3296 FromType1->isPointerType() && FromType2->isPointerType() &&
3297 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003298 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003299 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003300 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003301 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003302 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003303 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003304 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003305 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003306
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003307 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003308 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003309 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003310 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003311 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003312 return ImplicitConversionSequence::Worse;
3313 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003314
3315 // -- conversion of B* to A* is better than conversion of C* to A*,
3316 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003317 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003318 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003319 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003320 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003321 }
3322 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3323 SCS2.Second == ICK_Pointer_Conversion) {
3324 const ObjCObjectPointerType *FromPtr1
3325 = FromType1->getAs<ObjCObjectPointerType>();
3326 const ObjCObjectPointerType *FromPtr2
3327 = FromType2->getAs<ObjCObjectPointerType>();
3328 const ObjCObjectPointerType *ToPtr1
3329 = ToType1->getAs<ObjCObjectPointerType>();
3330 const ObjCObjectPointerType *ToPtr2
3331 = ToType2->getAs<ObjCObjectPointerType>();
3332
3333 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3334 // Apply the same conversion ranking rules for Objective-C pointer types
3335 // that we do for C++ pointers to class types. However, we employ the
3336 // Objective-C pseudo-subtyping relationship used for assignment of
3337 // Objective-C pointer types.
3338 bool FromAssignLeft
3339 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3340 bool FromAssignRight
3341 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3342 bool ToAssignLeft
3343 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3344 bool ToAssignRight
3345 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3346
3347 // A conversion to an a non-id object pointer type or qualified 'id'
3348 // type is better than a conversion to 'id'.
3349 if (ToPtr1->isObjCIdType() &&
3350 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3351 return ImplicitConversionSequence::Worse;
3352 if (ToPtr2->isObjCIdType() &&
3353 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3354 return ImplicitConversionSequence::Better;
3355
3356 // A conversion to a non-id object pointer type is better than a
3357 // conversion to a qualified 'id' type
3358 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3359 return ImplicitConversionSequence::Worse;
3360 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3361 return ImplicitConversionSequence::Better;
3362
3363 // A conversion to an a non-Class object pointer type or qualified 'Class'
3364 // type is better than a conversion to 'Class'.
3365 if (ToPtr1->isObjCClassType() &&
3366 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3367 return ImplicitConversionSequence::Worse;
3368 if (ToPtr2->isObjCClassType() &&
3369 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3370 return ImplicitConversionSequence::Better;
3371
3372 // A conversion to a non-Class object pointer type is better than a
3373 // conversion to a qualified 'Class' type.
3374 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3375 return ImplicitConversionSequence::Worse;
3376 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3377 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003378
Douglas Gregor058d3de2011-01-31 18:51:41 +00003379 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3380 if (S.Context.hasSameType(FromType1, FromType2) &&
3381 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3382 (ToAssignLeft != ToAssignRight))
3383 return ToAssignLeft? ImplicitConversionSequence::Worse
3384 : ImplicitConversionSequence::Better;
3385
3386 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3387 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3388 (FromAssignLeft != FromAssignRight))
3389 return FromAssignLeft? ImplicitConversionSequence::Better
3390 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003391 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003392 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003393
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003394 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003395 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3396 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3397 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003399 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003401 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003402 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003403 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003404 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003405 ToType2->getAs<MemberPointerType>();
3406 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3407 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3408 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3409 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3410 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3411 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3412 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3413 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003414 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003415 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003416 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003417 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003418 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003419 return ImplicitConversionSequence::Better;
3420 }
3421 // conversion of B::* to C::* is better than conversion of A::* to C::*
3422 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003423 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003424 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003425 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003426 return ImplicitConversionSequence::Worse;
3427 }
3428 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003429
Douglas Gregor5ab11652010-04-17 22:01:05 +00003430 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003431 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003432 // -- binding of an expression of type C to a reference of type
3433 // B& is better than binding an expression of type C to a
3434 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003435 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3436 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3437 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003438 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003439 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003440 return ImplicitConversionSequence::Worse;
3441 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003442
Douglas Gregor2fe98832008-11-03 19:09:14 +00003443 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003444 // -- binding of an expression of type B to a reference of type
3445 // A& is better than binding an expression of type C to a
3446 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003447 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3448 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3449 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003450 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003451 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003452 return ImplicitConversionSequence::Worse;
3453 }
3454 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003455
Douglas Gregor5c407d92008-10-23 00:40:37 +00003456 return ImplicitConversionSequence::Indistinguishable;
3457}
3458
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003459/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3460/// determine whether they are reference-related,
3461/// reference-compatible, reference-compatible with added
3462/// qualification, or incompatible, for use in C++ initialization by
3463/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3464/// type, and the first type (T1) is the pointee type of the reference
3465/// type being initialized.
3466Sema::ReferenceCompareResult
3467Sema::CompareReferenceRelationship(SourceLocation Loc,
3468 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003469 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003470 bool &ObjCConversion,
3471 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003472 assert(!OrigT1->isReferenceType() &&
3473 "T1 must be the pointee type of the reference type");
3474 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3475
3476 QualType T1 = Context.getCanonicalType(OrigT1);
3477 QualType T2 = Context.getCanonicalType(OrigT2);
3478 Qualifiers T1Quals, T2Quals;
3479 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3480 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3481
3482 // C++ [dcl.init.ref]p4:
3483 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3484 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3485 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003486 DerivedToBase = false;
3487 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003488 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003489 if (UnqualT1 == UnqualT2) {
3490 // Nothing to do.
3491 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003492 IsDerivedFrom(UnqualT2, UnqualT1))
3493 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003494 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3495 UnqualT2->isObjCObjectOrInterfaceType() &&
3496 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3497 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003498 else
3499 return Ref_Incompatible;
3500
3501 // At this point, we know that T1 and T2 are reference-related (at
3502 // least).
3503
3504 // If the type is an array type, promote the element qualifiers to the type
3505 // for comparison.
3506 if (isa<ArrayType>(T1) && T1Quals)
3507 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3508 if (isa<ArrayType>(T2) && T2Quals)
3509 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3510
3511 // C++ [dcl.init.ref]p4:
3512 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3513 // reference-related to T2 and cv1 is the same cv-qualification
3514 // as, or greater cv-qualification than, cv2. For purposes of
3515 // overload resolution, cases for which cv1 is greater
3516 // cv-qualification than cv2 are identified as
3517 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003518 //
3519 // Note that we also require equivalence of Objective-C GC and address-space
3520 // qualifiers when performing these computations, so that e.g., an int in
3521 // address space 1 is not reference-compatible with an int in address
3522 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003523 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3524 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3525 T1Quals.removeObjCLifetime();
3526 T2Quals.removeObjCLifetime();
3527 ObjCLifetimeConversion = true;
3528 }
3529
Douglas Gregord517d552011-04-28 17:56:11 +00003530 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003531 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003532 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003533 return Ref_Compatible_With_Added_Qualification;
3534 else
3535 return Ref_Related;
3536}
3537
Douglas Gregor836a7e82010-08-11 02:15:33 +00003538/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003539/// with DeclType. Return true if something definite is found.
3540static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003541FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3542 QualType DeclType, SourceLocation DeclLoc,
3543 Expr *Init, QualType T2, bool AllowRvalues,
3544 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003545 assert(T2->isRecordType() && "Can only find conversions of record types.");
3546 CXXRecordDecl *T2RecordDecl
3547 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3548
3549 OverloadCandidateSet CandidateSet(DeclLoc);
3550 const UnresolvedSetImpl *Conversions
3551 = T2RecordDecl->getVisibleConversionFunctions();
3552 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3553 E = Conversions->end(); I != E; ++I) {
3554 NamedDecl *D = *I;
3555 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3556 if (isa<UsingShadowDecl>(D))
3557 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3558
3559 FunctionTemplateDecl *ConvTemplate
3560 = dyn_cast<FunctionTemplateDecl>(D);
3561 CXXConversionDecl *Conv;
3562 if (ConvTemplate)
3563 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3564 else
3565 Conv = cast<CXXConversionDecl>(D);
3566
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003568 // explicit conversions, skip it.
3569 if (!AllowExplicit && Conv->isExplicit())
3570 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571
Douglas Gregor836a7e82010-08-11 02:15:33 +00003572 if (AllowRvalues) {
3573 bool DerivedToBase = false;
3574 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003575 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003576
3577 // If we are initializing an rvalue reference, don't permit conversion
3578 // functions that return lvalues.
3579 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3580 const ReferenceType *RefType
3581 = Conv->getConversionType()->getAs<LValueReferenceType>();
3582 if (RefType && !RefType->getPointeeType()->isFunctionType())
3583 continue;
3584 }
3585
Douglas Gregor836a7e82010-08-11 02:15:33 +00003586 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003587 S.CompareReferenceRelationship(
3588 DeclLoc,
3589 Conv->getConversionType().getNonReferenceType()
3590 .getUnqualifiedType(),
3591 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003592 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003593 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003594 continue;
3595 } else {
3596 // If the conversion function doesn't return a reference type,
3597 // it can't be considered for this conversion. An rvalue reference
3598 // is only acceptable if its referencee is a function type.
3599
3600 const ReferenceType *RefType =
3601 Conv->getConversionType()->getAs<ReferenceType>();
3602 if (!RefType ||
3603 (!RefType->isLValueReferenceType() &&
3604 !RefType->getPointeeType()->isFunctionType()))
3605 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003607
Douglas Gregor836a7e82010-08-11 02:15:33 +00003608 if (ConvTemplate)
3609 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003610 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003611 else
3612 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003613 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003614 }
3615
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003616 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3617
Sebastian Redld92badf2010-06-30 18:13:39 +00003618 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003619 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003620 case OR_Success:
3621 // C++ [over.ics.ref]p1:
3622 //
3623 // [...] If the parameter binds directly to the result of
3624 // applying a conversion function to the argument
3625 // expression, the implicit conversion sequence is a
3626 // user-defined conversion sequence (13.3.3.1.2), with the
3627 // second standard conversion sequence either an identity
3628 // conversion or, if the conversion function returns an
3629 // entity of a type that is a derived class of the parameter
3630 // type, a derived-to-base Conversion.
3631 if (!Best->FinalConversion.DirectBinding)
3632 return false;
3633
Chandler Carruth30141632011-02-25 19:41:05 +00003634 if (Best->Function)
3635 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003636 ICS.setUserDefined();
3637 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3638 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003639 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003640 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003641 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003642 ICS.UserDefined.EllipsisConversion = false;
3643 assert(ICS.UserDefined.After.ReferenceBinding &&
3644 ICS.UserDefined.After.DirectBinding &&
3645 "Expected a direct reference binding!");
3646 return true;
3647
3648 case OR_Ambiguous:
3649 ICS.setAmbiguous();
3650 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3651 Cand != CandidateSet.end(); ++Cand)
3652 if (Cand->Viable)
3653 ICS.Ambiguous.addConversion(Cand->Function);
3654 return true;
3655
3656 case OR_No_Viable_Function:
3657 case OR_Deleted:
3658 // There was no suitable conversion, or we found a deleted
3659 // conversion; continue with other checks.
3660 return false;
3661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
Eric Christopheraba9fb22010-06-30 18:36:32 +00003663 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003664}
3665
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003666/// \brief Compute an implicit conversion sequence for reference
3667/// initialization.
3668static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00003669TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003670 SourceLocation DeclLoc,
3671 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003672 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003673 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3674
3675 // Most paths end in a failed conversion.
3676 ImplicitConversionSequence ICS;
3677 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3678
3679 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3680 QualType T2 = Init->getType();
3681
3682 // If the initializer is the address of an overloaded function, try
3683 // to resolve the overloaded function. If all goes well, T2 is the
3684 // type of the resulting function.
3685 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3686 DeclAccessPair Found;
3687 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3688 false, Found))
3689 T2 = Fn->getType();
3690 }
3691
3692 // Compute some basic properties of the types and the initializer.
3693 bool isRValRef = DeclType->isRValueReferenceType();
3694 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003695 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003696 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003697 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003698 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003699 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003700 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003701
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003702
Sebastian Redld92badf2010-06-30 18:13:39 +00003703 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003704 // A reference to type "cv1 T1" is initialized by an expression
3705 // of type "cv2 T2" as follows:
3706
Sebastian Redld92badf2010-06-30 18:13:39 +00003707 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003708 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003709 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3710 // reference-compatible with "cv2 T2," or
3711 //
3712 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3713 if (InitCategory.isLValue() &&
3714 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003715 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003716 // When a parameter of reference type binds directly (8.5.3)
3717 // to an argument expression, the implicit conversion sequence
3718 // is the identity conversion, unless the argument expression
3719 // has a type that is a derived class of the parameter type,
3720 // in which case the implicit conversion sequence is a
3721 // derived-to-base Conversion (13.3.3.1).
3722 ICS.setStandard();
3723 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003724 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3725 : ObjCConversion? ICK_Compatible_Conversion
3726 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003727 ICS.Standard.Third = ICK_Identity;
3728 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3729 ICS.Standard.setToType(0, T2);
3730 ICS.Standard.setToType(1, T1);
3731 ICS.Standard.setToType(2, T1);
3732 ICS.Standard.ReferenceBinding = true;
3733 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003734 ICS.Standard.IsLvalueReference = !isRValRef;
3735 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3736 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003737 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003738 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003739 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003740
Sebastian Redld92badf2010-06-30 18:13:39 +00003741 // Nothing more to do: the inaccessibility/ambiguity check for
3742 // derived-to-base conversions is suppressed when we're
3743 // computing the implicit conversion sequence (C++
3744 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003745 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003746 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003747
Sebastian Redld92badf2010-06-30 18:13:39 +00003748 // -- has a class type (i.e., T2 is a class type), where T1 is
3749 // not reference-related to T2, and can be implicitly
3750 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3751 // is reference-compatible with "cv3 T3" 92) (this
3752 // conversion is selected by enumerating the applicable
3753 // conversion functions (13.3.1.6) and choosing the best
3754 // one through overload resolution (13.3)),
3755 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003756 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003757 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003758 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3759 Init, T2, /*AllowRvalues=*/false,
3760 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003761 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003762 }
3763 }
3764
Sebastian Redld92badf2010-06-30 18:13:39 +00003765 // -- Otherwise, the reference shall be an lvalue reference to a
3766 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003767 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003769 // We actually handle one oddity of C++ [over.ics.ref] at this
3770 // point, which is that, due to p2 (which short-circuits reference
3771 // binding by only attempting a simple conversion for non-direct
3772 // bindings) and p3's strange wording, we allow a const volatile
3773 // reference to bind to an rvalue. Hence the check for the presence
3774 // of "const" rather than checking for "const" being the only
3775 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003776 // This is also the point where rvalue references and lvalue inits no longer
3777 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003778 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003779 return ICS;
3780
Douglas Gregorf143cd52011-01-24 16:14:37 +00003781 // -- If the initializer expression
3782 //
3783 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003784 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003785 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3786 (InitCategory.isXValue() ||
3787 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3788 (InitCategory.isLValue() && T2->isFunctionType()))) {
3789 ICS.setStandard();
3790 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003791 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003792 : ObjCConversion? ICK_Compatible_Conversion
3793 : ICK_Identity;
3794 ICS.Standard.Third = ICK_Identity;
3795 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3796 ICS.Standard.setToType(0, T2);
3797 ICS.Standard.setToType(1, T1);
3798 ICS.Standard.setToType(2, T1);
3799 ICS.Standard.ReferenceBinding = true;
3800 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3801 // binding unless we're binding to a class prvalue.
3802 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3803 // allow the use of rvalue references in C++98/03 for the benefit of
3804 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003805 ICS.Standard.DirectBinding =
3806 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003807 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003808 ICS.Standard.IsLvalueReference = !isRValRef;
3809 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003810 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003811 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003812 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003813 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003816
Douglas Gregorf143cd52011-01-24 16:14:37 +00003817 // -- has a class type (i.e., T2 is a class type), where T1 is not
3818 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819 // an xvalue, class prvalue, or function lvalue of type
3820 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003821 // "cv3 T3",
3822 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003824 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003826 // class subobject).
3827 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003829 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3830 Init, T2, /*AllowRvalues=*/true,
3831 AllowExplicit)) {
3832 // In the second case, if the reference is an rvalue reference
3833 // and the second standard conversion sequence of the
3834 // user-defined conversion sequence includes an lvalue-to-rvalue
3835 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003837 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3838 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3839
Douglas Gregor95273c32011-01-21 16:36:05 +00003840 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003841 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003842
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003843 // -- Otherwise, a temporary of type "cv1 T1" is created and
3844 // initialized from the initializer expression using the
3845 // rules for a non-reference copy initialization (8.5). The
3846 // reference is then bound to the temporary. If T1 is
3847 // reference-related to T2, cv1 must be the same
3848 // cv-qualification as, or greater cv-qualification than,
3849 // cv2; otherwise, the program is ill-formed.
3850 if (RefRelationship == Sema::Ref_Related) {
3851 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3852 // we would be reference-compatible or reference-compatible with
3853 // added qualification. But that wasn't the case, so the reference
3854 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003855 //
3856 // Note that we only want to check address spaces and cvr-qualifiers here.
3857 // ObjC GC and lifetime qualifiers aren't important.
3858 Qualifiers T1Quals = T1.getQualifiers();
3859 Qualifiers T2Quals = T2.getQualifiers();
3860 T1Quals.removeObjCGCAttr();
3861 T1Quals.removeObjCLifetime();
3862 T2Quals.removeObjCGCAttr();
3863 T2Quals.removeObjCLifetime();
3864 if (!T1Quals.compatiblyIncludes(T2Quals))
3865 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003866 }
3867
3868 // If at least one of the types is a class type, the types are not
3869 // related, and we aren't allowed any user conversions, the
3870 // reference binding fails. This case is important for breaking
3871 // recursion, since TryImplicitConversion below will attempt to
3872 // create a temporary through the use of a copy constructor.
3873 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3874 (T1->isRecordType() || T2->isRecordType()))
3875 return ICS;
3876
Douglas Gregorcba72b12011-01-21 05:18:22 +00003877 // If T1 is reference-related to T2 and the reference is an rvalue
3878 // reference, the initializer expression shall not be an lvalue.
3879 if (RefRelationship >= Sema::Ref_Related &&
3880 isRValRef && Init->Classify(S.Context).isLValue())
3881 return ICS;
3882
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003883 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003884 // When a parameter of reference type is not bound directly to
3885 // an argument expression, the conversion sequence is the one
3886 // required to convert the argument expression to the
3887 // underlying type of the reference according to
3888 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3889 // to copy-initializing a temporary of the underlying type with
3890 // the argument expression. Any difference in top-level
3891 // cv-qualification is subsumed by the initialization itself
3892 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003893 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3894 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003895 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003896 /*CStyle=*/false,
3897 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003898
3899 // Of course, that's still a reference binding.
3900 if (ICS.isStandard()) {
3901 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003902 ICS.Standard.IsLvalueReference = !isRValRef;
3903 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3904 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003905 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003906 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003907 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003908 // Don't allow rvalue references to bind to lvalues.
3909 if (DeclType->isRValueReferenceType()) {
3910 if (const ReferenceType *RefType
3911 = ICS.UserDefined.ConversionFunction->getResultType()
3912 ->getAs<LValueReferenceType>()) {
3913 if (!RefType->getPointeeType()->isFunctionType()) {
3914 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3915 DeclType);
3916 return ICS;
3917 }
3918 }
3919 }
3920
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003921 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003922 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3923 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3924 ICS.UserDefined.After.BindsToRvalue = true;
3925 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3926 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003927 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003928
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003929 return ICS;
3930}
3931
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003932static ImplicitConversionSequence
3933TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3934 bool SuppressUserConversions,
3935 bool InOverloadResolution,
3936 bool AllowObjCWritebackConversion);
3937
3938/// TryListConversion - Try to copy-initialize a value of type ToType from the
3939/// initializer list From.
3940static ImplicitConversionSequence
3941TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3942 bool SuppressUserConversions,
3943 bool InOverloadResolution,
3944 bool AllowObjCWritebackConversion) {
3945 // C++11 [over.ics.list]p1:
3946 // When an argument is an initializer list, it is not an expression and
3947 // special rules apply for converting it to a parameter type.
3948
3949 ImplicitConversionSequence Result;
3950 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003951 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003952
3953 // C++11 [over.ics.list]p2:
3954 // If the parameter type is std::initializer_list<X> or "array of X" and
3955 // all the elements can be implicitly converted to X, the implicit
3956 // conversion sequence is the worst conversion necessary to convert an
3957 // element of the list to X.
3958 // FIXME: Recognize std::initializer_list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003959 // FIXME: Implement arrays.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003960 if (ToType->isArrayType())
3961 return Result;
3962
3963 // C++11 [over.ics.list]p3:
3964 // Otherwise, if the parameter is a non-aggregate class X and overload
3965 // resolution chooses a single best constructor [...] the implicit
3966 // conversion sequence is a user-defined conversion sequence. If multiple
3967 // constructors are viable but none is better than the others, the
3968 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003969 if (ToType->isRecordType() && !ToType->isAggregateType()) {
3970 // This function can deal with initializer lists.
3971 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
3972 /*AllowExplicit=*/false,
3973 InOverloadResolution, /*CStyle=*/false,
3974 AllowObjCWritebackConversion);
3975 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003976 return Result;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003977 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003978
3979 // C++11 [over.ics.list]p4:
3980 // Otherwise, if the parameter has an aggregate type which can be
3981 // initialized from the initializer list [...] the implicit conversion
3982 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003983 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003984 // Type is an aggregate, argument is an init list. At this point it comes
3985 // down to checking whether the initialization works.
3986 // FIXME: Find out whether this parameter is consumed or not.
3987 InitializedEntity Entity =
3988 InitializedEntity::InitializeParameter(S.Context, ToType,
3989 /*Consumed=*/false);
3990 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3991 Result.setUserDefined();
3992 Result.UserDefined.Before.setAsIdentityConversion();
3993 // Initializer lists don't have a type.
3994 Result.UserDefined.Before.setFromType(QualType());
3995 Result.UserDefined.Before.setAllToTypes(QualType());
3996
3997 Result.UserDefined.After.setAsIdentityConversion();
3998 Result.UserDefined.After.setFromType(ToType);
3999 Result.UserDefined.After.setAllToTypes(ToType);
4000 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004001 return Result;
4002 }
4003
4004 // C++11 [over.ics.list]p5:
4005 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004006 if (ToType->isReferenceType()) {
4007 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4008 // mention initializer lists in any way. So we go by what list-
4009 // initialization would do and try to extrapolate from that.
4010
4011 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4012
4013 // If the initializer list has a single element that is reference-related
4014 // to the parameter type, we initialize the reference from that.
4015 if (From->getNumInits() == 1) {
4016 Expr *Init = From->getInit(0);
4017
4018 QualType T2 = Init->getType();
4019
4020 // If the initializer is the address of an overloaded function, try
4021 // to resolve the overloaded function. If all goes well, T2 is the
4022 // type of the resulting function.
4023 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4024 DeclAccessPair Found;
4025 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4026 Init, ToType, false, Found))
4027 T2 = Fn->getType();
4028 }
4029
4030 // Compute some basic properties of the types and the initializer.
4031 bool dummy1 = false;
4032 bool dummy2 = false;
4033 bool dummy3 = false;
4034 Sema::ReferenceCompareResult RefRelationship
4035 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4036 dummy2, dummy3);
4037
4038 if (RefRelationship >= Sema::Ref_Related)
4039 return TryReferenceInit(S, Init, ToType,
4040 /*FIXME:*/From->getLocStart(),
4041 SuppressUserConversions,
4042 /*AllowExplicit=*/false);
4043 }
4044
4045 // Otherwise, we bind the reference to a temporary created from the
4046 // initializer list.
4047 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4048 InOverloadResolution,
4049 AllowObjCWritebackConversion);
4050 if (Result.isFailure())
4051 return Result;
4052 assert(!Result.isEllipsis() &&
4053 "Sub-initialization cannot result in ellipsis conversion.");
4054
4055 // Can we even bind to a temporary?
4056 if (ToType->isRValueReferenceType() ||
4057 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4058 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4059 Result.UserDefined.After;
4060 SCS.ReferenceBinding = true;
4061 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4062 SCS.BindsToRvalue = true;
4063 SCS.BindsToFunctionLvalue = false;
4064 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4065 SCS.ObjCLifetimeConversionBinding = false;
4066 } else
4067 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4068 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004069 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004070 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004071
4072 // C++11 [over.ics.list]p6:
4073 // Otherwise, if the parameter type is not a class:
4074 if (!ToType->isRecordType()) {
4075 // - if the initializer list has one element, the implicit conversion
4076 // sequence is the one required to convert the element to the
4077 // parameter type.
4078 // FIXME: Catch narrowing here?
4079 unsigned NumInits = From->getNumInits();
4080 if (NumInits == 1)
4081 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4082 SuppressUserConversions,
4083 InOverloadResolution,
4084 AllowObjCWritebackConversion);
4085 // - if the initializer list has no elements, the implicit conversion
4086 // sequence is the identity conversion.
4087 else if (NumInits == 0) {
4088 Result.setStandard();
4089 Result.Standard.setAsIdentityConversion();
4090 }
4091 return Result;
4092 }
4093
4094 // C++11 [over.ics.list]p7:
4095 // In all cases other than those enumerated above, no conversion is possible
4096 return Result;
4097}
4098
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004099/// TryCopyInitialization - Try to copy-initialize a value of type
4100/// ToType from the expression From. Return the implicit conversion
4101/// sequence required to pass this argument, which may be a bad
4102/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004103/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004104/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004105static ImplicitConversionSequence
4106TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004108 bool InOverloadResolution,
4109 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004110 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4111 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4112 InOverloadResolution,AllowObjCWritebackConversion);
4113
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004114 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004115 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004116 /*FIXME:*/From->getLocStart(),
4117 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004118 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004119
John McCall5c32be02010-08-24 20:38:10 +00004120 return TryImplicitConversion(S, From, ToType,
4121 SuppressUserConversions,
4122 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004123 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004124 /*CStyle=*/false,
4125 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004126}
4127
Anna Zaks1b068122011-07-28 19:46:48 +00004128static bool TryCopyInitialization(const CanQualType FromQTy,
4129 const CanQualType ToQTy,
4130 Sema &S,
4131 SourceLocation Loc,
4132 ExprValueKind FromVK) {
4133 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4134 ImplicitConversionSequence ICS =
4135 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4136
4137 return !ICS.isBad();
4138}
4139
Douglas Gregor436424c2008-11-18 23:14:02 +00004140/// TryObjectArgumentInitialization - Try to initialize the object
4141/// parameter of the given member function (@c Method) from the
4142/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004143static ImplicitConversionSequence
4144TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004145 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004146 CXXMethodDecl *Method,
4147 CXXRecordDecl *ActingContext) {
4148 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004149 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4150 // const volatile object.
4151 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4152 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004153 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004154
4155 // Set up the conversion sequence as a "bad" conversion, to allow us
4156 // to exit early.
4157 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004158
4159 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004160 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004161 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004162 FromType = PT->getPointeeType();
4163
Douglas Gregor02824322011-01-26 19:30:28 +00004164 // When we had a pointer, it's implicitly dereferenced, so we
4165 // better have an lvalue.
4166 assert(FromClassification.isLValue());
4167 }
4168
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004169 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004170
Douglas Gregor02824322011-01-26 19:30:28 +00004171 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004173 // parameter is
4174 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004175 // - "lvalue reference to cv X" for functions declared without a
4176 // ref-qualifier or with the & ref-qualifier
4177 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004178 // ref-qualifier
4179 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004180 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004181 // cv-qualification on the member function declaration.
4182 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004184 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004185 // (C++ [over.match.funcs]p5). We perform a simplified version of
4186 // reference binding here, that allows class rvalues to bind to
4187 // non-constant references.
4188
Douglas Gregor02824322011-01-26 19:30:28 +00004189 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004190 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004191 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004192 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004193 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004194 ICS.setBad(BadConversionSequence::bad_qualifiers,
4195 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004196 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004197 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004198
4199 // Check that we have either the same type or a derived type. It
4200 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004201 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004202 ImplicitConversionKind SecondKind;
4203 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4204 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004205 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004206 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004207 else {
John McCall65eb8792010-02-25 01:37:24 +00004208 ICS.setBad(BadConversionSequence::unrelated_class,
4209 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004210 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004211 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004212
Douglas Gregor02824322011-01-26 19:30:28 +00004213 // Check the ref-qualifier.
4214 switch (Method->getRefQualifier()) {
4215 case RQ_None:
4216 // Do nothing; we don't care about lvalueness or rvalueness.
4217 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218
Douglas Gregor02824322011-01-26 19:30:28 +00004219 case RQ_LValue:
4220 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4221 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004223 ImplicitParamType);
4224 return ICS;
4225 }
4226 break;
4227
4228 case RQ_RValue:
4229 if (!FromClassification.isRValue()) {
4230 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004232 ImplicitParamType);
4233 return ICS;
4234 }
4235 break;
4236 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004237
Douglas Gregor436424c2008-11-18 23:14:02 +00004238 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004239 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004240 ICS.Standard.setAsIdentityConversion();
4241 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004242 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004243 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004244 ICS.Standard.ReferenceBinding = true;
4245 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004246 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004247 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004248 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4249 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4250 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004251 return ICS;
4252}
4253
4254/// PerformObjectArgumentInitialization - Perform initialization of
4255/// the implicit object parameter for the given Method with the given
4256/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004257ExprResult
4258Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004260 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004261 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004262 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004263 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004264 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004265
Douglas Gregor02824322011-01-26 19:30:28 +00004266 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004267 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004268 FromRecordType = PT->getPointeeType();
4269 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004270 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004271 } else {
4272 FromRecordType = From->getType();
4273 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004274 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004275 }
4276
John McCall6e9f8f62009-12-03 04:06:58 +00004277 // Note that we always use the true parent context when performing
4278 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004279 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004280 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4281 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004282 if (ICS.isBad()) {
4283 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4284 Qualifiers FromQs = FromRecordType.getQualifiers();
4285 Qualifiers ToQs = DestType.getQualifiers();
4286 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4287 if (CVR) {
4288 Diag(From->getSourceRange().getBegin(),
4289 diag::err_member_function_call_bad_cvr)
4290 << Method->getDeclName() << FromRecordType << (CVR - 1)
4291 << From->getSourceRange();
4292 Diag(Method->getLocation(), diag::note_previous_decl)
4293 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004294 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004295 }
4296 }
4297
Douglas Gregor436424c2008-11-18 23:14:02 +00004298 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004299 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004300 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004301 }
Mike Stump11289f42009-09-09 15:08:12 +00004302
John Wiegley01296292011-04-08 18:41:53 +00004303 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4304 ExprResult FromRes =
4305 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4306 if (FromRes.isInvalid())
4307 return ExprError();
4308 From = FromRes.take();
4309 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004310
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004311 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004312 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004313 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004314 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004315}
4316
Douglas Gregor5fb53972009-01-14 15:45:31 +00004317/// TryContextuallyConvertToBool - Attempt to contextually convert the
4318/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004319static ImplicitConversionSequence
4320TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004321 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004322 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004323 // FIXME: Are these flags correct?
4324 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004325 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004326 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004327 /*CStyle=*/false,
4328 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004329}
4330
4331/// PerformContextuallyConvertToBool - Perform a contextual conversion
4332/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004333ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004334 if (checkPlaceholderForOverload(*this, From))
4335 return ExprError();
4336
John McCall5c32be02010-08-24 20:38:10 +00004337 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004338 if (!ICS.isBad())
4339 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Fariborz Jahanian76197412009-11-18 18:26:29 +00004341 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004342 return Diag(From->getSourceRange().getBegin(),
4343 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004344 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004345 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004346}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347
John McCallfec112d2011-09-09 06:11:02 +00004348/// dropPointerConversions - If the given standard conversion sequence
4349/// involves any pointer conversions, remove them. This may change
4350/// the result type of the conversion sequence.
4351static void dropPointerConversion(StandardConversionSequence &SCS) {
4352 if (SCS.Second == ICK_Pointer_Conversion) {
4353 SCS.Second = ICK_Identity;
4354 SCS.Third = ICK_Identity;
4355 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4356 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004357}
John McCall5c32be02010-08-24 20:38:10 +00004358
John McCallfec112d2011-09-09 06:11:02 +00004359/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4360/// convert the expression From to an Objective-C pointer type.
4361static ImplicitConversionSequence
4362TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4363 // Do an implicit conversion to 'id'.
4364 QualType Ty = S.Context.getObjCIdType();
4365 ImplicitConversionSequence ICS
4366 = TryImplicitConversion(S, From, Ty,
4367 // FIXME: Are these flags correct?
4368 /*SuppressUserConversions=*/false,
4369 /*AllowExplicit=*/true,
4370 /*InOverloadResolution=*/false,
4371 /*CStyle=*/false,
4372 /*AllowObjCWritebackConversion=*/false);
4373
4374 // Strip off any final conversions to 'id'.
4375 switch (ICS.getKind()) {
4376 case ImplicitConversionSequence::BadConversion:
4377 case ImplicitConversionSequence::AmbiguousConversion:
4378 case ImplicitConversionSequence::EllipsisConversion:
4379 break;
4380
4381 case ImplicitConversionSequence::UserDefinedConversion:
4382 dropPointerConversion(ICS.UserDefined.After);
4383 break;
4384
4385 case ImplicitConversionSequence::StandardConversion:
4386 dropPointerConversion(ICS.Standard);
4387 break;
4388 }
4389
4390 return ICS;
4391}
4392
4393/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4394/// conversion of the expression From to an Objective-C pointer type.
4395ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004396 if (checkPlaceholderForOverload(*this, From))
4397 return ExprError();
4398
John McCall8b07ec22010-05-15 11:32:37 +00004399 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004400 ImplicitConversionSequence ICS =
4401 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004402 if (!ICS.isBad())
4403 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004404 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004405}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004406
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004408/// enumeration type.
4409///
4410/// This routine will attempt to convert an expression of class type to an
4411/// integral or enumeration type, if that class type only has a single
4412/// conversion to an integral or enumeration type.
4413///
Douglas Gregor4799d032010-06-30 00:20:43 +00004414/// \param Loc The source location of the construct that requires the
4415/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004416///
Douglas Gregor4799d032010-06-30 00:20:43 +00004417/// \param FromE The expression we're converting from.
4418///
4419/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4420/// have integral or enumeration type.
4421///
4422/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4423/// incomplete class type.
4424///
4425/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4426/// explicit conversion function (because no implicit conversion functions
4427/// were available). This is a recovery mode.
4428///
4429/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4430/// showing which conversion was picked.
4431///
4432/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4433/// conversion function that could convert to integral or enumeration type.
4434///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004436/// usable conversion function.
4437///
4438/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4439/// function, which may be an extension in this case.
4440///
4441/// \returns The expression, converted to an integral or enumeration type if
4442/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443ExprResult
John McCallb268a282010-08-23 23:25:46 +00004444Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004445 const PartialDiagnostic &NotIntDiag,
4446 const PartialDiagnostic &IncompleteDiag,
4447 const PartialDiagnostic &ExplicitConvDiag,
4448 const PartialDiagnostic &ExplicitConvNote,
4449 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004450 const PartialDiagnostic &AmbigNote,
4451 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004452 // We can't perform any more checking for type-dependent expressions.
4453 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004454 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004455
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004456 // If the expression already has integral or enumeration type, we're golden.
4457 QualType T = From->getType();
4458 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004459 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004460
4461 // FIXME: Check for missing '()' if T is a function type?
4462
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004463 // 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 +00004464 // expression of integral or enumeration type.
4465 const RecordType *RecordTy = T->getAs<RecordType>();
4466 if (!RecordTy || !getLangOptions().CPlusPlus) {
4467 Diag(Loc, NotIntDiag)
4468 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004469 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004470 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004471
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004472 // We must have a complete class type.
4473 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004474 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004475
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004476 // Look for a conversion to an integral or enumeration type.
4477 UnresolvedSet<4> ViableConversions;
4478 UnresolvedSet<4> ExplicitConversions;
4479 const UnresolvedSetImpl *Conversions
4480 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004481
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004482 bool HadMultipleCandidates = (Conversions->size() > 1);
4483
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004484 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485 E = Conversions->end();
4486 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004487 ++I) {
4488 if (CXXConversionDecl *Conversion
4489 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4490 if (Conversion->getConversionType().getNonReferenceType()
4491 ->isIntegralOrEnumerationType()) {
4492 if (Conversion->isExplicit())
4493 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4494 else
4495 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4496 }
4497 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004498
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004499 switch (ViableConversions.size()) {
4500 case 0:
4501 if (ExplicitConversions.size() == 1) {
4502 DeclAccessPair Found = ExplicitConversions[0];
4503 CXXConversionDecl *Conversion
4504 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004506 // The user probably meant to invoke the given explicit
4507 // conversion; use it.
4508 QualType ConvTy
4509 = Conversion->getConversionType().getNonReferenceType();
4510 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004511 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004512
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004513 Diag(Loc, ExplicitConvDiag)
4514 << T << ConvTy
4515 << FixItHint::CreateInsertion(From->getLocStart(),
4516 "static_cast<" + TypeStr + ">(")
4517 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4518 ")");
4519 Diag(Conversion->getLocation(), ExplicitConvNote)
4520 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004521
4522 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004523 // explicit conversion function.
4524 if (isSFINAEContext())
4525 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004526
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004527 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004528 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4529 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004530 if (Result.isInvalid())
4531 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004532 // Record usage of conversion in an implicit cast.
4533 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4534 CK_UserDefinedConversion,
4535 Result.get(), 0,
4536 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004538
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004539 // We'll complain below about a non-integral condition type.
4540 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004542 case 1: {
4543 // Apply this conversion.
4544 DeclAccessPair Found = ViableConversions[0];
4545 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004546
Douglas Gregor4799d032010-06-30 00:20:43 +00004547 CXXConversionDecl *Conversion
4548 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4549 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004551 if (ConvDiag.getDiagID()) {
4552 if (isSFINAEContext())
4553 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004554
Douglas Gregor4799d032010-06-30 00:20:43 +00004555 Diag(Loc, ConvDiag)
4556 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4557 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004559 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4560 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004561 if (Result.isInvalid())
4562 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004563 // Record usage of conversion in an implicit cast.
4564 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4565 CK_UserDefinedConversion,
4566 Result.get(), 0,
4567 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004568 break;
4569 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004570
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004571 default:
4572 Diag(Loc, AmbigDiag)
4573 << T << From->getSourceRange();
4574 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4575 CXXConversionDecl *Conv
4576 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4577 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4578 Diag(Conv->getLocation(), AmbigNote)
4579 << ConvTy->isEnumeralType() << ConvTy;
4580 }
John McCallb268a282010-08-23 23:25:46 +00004581 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004582 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004583
Douglas Gregor5823da32010-06-29 23:25:20 +00004584 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004585 Diag(Loc, NotIntDiag)
4586 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004587
John McCallb268a282010-08-23 23:25:46 +00004588 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004589}
4590
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004591/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004592/// candidate functions, using the given function call arguments. If
4593/// @p SuppressUserConversions, then don't allow user-defined
4594/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004595///
4596/// \para PartialOverloading true if we are performing "partial" overloading
4597/// based on an incomplete set of function arguments. This feature is used by
4598/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004599void
4600Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004601 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004602 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004603 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004604 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004605 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004606 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004607 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004608 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004609 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004610 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004611
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004613 if (!isa<CXXConstructorDecl>(Method)) {
4614 // If we get here, it's because we're calling a member function
4615 // that is named without a member access expression (e.g.,
4616 // "this->f") that was either written explicitly or created
4617 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004618 // function, e.g., X::f(). We use an empty type for the implied
4619 // object argument (C++ [over.call.func]p3), and the acting context
4620 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004621 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004622 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004623 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004624 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004625 return;
4626 }
4627 // We treat a constructor like a non-member function, since its object
4628 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004629 }
4630
Douglas Gregorff7028a2009-11-13 23:59:09 +00004631 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004632 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004633
Douglas Gregor27381f32009-11-23 12:27:39 +00004634 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004635 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004636
Douglas Gregorffe14e32009-11-14 01:20:54 +00004637 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4638 // C++ [class.copy]p3:
4639 // A member function template is never instantiated to perform the copy
4640 // of a class object to an object of its class type.
4641 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004642 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004643 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004644 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4645 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004646 return;
4647 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004648
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004649 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004650 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00004651 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004652 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004653 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004654 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004655 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004656 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004657
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004658 unsigned NumArgsInProto = Proto->getNumArgs();
4659
4660 // (C++ 13.3.2p2): A candidate function having fewer than m
4661 // parameters is viable only if it has an ellipsis in its parameter
4662 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004663 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004664 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004665 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004666 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004667 return;
4668 }
4669
4670 // (C++ 13.3.2p2): A candidate function having more than m parameters
4671 // is viable only if the (m+1)st parameter has a default argument
4672 // (8.3.6). For the purposes of overload resolution, the
4673 // parameter list is truncated on the right, so that there are
4674 // exactly m parameters.
4675 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004676 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004677 // Not enough arguments.
4678 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004679 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004680 return;
4681 }
4682
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004683 // (CUDA B.1): Check for invalid calls between targets.
4684 if (getLangOptions().CUDA)
4685 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4686 if (CheckCUDATarget(Caller, Function)) {
4687 Candidate.Viable = false;
4688 Candidate.FailureKind = ovl_fail_bad_target;
4689 return;
4690 }
4691
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004692 // Determine the implicit conversion sequences for each of the
4693 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004694 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4695 if (ArgIdx < NumArgsInProto) {
4696 // (C++ 13.3.2p3): for F to be a viable function, there shall
4697 // exist for each argument an implicit conversion sequence
4698 // (13.3.3.1) that converts that argument to the corresponding
4699 // parameter of F.
4700 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004701 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004702 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004703 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004704 /*InOverloadResolution=*/true,
4705 /*AllowObjCWritebackConversion=*/
4706 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004707 if (Candidate.Conversions[ArgIdx].isBad()) {
4708 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004709 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004710 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004711 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004712 } else {
4713 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4714 // argument for which there is no corresponding parameter is
4715 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004716 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004717 }
4718 }
4719}
4720
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004721/// \brief Add all of the function declarations in the given function set to
4722/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004723void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004724 Expr **Args, unsigned NumArgs,
4725 OverloadCandidateSet& CandidateSet,
4726 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004727 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004728 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004730 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004731 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004732 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004733 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004734 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004735 CandidateSet, SuppressUserConversions);
4736 else
John McCalla0296f72010-03-19 07:35:19 +00004737 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004738 SuppressUserConversions);
4739 } else {
John McCalla0296f72010-03-19 07:35:19 +00004740 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004741 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4742 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004743 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004744 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004745 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004746 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004747 Args[0]->Classify(Context),
4748 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004749 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004750 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004751 else
John McCalla0296f72010-03-19 07:35:19 +00004752 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004753 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004754 Args, NumArgs, CandidateSet,
4755 SuppressUserConversions);
4756 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004757 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004758}
4759
John McCallf0f1cf02009-11-17 07:50:12 +00004760/// AddMethodCandidate - Adds a named decl (which is some kind of
4761/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004762void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004763 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004764 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004765 Expr **Args, unsigned NumArgs,
4766 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004767 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004768 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004769 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004770
4771 if (isa<UsingShadowDecl>(Decl))
4772 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004773
John McCallf0f1cf02009-11-17 07:50:12 +00004774 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4775 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4776 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004777 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4778 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004779 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004780 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004781 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004782 } else {
John McCalla0296f72010-03-19 07:35:19 +00004783 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004784 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004785 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004786 }
4787}
4788
Douglas Gregor436424c2008-11-18 23:14:02 +00004789/// AddMethodCandidate - Adds the given C++ member function to the set
4790/// of candidate functions, using the given function call arguments
4791/// and the object argument (@c Object). For example, in a call
4792/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4793/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4794/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004795/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004796void
John McCalla0296f72010-03-19 07:35:19 +00004797Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004798 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004799 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004800 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004801 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004802 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004803 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004804 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004805 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004806 assert(!isa<CXXConstructorDecl>(Method) &&
4807 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004808
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004809 if (!CandidateSet.isNewCandidate(Method))
4810 return;
4811
Douglas Gregor27381f32009-11-23 12:27:39 +00004812 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004813 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004814
Douglas Gregor436424c2008-11-18 23:14:02 +00004815 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004816 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00004817 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004818 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004819 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004820 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004821 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004822
4823 unsigned NumArgsInProto = Proto->getNumArgs();
4824
4825 // (C++ 13.3.2p2): A candidate function having fewer than m
4826 // parameters is viable only if it has an ellipsis in its parameter
4827 // list (8.3.5).
4828 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4829 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004830 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004831 return;
4832 }
4833
4834 // (C++ 13.3.2p2): A candidate function having more than m parameters
4835 // is viable only if the (m+1)st parameter has a default argument
4836 // (8.3.6). For the purposes of overload resolution, the
4837 // parameter list is truncated on the right, so that there are
4838 // exactly m parameters.
4839 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4840 if (NumArgs < MinRequiredArgs) {
4841 // Not enough arguments.
4842 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004843 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004844 return;
4845 }
4846
4847 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00004848
John McCall6e9f8f62009-12-03 04:06:58 +00004849 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004850 // The implicit object argument is ignored.
4851 Candidate.IgnoreObjectArgument = true;
4852 else {
4853 // Determine the implicit conversion sequence for the object
4854 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004855 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004856 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4857 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004858 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004859 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004860 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004861 return;
4862 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004863 }
4864
4865 // Determine the implicit conversion sequences for each of the
4866 // arguments.
4867 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4868 if (ArgIdx < NumArgsInProto) {
4869 // (C++ 13.3.2p3): for F to be a viable function, there shall
4870 // exist for each argument an implicit conversion sequence
4871 // (13.3.3.1) that converts that argument to the corresponding
4872 // parameter of F.
4873 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004874 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004875 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004877 /*InOverloadResolution=*/true,
4878 /*AllowObjCWritebackConversion=*/
4879 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004880 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004881 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004882 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004883 break;
4884 }
4885 } else {
4886 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4887 // argument for which there is no corresponding parameter is
4888 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004889 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004890 }
4891 }
4892}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004893
Douglas Gregor97628d62009-08-21 00:16:32 +00004894/// \brief Add a C++ member function template as a candidate to the candidate
4895/// set, using template argument deduction to produce an appropriate member
4896/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004897void
Douglas Gregor97628d62009-08-21 00:16:32 +00004898Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004899 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004900 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004901 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004902 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004903 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004904 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004905 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004906 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004907 if (!CandidateSet.isNewCandidate(MethodTmpl))
4908 return;
4909
Douglas Gregor97628d62009-08-21 00:16:32 +00004910 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004911 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004912 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004913 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004914 // candidate functions in the usual way.113) A given name can refer to one
4915 // or more function templates and also to a set of overloaded non-template
4916 // functions. In such a case, the candidate functions generated from each
4917 // function template are combined with the set of non-template candidate
4918 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004919 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004920 FunctionDecl *Specialization = 0;
4921 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004922 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004923 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004924 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004925 Candidate.FoundDecl = FoundDecl;
4926 Candidate.Function = MethodTmpl->getTemplatedDecl();
4927 Candidate.Viable = false;
4928 Candidate.FailureKind = ovl_fail_bad_deduction;
4929 Candidate.IsSurrogate = false;
4930 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004931 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004933 Info);
4934 return;
4935 }
Mike Stump11289f42009-09-09 15:08:12 +00004936
Douglas Gregor97628d62009-08-21 00:16:32 +00004937 // Add the function template specialization produced by template argument
4938 // deduction as a candidate.
4939 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004940 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004941 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004942 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004943 ActingContext, ObjectType, ObjectClassification,
4944 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004945}
4946
Douglas Gregor05155d82009-08-21 23:19:43 +00004947/// \brief Add a C++ function template specialization as a candidate
4948/// in the candidate set, using template argument deduction to produce
4949/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004950void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004951Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004952 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004953 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004954 Expr **Args, unsigned NumArgs,
4955 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004956 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004957 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4958 return;
4959
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004960 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004961 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004962 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004963 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004964 // candidate functions in the usual way.113) A given name can refer to one
4965 // or more function templates and also to a set of overloaded non-template
4966 // functions. In such a case, the candidate functions generated from each
4967 // function template are combined with the set of non-template candidate
4968 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004969 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004970 FunctionDecl *Specialization = 0;
4971 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004972 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004973 Args, NumArgs, Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00004974 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00004975 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004976 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4977 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004978 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004979 Candidate.IsSurrogate = false;
4980 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004981 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004982 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004983 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004984 return;
4985 }
Mike Stump11289f42009-09-09 15:08:12 +00004986
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004987 // Add the function template specialization produced by template argument
4988 // deduction as a candidate.
4989 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004990 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004991 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004992}
Mike Stump11289f42009-09-09 15:08:12 +00004993
Douglas Gregora1f013e2008-11-07 22:36:19 +00004994/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004995/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004996/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004997/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004998/// (which may or may not be the same type as the type that the
4999/// conversion function produces).
5000void
5001Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005002 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005003 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005004 Expr *From, QualType ToType,
5005 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005006 assert(!Conversion->getDescribedFunctionTemplate() &&
5007 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00005008 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005009 if (!CandidateSet.isNewCandidate(Conversion))
5010 return;
5011
Douglas Gregor27381f32009-11-23 12:27:39 +00005012 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005013 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005014
Douglas Gregora1f013e2008-11-07 22:36:19 +00005015 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005016 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00005017 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005018 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005019 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005020 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005021 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00005022 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00005023 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00005024 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005025 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005026
Douglas Gregor6affc782010-08-19 15:37:02 +00005027 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028 // For conversion functions, the function is considered to be a member of
5029 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00005030 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005031 //
5032 // Determine the implicit conversion sequence for the implicit
5033 // object parameter.
5034 QualType ImplicitParamType = From->getType();
5035 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5036 ImplicitParamType = FromPtrType->getPointeeType();
5037 CXXRecordDecl *ConversionContext
5038 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005039
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005040 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005041 = TryObjectArgumentInitialization(*this, From->getType(),
5042 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00005043 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005044
John McCall0d1da222010-01-12 00:44:57 +00005045 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005046 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005047 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005048 return;
5049 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005050
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005051 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005052 // derived to base as such conversions are given Conversion Rank. They only
5053 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5054 QualType FromCanon
5055 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5056 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5057 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5058 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005059 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005060 return;
5061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
Douglas Gregora1f013e2008-11-07 22:36:19 +00005063 // To determine what the conversion from the result of calling the
5064 // conversion function to the type we're eventually trying to
5065 // convert to (ToType), we need to synthesize a call to the
5066 // conversion function and attempt copy initialization from it. This
5067 // makes sure that we get the right semantics with respect to
5068 // lvalues/rvalues and the type. Fortunately, we can allocate this
5069 // call on the stack and we don't need its arguments to be
5070 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005071 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005072 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005073 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5074 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005075 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005076 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005077
Richard Smith48d24642011-07-13 22:53:21 +00005078 QualType ConversionType = Conversion->getConversionType();
5079 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005080 Candidate.Viable = false;
5081 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5082 return;
5083 }
5084
Richard Smith48d24642011-07-13 22:53:21 +00005085 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005086
Mike Stump11289f42009-09-09 15:08:12 +00005087 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005088 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5089 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005090 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005091 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005092 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005093 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005094 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005095 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005096 /*InOverloadResolution=*/false,
5097 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005098
John McCall0d1da222010-01-12 00:44:57 +00005099 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005100 case ImplicitConversionSequence::StandardConversion:
5101 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005102
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005103 // C++ [over.ics.user]p3:
5104 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005105 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005106 // shall have exact match rank.
5107 if (Conversion->getPrimaryTemplate() &&
5108 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5109 Candidate.Viable = false;
5110 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005112
Douglas Gregorcba72b12011-01-21 05:18:22 +00005113 // C++0x [dcl.init.ref]p5:
5114 // In the second case, if the reference is an rvalue reference and
5115 // the second standard conversion sequence of the user-defined
5116 // conversion sequence includes an lvalue-to-rvalue conversion, the
5117 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005118 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005119 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5120 Candidate.Viable = false;
5121 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5122 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005123 break;
5124
5125 case ImplicitConversionSequence::BadConversion:
5126 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005127 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005128 break;
5129
5130 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005131 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005132 "Can only end up with a standard conversion sequence or failure");
5133 }
5134}
5135
Douglas Gregor05155d82009-08-21 23:19:43 +00005136/// \brief Adds a conversion function template specialization
5137/// candidate to the overload set, using template argument deduction
5138/// to deduce the template arguments of the conversion function
5139/// template from the type that we are converting to (C++
5140/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005141void
Douglas Gregor05155d82009-08-21 23:19:43 +00005142Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005143 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005144 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005145 Expr *From, QualType ToType,
5146 OverloadCandidateSet &CandidateSet) {
5147 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5148 "Only conversion function templates permitted here");
5149
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005150 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5151 return;
5152
John McCallbc077cf2010-02-08 23:07:23 +00005153 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005154 CXXConversionDecl *Specialization = 0;
5155 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005156 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005157 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005158 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005159 Candidate.FoundDecl = FoundDecl;
5160 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5161 Candidate.Viable = false;
5162 Candidate.FailureKind = ovl_fail_bad_deduction;
5163 Candidate.IsSurrogate = false;
5164 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005165 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005166 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005167 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005168 return;
5169 }
Mike Stump11289f42009-09-09 15:08:12 +00005170
Douglas Gregor05155d82009-08-21 23:19:43 +00005171 // Add the conversion function template specialization produced by
5172 // template argument deduction as a candidate.
5173 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005174 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005175 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005176}
5177
Douglas Gregorab7897a2008-11-19 22:57:39 +00005178/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5179/// converts the given @c Object to a function pointer via the
5180/// conversion function @c Conversion, and then attempts to call it
5181/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5182/// the type of function that we'll eventually be calling.
5183void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005184 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005185 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005186 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005187 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005188 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005189 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005190 if (!CandidateSet.isNewCandidate(Conversion))
5191 return;
5192
Douglas Gregor27381f32009-11-23 12:27:39 +00005193 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005194 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005195
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005196 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs + 1);
John McCalla0296f72010-03-19 07:35:19 +00005197 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005198 Candidate.Function = 0;
5199 Candidate.Surrogate = Conversion;
5200 Candidate.Viable = true;
5201 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005202 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005203 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005204
5205 // Determine the implicit conversion sequence for the implicit
5206 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005207 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005208 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005209 Object->Classify(Context),
5210 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005211 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005212 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005213 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005214 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005215 return;
5216 }
5217
5218 // The first conversion is actually a user-defined conversion whose
5219 // first conversion is ObjectInit's standard conversion (which is
5220 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005221 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005222 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005223 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005224 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005225 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005226 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005227 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005228 = Candidate.Conversions[0].UserDefined.Before;
5229 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5230
Mike Stump11289f42009-09-09 15:08:12 +00005231 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005232 unsigned NumArgsInProto = Proto->getNumArgs();
5233
5234 // (C++ 13.3.2p2): A candidate function having fewer than m
5235 // parameters is viable only if it has an ellipsis in its parameter
5236 // list (8.3.5).
5237 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5238 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005239 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005240 return;
5241 }
5242
5243 // Function types don't have any default arguments, so just check if
5244 // we have enough arguments.
5245 if (NumArgs < NumArgsInProto) {
5246 // Not enough arguments.
5247 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005248 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005249 return;
5250 }
5251
5252 // Determine the implicit conversion sequences for each of the
5253 // arguments.
5254 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5255 if (ArgIdx < NumArgsInProto) {
5256 // (C++ 13.3.2p3): for F to be a viable function, there shall
5257 // exist for each argument an implicit conversion sequence
5258 // (13.3.3.1) that converts that argument to the corresponding
5259 // parameter of F.
5260 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005261 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005262 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005263 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005264 /*InOverloadResolution=*/false,
5265 /*AllowObjCWritebackConversion=*/
5266 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005267 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005268 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005269 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005270 break;
5271 }
5272 } else {
5273 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5274 // argument for which there is no corresponding parameter is
5275 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005276 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005277 }
5278 }
5279}
5280
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005281/// \brief Add overload candidates for overloaded operators that are
5282/// member functions.
5283///
5284/// Add the overloaded operator candidates that are member functions
5285/// for the operator Op that was used in an operator expression such
5286/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5287/// CandidateSet will store the added overload candidates. (C++
5288/// [over.match.oper]).
5289void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5290 SourceLocation OpLoc,
5291 Expr **Args, unsigned NumArgs,
5292 OverloadCandidateSet& CandidateSet,
5293 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005294 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5295
5296 // C++ [over.match.oper]p3:
5297 // For a unary operator @ with an operand of a type whose
5298 // cv-unqualified version is T1, and for a binary operator @ with
5299 // a left operand of a type whose cv-unqualified version is T1 and
5300 // a right operand of a type whose cv-unqualified version is T2,
5301 // three sets of candidate functions, designated member
5302 // candidates, non-member candidates and built-in candidates, are
5303 // constructed as follows:
5304 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005305
5306 // -- If T1 is a class type, the set of member candidates is the
5307 // result of the qualified lookup of T1::operator@
5308 // (13.3.1.1.1); otherwise, the set of member candidates is
5309 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005310 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005311 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005312 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005313 return;
Mike Stump11289f42009-09-09 15:08:12 +00005314
John McCall27b18f82009-11-17 02:14:36 +00005315 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5316 LookupQualifiedName(Operators, T1Rec->getDecl());
5317 Operators.suppressDiagnostics();
5318
Mike Stump11289f42009-09-09 15:08:12 +00005319 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005320 OperEnd = Operators.end();
5321 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005322 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005323 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005324 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005325 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005326 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005327 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005328}
5329
Douglas Gregora11693b2008-11-12 17:17:38 +00005330/// AddBuiltinCandidate - Add a candidate for a built-in
5331/// operator. ResultTy and ParamTys are the result and parameter types
5332/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005333/// arguments being passed to the candidate. IsAssignmentOperator
5334/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005335/// operator. NumContextualBoolArguments is the number of arguments
5336/// (at the beginning of the argument list) that will be contextually
5337/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005338void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005339 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005340 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005341 bool IsAssignmentOperator,
5342 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005343 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005344 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005345
Douglas Gregora11693b2008-11-12 17:17:38 +00005346 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005347 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCalla0296f72010-03-19 07:35:19 +00005348 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005349 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005350 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005351 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005352 Candidate.BuiltinTypes.ResultTy = ResultTy;
5353 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5354 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5355
5356 // Determine the implicit conversion sequences for each of the
5357 // arguments.
5358 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005359 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005360 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005361 // C++ [over.match.oper]p4:
5362 // For the built-in assignment operators, conversions of the
5363 // left operand are restricted as follows:
5364 // -- no temporaries are introduced to hold the left operand, and
5365 // -- no user-defined conversions are applied to the left
5366 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005367 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005368 //
5369 // We block these conversions by turning off user-defined
5370 // conversions, since that is the only way that initialization of
5371 // a reference to a non-class type can occur from something that
5372 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005373 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005374 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005375 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005376 Candidate.Conversions[ArgIdx]
5377 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005378 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005379 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005380 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005381 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005382 /*InOverloadResolution=*/false,
5383 /*AllowObjCWritebackConversion=*/
5384 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005385 }
John McCall0d1da222010-01-12 00:44:57 +00005386 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005387 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005388 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005389 break;
5390 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005391 }
5392}
5393
5394/// BuiltinCandidateTypeSet - A set of types that will be used for the
5395/// candidate operator functions for built-in operators (C++
5396/// [over.built]). The types are separated into pointer types and
5397/// enumeration types.
5398class BuiltinCandidateTypeSet {
5399 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005400 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005401
5402 /// PointerTypes - The set of pointer types that will be used in the
5403 /// built-in candidates.
5404 TypeSet PointerTypes;
5405
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005406 /// MemberPointerTypes - The set of member pointer types that will be
5407 /// used in the built-in candidates.
5408 TypeSet MemberPointerTypes;
5409
Douglas Gregora11693b2008-11-12 17:17:38 +00005410 /// EnumerationTypes - The set of enumeration types that will be
5411 /// used in the built-in candidates.
5412 TypeSet EnumerationTypes;
5413
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005414 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005415 /// candidates.
5416 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005417
5418 /// \brief A flag indicating non-record types are viable candidates
5419 bool HasNonRecordTypes;
5420
5421 /// \brief A flag indicating whether either arithmetic or enumeration types
5422 /// were present in the candidate set.
5423 bool HasArithmeticOrEnumeralTypes;
5424
Douglas Gregor80af3132011-05-21 23:15:46 +00005425 /// \brief A flag indicating whether the nullptr type was present in the
5426 /// candidate set.
5427 bool HasNullPtrType;
5428
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005429 /// Sema - The semantic analysis instance where we are building the
5430 /// candidate type set.
5431 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005432
Douglas Gregora11693b2008-11-12 17:17:38 +00005433 /// Context - The AST context in which we will build the type sets.
5434 ASTContext &Context;
5435
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005436 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5437 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005438 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005439
5440public:
5441 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005442 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005443
Mike Stump11289f42009-09-09 15:08:12 +00005444 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005445 : HasNonRecordTypes(false),
5446 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005447 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005448 SemaRef(SemaRef),
5449 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005450
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005451 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005452 SourceLocation Loc,
5453 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005454 bool AllowExplicitConversions,
5455 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005456
5457 /// pointer_begin - First pointer type found;
5458 iterator pointer_begin() { return PointerTypes.begin(); }
5459
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005460 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005461 iterator pointer_end() { return PointerTypes.end(); }
5462
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005463 /// member_pointer_begin - First member pointer type found;
5464 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5465
5466 /// member_pointer_end - Past the last member pointer type found;
5467 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5468
Douglas Gregora11693b2008-11-12 17:17:38 +00005469 /// enumeration_begin - First enumeration type found;
5470 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5471
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005472 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005473 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005474
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005475 iterator vector_begin() { return VectorTypes.begin(); }
5476 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005477
5478 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5479 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005480 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005481};
5482
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005483/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005484/// the set of pointer types along with any more-qualified variants of
5485/// that type. For example, if @p Ty is "int const *", this routine
5486/// will add "int const *", "int const volatile *", "int const
5487/// restrict *", and "int const volatile restrict *" to the set of
5488/// pointer types. Returns true if the add of @p Ty itself succeeded,
5489/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005490///
5491/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005492bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005493BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5494 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005495
Douglas Gregora11693b2008-11-12 17:17:38 +00005496 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005497 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005498 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005499
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005500 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005501 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005502 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005503 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005504 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005505 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005506 buildObjCPtr = true;
5507 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005508 else
David Blaikie83d382b2011-09-23 05:06:16 +00005509 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005510 }
5511 else
5512 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513
Sebastian Redl4990a632009-11-18 20:39:26 +00005514 // Don't add qualified variants of arrays. For one, they're not allowed
5515 // (the qualifier would sink to the element type), and for another, the
5516 // only overload situation where it matters is subscript or pointer +- int,
5517 // and those shouldn't have qualifier variants anyway.
5518 if (PointeeTy->isArrayType())
5519 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005520 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005521 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005522 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005523 bool hasVolatile = VisibleQuals.hasVolatile();
5524 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005525
John McCall8ccfcb52009-09-24 19:53:00 +00005526 // Iterate through all strict supersets of BaseCVR.
5527 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5528 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005529 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5530 // in the types.
5531 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5532 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005533 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005534 if (!buildObjCPtr)
5535 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5536 else
5537 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005538 }
5539
5540 return true;
5541}
5542
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005543/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5544/// to the set of pointer types along with any more-qualified variants of
5545/// that type. For example, if @p Ty is "int const *", this routine
5546/// will add "int const *", "int const volatile *", "int const
5547/// restrict *", and "int const volatile restrict *" to the set of
5548/// pointer types. Returns true if the add of @p Ty itself succeeded,
5549/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005550///
5551/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005552bool
5553BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5554 QualType Ty) {
5555 // Insert this type.
5556 if (!MemberPointerTypes.insert(Ty))
5557 return false;
5558
John McCall8ccfcb52009-09-24 19:53:00 +00005559 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5560 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005561
John McCall8ccfcb52009-09-24 19:53:00 +00005562 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005563 // Don't add qualified variants of arrays. For one, they're not allowed
5564 // (the qualifier would sink to the element type), and for another, the
5565 // only overload situation where it matters is subscript or pointer +- int,
5566 // and those shouldn't have qualifier variants anyway.
5567 if (PointeeTy->isArrayType())
5568 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005569 const Type *ClassTy = PointerTy->getClass();
5570
5571 // Iterate through all strict supersets of the pointee type's CVR
5572 // qualifiers.
5573 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5574 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5575 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005576
John McCall8ccfcb52009-09-24 19:53:00 +00005577 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005578 MemberPointerTypes.insert(
5579 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005580 }
5581
5582 return true;
5583}
5584
Douglas Gregora11693b2008-11-12 17:17:38 +00005585/// AddTypesConvertedFrom - Add each of the types to which the type @p
5586/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005587/// primarily interested in pointer types and enumeration types. We also
5588/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005589/// AllowUserConversions is true if we should look at the conversion
5590/// functions of a class type, and AllowExplicitConversions if we
5591/// should also include the explicit conversion functions of a class
5592/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005593void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005594BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005595 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005596 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005597 bool AllowExplicitConversions,
5598 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005599 // Only deal with canonical types.
5600 Ty = Context.getCanonicalType(Ty);
5601
5602 // Look through reference types; they aren't part of the type of an
5603 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005604 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005605 Ty = RefTy->getPointeeType();
5606
John McCall33ddac02011-01-19 10:06:00 +00005607 // If we're dealing with an array type, decay to the pointer.
5608 if (Ty->isArrayType())
5609 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5610
5611 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005612 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005613
Chandler Carruth00a38332010-12-13 01:44:01 +00005614 // Flag if we ever add a non-record type.
5615 const RecordType *TyRec = Ty->getAs<RecordType>();
5616 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5617
Chandler Carruth00a38332010-12-13 01:44:01 +00005618 // Flag if we encounter an arithmetic type.
5619 HasArithmeticOrEnumeralTypes =
5620 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5621
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005622 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5623 PointerTypes.insert(Ty);
5624 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005625 // Insert our type, and its more-qualified variants, into the set
5626 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005627 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005628 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005629 } else if (Ty->isMemberPointerType()) {
5630 // Member pointers are far easier, since the pointee can't be converted.
5631 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5632 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005633 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005634 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005635 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005636 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005637 // We treat vector types as arithmetic types in many contexts as an
5638 // extension.
5639 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005640 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005641 } else if (Ty->isNullPtrType()) {
5642 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005643 } else if (AllowUserConversions && TyRec) {
5644 // No conversion functions in incomplete types.
5645 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5646 return;
Mike Stump11289f42009-09-09 15:08:12 +00005647
Chandler Carruth00a38332010-12-13 01:44:01 +00005648 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5649 const UnresolvedSetImpl *Conversions
5650 = ClassDecl->getVisibleConversionFunctions();
5651 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5652 E = Conversions->end(); I != E; ++I) {
5653 NamedDecl *D = I.getDecl();
5654 if (isa<UsingShadowDecl>(D))
5655 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005656
Chandler Carruth00a38332010-12-13 01:44:01 +00005657 // Skip conversion function templates; they don't tell us anything
5658 // about which builtin types we can convert to.
5659 if (isa<FunctionTemplateDecl>(D))
5660 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005661
Chandler Carruth00a38332010-12-13 01:44:01 +00005662 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5663 if (AllowExplicitConversions || !Conv->isExplicit()) {
5664 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5665 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005666 }
5667 }
5668 }
5669}
5670
Douglas Gregor84605ae2009-08-24 13:43:27 +00005671/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5672/// the volatile- and non-volatile-qualified assignment operators for the
5673/// given type to the candidate set.
5674static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5675 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005676 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005677 unsigned NumArgs,
5678 OverloadCandidateSet &CandidateSet) {
5679 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005680
Douglas Gregor84605ae2009-08-24 13:43:27 +00005681 // T& operator=(T&, T)
5682 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5683 ParamTypes[1] = T;
5684 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5685 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005686
Douglas Gregor84605ae2009-08-24 13:43:27 +00005687 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5688 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005689 ParamTypes[0]
5690 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005691 ParamTypes[1] = T;
5692 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005693 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005694 }
5695}
Mike Stump11289f42009-09-09 15:08:12 +00005696
Sebastian Redl1054fae2009-10-25 17:03:50 +00005697/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5698/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005699static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5700 Qualifiers VRQuals;
5701 const RecordType *TyRec;
5702 if (const MemberPointerType *RHSMPType =
5703 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005704 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005705 else
5706 TyRec = ArgExpr->getType()->getAs<RecordType>();
5707 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005708 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005709 VRQuals.addVolatile();
5710 VRQuals.addRestrict();
5711 return VRQuals;
5712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005713
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005714 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005715 if (!ClassDecl->hasDefinition())
5716 return VRQuals;
5717
John McCallad371252010-01-20 00:46:10 +00005718 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005719 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005720
John McCallad371252010-01-20 00:46:10 +00005721 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005722 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005723 NamedDecl *D = I.getDecl();
5724 if (isa<UsingShadowDecl>(D))
5725 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5726 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005727 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5728 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5729 CanTy = ResTypeRef->getPointeeType();
5730 // Need to go down the pointer/mempointer chain and add qualifiers
5731 // as see them.
5732 bool done = false;
5733 while (!done) {
5734 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5735 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005736 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005737 CanTy->getAs<MemberPointerType>())
5738 CanTy = ResTypeMPtr->getPointeeType();
5739 else
5740 done = true;
5741 if (CanTy.isVolatileQualified())
5742 VRQuals.addVolatile();
5743 if (CanTy.isRestrictQualified())
5744 VRQuals.addRestrict();
5745 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5746 return VRQuals;
5747 }
5748 }
5749 }
5750 return VRQuals;
5751}
John McCall52872982010-11-13 05:51:15 +00005752
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005753namespace {
John McCall52872982010-11-13 05:51:15 +00005754
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005755/// \brief Helper class to manage the addition of builtin operator overload
5756/// candidates. It provides shared state and utility methods used throughout
5757/// the process, as well as a helper method to add each group of builtin
5758/// operator overloads from the standard to a candidate set.
5759class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005760 // Common instance state available to all overload candidate addition methods.
5761 Sema &S;
5762 Expr **Args;
5763 unsigned NumArgs;
5764 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005765 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005766 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005767 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005768
Chandler Carruthc6586e52010-12-12 10:35:00 +00005769 // Define some constants used to index and iterate over the arithemetic types
5770 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005771 // The "promoted arithmetic types" are the arithmetic
5772 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005773 static const unsigned FirstIntegralType = 3;
5774 static const unsigned LastIntegralType = 18;
5775 static const unsigned FirstPromotedIntegralType = 3,
5776 LastPromotedIntegralType = 9;
5777 static const unsigned FirstPromotedArithmeticType = 0,
5778 LastPromotedArithmeticType = 9;
5779 static const unsigned NumArithmeticTypes = 18;
5780
Chandler Carruthc6586e52010-12-12 10:35:00 +00005781 /// \brief Get the canonical type for a given arithmetic type index.
5782 CanQualType getArithmeticType(unsigned index) {
5783 assert(index < NumArithmeticTypes);
5784 static CanQualType ASTContext::* const
5785 ArithmeticTypes[NumArithmeticTypes] = {
5786 // Start of promoted types.
5787 &ASTContext::FloatTy,
5788 &ASTContext::DoubleTy,
5789 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005790
Chandler Carruthc6586e52010-12-12 10:35:00 +00005791 // Start of integral types.
5792 &ASTContext::IntTy,
5793 &ASTContext::LongTy,
5794 &ASTContext::LongLongTy,
5795 &ASTContext::UnsignedIntTy,
5796 &ASTContext::UnsignedLongTy,
5797 &ASTContext::UnsignedLongLongTy,
5798 // End of promoted types.
5799
5800 &ASTContext::BoolTy,
5801 &ASTContext::CharTy,
5802 &ASTContext::WCharTy,
5803 &ASTContext::Char16Ty,
5804 &ASTContext::Char32Ty,
5805 &ASTContext::SignedCharTy,
5806 &ASTContext::ShortTy,
5807 &ASTContext::UnsignedCharTy,
5808 &ASTContext::UnsignedShortTy,
5809 // End of integral types.
5810 // FIXME: What about complex?
5811 };
5812 return S.Context.*ArithmeticTypes[index];
5813 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005814
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005815 /// \brief Gets the canonical type resulting from the usual arithemetic
5816 /// converions for the given arithmetic types.
5817 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5818 // Accelerator table for performing the usual arithmetic conversions.
5819 // The rules are basically:
5820 // - if either is floating-point, use the wider floating-point
5821 // - if same signedness, use the higher rank
5822 // - if same size, use unsigned of the higher rank
5823 // - use the larger type
5824 // These rules, together with the axiom that higher ranks are
5825 // never smaller, are sufficient to precompute all of these results
5826 // *except* when dealing with signed types of higher rank.
5827 // (we could precompute SLL x UI for all known platforms, but it's
5828 // better not to make any assumptions).
5829 enum PromotedType {
5830 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5831 };
5832 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5833 [LastPromotedArithmeticType] = {
5834 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5835 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5836 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5837 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5838 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5839 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5840 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5841 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5842 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5843 };
5844
5845 assert(L < LastPromotedArithmeticType);
5846 assert(R < LastPromotedArithmeticType);
5847 int Idx = ConversionsTable[L][R];
5848
5849 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005850 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005851
5852 // Slow path: we need to compare widths.
5853 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005854 CanQualType LT = getArithmeticType(L),
5855 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005856 unsigned LW = S.Context.getIntWidth(LT),
5857 RW = S.Context.getIntWidth(RT);
5858
5859 // If they're different widths, use the signed type.
5860 if (LW > RW) return LT;
5861 else if (LW < RW) return RT;
5862
5863 // Otherwise, use the unsigned type of the signed type's rank.
5864 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5865 assert(L == SLL || R == SLL);
5866 return S.Context.UnsignedLongLongTy;
5867 }
5868
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005869 /// \brief Helper method to factor out the common pattern of adding overloads
5870 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005871 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5872 bool HasVolatile) {
5873 QualType ParamTypes[2] = {
5874 S.Context.getLValueReferenceType(CandidateTy),
5875 S.Context.IntTy
5876 };
5877
5878 // Non-volatile version.
5879 if (NumArgs == 1)
5880 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5881 else
5882 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5883
5884 // Use a heuristic to reduce number of builtin candidates in the set:
5885 // add volatile version only if there are conversions to a volatile type.
5886 if (HasVolatile) {
5887 ParamTypes[0] =
5888 S.Context.getLValueReferenceType(
5889 S.Context.getVolatileType(CandidateTy));
5890 if (NumArgs == 1)
5891 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5892 else
5893 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5894 }
5895 }
5896
5897public:
5898 BuiltinOperatorOverloadBuilder(
5899 Sema &S, Expr **Args, unsigned NumArgs,
5900 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005901 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005902 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005903 OverloadCandidateSet &CandidateSet)
5904 : S(S), Args(Args), NumArgs(NumArgs),
5905 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005906 HasArithmeticOrEnumeralCandidateType(
5907 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005908 CandidateTypes(CandidateTypes),
5909 CandidateSet(CandidateSet) {
5910 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005911 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005912 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005913 assert(getArithmeticType(LastPromotedIntegralType - 1)
5914 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005915 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005916 assert(getArithmeticType(FirstPromotedArithmeticType)
5917 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005918 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005919 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5920 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005921 "Invalid last promoted arithmetic type");
5922 }
5923
5924 // C++ [over.built]p3:
5925 //
5926 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5927 // is either volatile or empty, there exist candidate operator
5928 // functions of the form
5929 //
5930 // VQ T& operator++(VQ T&);
5931 // T operator++(VQ T&, int);
5932 //
5933 // C++ [over.built]p4:
5934 //
5935 // For every pair (T, VQ), where T is an arithmetic type other
5936 // than bool, and VQ is either volatile or empty, there exist
5937 // candidate operator functions of the form
5938 //
5939 // VQ T& operator--(VQ T&);
5940 // T operator--(VQ T&, int);
5941 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005942 if (!HasArithmeticOrEnumeralCandidateType)
5943 return;
5944
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005945 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5946 Arith < NumArithmeticTypes; ++Arith) {
5947 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005948 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005949 VisibleTypeConversionsQuals.hasVolatile());
5950 }
5951 }
5952
5953 // C++ [over.built]p5:
5954 //
5955 // For every pair (T, VQ), where T is a cv-qualified or
5956 // cv-unqualified object type, and VQ is either volatile or
5957 // empty, there exist candidate operator functions of the form
5958 //
5959 // T*VQ& operator++(T*VQ&);
5960 // T*VQ& operator--(T*VQ&);
5961 // T* operator++(T*VQ&, int);
5962 // T* operator--(T*VQ&, int);
5963 void addPlusPlusMinusMinusPointerOverloads() {
5964 for (BuiltinCandidateTypeSet::iterator
5965 Ptr = CandidateTypes[0].pointer_begin(),
5966 PtrEnd = CandidateTypes[0].pointer_end();
5967 Ptr != PtrEnd; ++Ptr) {
5968 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005969 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005970 continue;
5971
5972 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5973 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5974 VisibleTypeConversionsQuals.hasVolatile()));
5975 }
5976 }
5977
5978 // C++ [over.built]p6:
5979 // For every cv-qualified or cv-unqualified object type T, there
5980 // exist candidate operator functions of the form
5981 //
5982 // T& operator*(T*);
5983 //
5984 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005985 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005986 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005987 // T& operator*(T*);
5988 void addUnaryStarPointerOverloads() {
5989 for (BuiltinCandidateTypeSet::iterator
5990 Ptr = CandidateTypes[0].pointer_begin(),
5991 PtrEnd = CandidateTypes[0].pointer_end();
5992 Ptr != PtrEnd; ++Ptr) {
5993 QualType ParamTy = *Ptr;
5994 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005995 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5996 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005997
Douglas Gregor02824322011-01-26 19:30:28 +00005998 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5999 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6000 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006001
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006002 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6003 &ParamTy, Args, 1, CandidateSet);
6004 }
6005 }
6006
6007 // C++ [over.built]p9:
6008 // For every promoted arithmetic type T, there exist candidate
6009 // operator functions of the form
6010 //
6011 // T operator+(T);
6012 // T operator-(T);
6013 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006014 if (!HasArithmeticOrEnumeralCandidateType)
6015 return;
6016
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006017 for (unsigned Arith = FirstPromotedArithmeticType;
6018 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006019 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006020 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6021 }
6022
6023 // Extension: We also add these operators for vector types.
6024 for (BuiltinCandidateTypeSet::iterator
6025 Vec = CandidateTypes[0].vector_begin(),
6026 VecEnd = CandidateTypes[0].vector_end();
6027 Vec != VecEnd; ++Vec) {
6028 QualType VecTy = *Vec;
6029 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6030 }
6031 }
6032
6033 // C++ [over.built]p8:
6034 // For every type T, there exist candidate operator functions of
6035 // the form
6036 //
6037 // T* operator+(T*);
6038 void addUnaryPlusPointerOverloads() {
6039 for (BuiltinCandidateTypeSet::iterator
6040 Ptr = CandidateTypes[0].pointer_begin(),
6041 PtrEnd = CandidateTypes[0].pointer_end();
6042 Ptr != PtrEnd; ++Ptr) {
6043 QualType ParamTy = *Ptr;
6044 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6045 }
6046 }
6047
6048 // C++ [over.built]p10:
6049 // For every promoted integral type T, there exist candidate
6050 // operator functions of the form
6051 //
6052 // T operator~(T);
6053 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006054 if (!HasArithmeticOrEnumeralCandidateType)
6055 return;
6056
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006057 for (unsigned Int = FirstPromotedIntegralType;
6058 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006059 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006060 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6061 }
6062
6063 // Extension: We also add this operator for vector types.
6064 for (BuiltinCandidateTypeSet::iterator
6065 Vec = CandidateTypes[0].vector_begin(),
6066 VecEnd = CandidateTypes[0].vector_end();
6067 Vec != VecEnd; ++Vec) {
6068 QualType VecTy = *Vec;
6069 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6070 }
6071 }
6072
6073 // C++ [over.match.oper]p16:
6074 // For every pointer to member type T, there exist candidate operator
6075 // functions of the form
6076 //
6077 // bool operator==(T,T);
6078 // bool operator!=(T,T);
6079 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6080 /// Set of (canonical) types that we've already handled.
6081 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6082
6083 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6084 for (BuiltinCandidateTypeSet::iterator
6085 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6086 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6087 MemPtr != MemPtrEnd;
6088 ++MemPtr) {
6089 // Don't add the same builtin candidate twice.
6090 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6091 continue;
6092
6093 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6094 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6095 CandidateSet);
6096 }
6097 }
6098 }
6099
6100 // C++ [over.built]p15:
6101 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006102 // For every T, where T is an enumeration type, a pointer type, or
6103 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006104 //
6105 // bool operator<(T, T);
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);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006111 void addRelationalPointerOrEnumeralOverloads() {
6112 // C++ [over.built]p1:
6113 // If there is a user-written candidate with the same name and parameter
6114 // types as a built-in candidate operator function, the built-in operator
6115 // function is hidden and is not included in the set of candidate
6116 // functions.
6117 //
6118 // The text is actually in a note, but if we don't implement it then we end
6119 // up with ambiguities when the user provides an overloaded operator for
6120 // an enumeration type. Note that only enumeration types have this problem,
6121 // so we track which enumeration types we've seen operators for. Also, the
6122 // only other overloaded operator with enumeration argumenst, operator=,
6123 // cannot be overloaded for enumeration types, so this is the only place
6124 // where we must suppress candidates like this.
6125 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6126 UserDefinedBinaryOperators;
6127
6128 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6129 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6130 CandidateTypes[ArgIdx].enumeration_end()) {
6131 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6132 CEnd = CandidateSet.end();
6133 C != CEnd; ++C) {
6134 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6135 continue;
6136
6137 QualType FirstParamType =
6138 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6139 QualType SecondParamType =
6140 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6141
6142 // Skip if either parameter isn't of enumeral type.
6143 if (!FirstParamType->isEnumeralType() ||
6144 !SecondParamType->isEnumeralType())
6145 continue;
6146
6147 // Add this operator to the set of known user-defined operators.
6148 UserDefinedBinaryOperators.insert(
6149 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6150 S.Context.getCanonicalType(SecondParamType)));
6151 }
6152 }
6153 }
6154
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006155 /// Set of (canonical) types that we've already handled.
6156 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6157
6158 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6159 for (BuiltinCandidateTypeSet::iterator
6160 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6161 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6162 Ptr != PtrEnd; ++Ptr) {
6163 // Don't add the same builtin candidate twice.
6164 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6165 continue;
6166
6167 QualType ParamTypes[2] = { *Ptr, *Ptr };
6168 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6169 CandidateSet);
6170 }
6171 for (BuiltinCandidateTypeSet::iterator
6172 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6173 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6174 Enum != EnumEnd; ++Enum) {
6175 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6176
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006177 // Don't add the same builtin candidate twice, or if a user defined
6178 // candidate exists.
6179 if (!AddedTypes.insert(CanonType) ||
6180 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6181 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006182 continue;
6183
6184 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006185 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6186 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006187 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006188
6189 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6190 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6191 if (AddedTypes.insert(NullPtrTy) &&
6192 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6193 NullPtrTy))) {
6194 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6195 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6196 CandidateSet);
6197 }
6198 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006199 }
6200 }
6201
6202 // C++ [over.built]p13:
6203 //
6204 // For every cv-qualified or cv-unqualified object type T
6205 // there exist candidate operator functions of the form
6206 //
6207 // T* operator+(T*, ptrdiff_t);
6208 // T& operator[](T*, ptrdiff_t); [BELOW]
6209 // T* operator-(T*, ptrdiff_t);
6210 // T* operator+(ptrdiff_t, T*);
6211 // T& operator[](ptrdiff_t, T*); [BELOW]
6212 //
6213 // C++ [over.built]p14:
6214 //
6215 // For every T, where T is a pointer to object type, there
6216 // exist candidate operator functions of the form
6217 //
6218 // ptrdiff_t operator-(T, T);
6219 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6220 /// Set of (canonical) types that we've already handled.
6221 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6222
6223 for (int Arg = 0; Arg < 2; ++Arg) {
6224 QualType AsymetricParamTypes[2] = {
6225 S.Context.getPointerDiffType(),
6226 S.Context.getPointerDiffType(),
6227 };
6228 for (BuiltinCandidateTypeSet::iterator
6229 Ptr = CandidateTypes[Arg].pointer_begin(),
6230 PtrEnd = CandidateTypes[Arg].pointer_end();
6231 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006232 QualType PointeeTy = (*Ptr)->getPointeeType();
6233 if (!PointeeTy->isObjectType())
6234 continue;
6235
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006236 AsymetricParamTypes[Arg] = *Ptr;
6237 if (Arg == 0 || Op == OO_Plus) {
6238 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6239 // T* operator+(ptrdiff_t, T*);
6240 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6241 CandidateSet);
6242 }
6243 if (Op == OO_Minus) {
6244 // ptrdiff_t operator-(T, T);
6245 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6246 continue;
6247
6248 QualType ParamTypes[2] = { *Ptr, *Ptr };
6249 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6250 Args, 2, CandidateSet);
6251 }
6252 }
6253 }
6254 }
6255
6256 // C++ [over.built]p12:
6257 //
6258 // For every pair of promoted arithmetic types L and R, there
6259 // exist candidate operator functions of the form
6260 //
6261 // LR operator*(L, R);
6262 // LR operator/(L, R);
6263 // LR operator+(L, R);
6264 // LR operator-(L, R);
6265 // bool 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 //
6272 // where LR is the result of the usual arithmetic conversions
6273 // between types L and R.
6274 //
6275 // C++ [over.built]p24:
6276 //
6277 // For every pair of promoted arithmetic types L and R, there exist
6278 // candidate operator functions of the form
6279 //
6280 // LR operator?(bool, L, R);
6281 //
6282 // where LR is the result of the usual arithmetic conversions
6283 // between types L and R.
6284 // Our candidates ignore the first parameter.
6285 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006286 if (!HasArithmeticOrEnumeralCandidateType)
6287 return;
6288
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006289 for (unsigned Left = FirstPromotedArithmeticType;
6290 Left < LastPromotedArithmeticType; ++Left) {
6291 for (unsigned Right = FirstPromotedArithmeticType;
6292 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006293 QualType LandR[2] = { getArithmeticType(Left),
6294 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006295 QualType Result =
6296 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006297 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006298 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6299 }
6300 }
6301
6302 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6303 // conditional operator for vector types.
6304 for (BuiltinCandidateTypeSet::iterator
6305 Vec1 = CandidateTypes[0].vector_begin(),
6306 Vec1End = CandidateTypes[0].vector_end();
6307 Vec1 != Vec1End; ++Vec1) {
6308 for (BuiltinCandidateTypeSet::iterator
6309 Vec2 = CandidateTypes[1].vector_begin(),
6310 Vec2End = CandidateTypes[1].vector_end();
6311 Vec2 != Vec2End; ++Vec2) {
6312 QualType LandR[2] = { *Vec1, *Vec2 };
6313 QualType Result = S.Context.BoolTy;
6314 if (!isComparison) {
6315 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6316 Result = *Vec1;
6317 else
6318 Result = *Vec2;
6319 }
6320
6321 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6322 }
6323 }
6324 }
6325
6326 // C++ [over.built]p17:
6327 //
6328 // For every pair of promoted integral types L and R, there
6329 // exist candidate operator functions of the form
6330 //
6331 // LR operator%(L, R);
6332 // LR operator&(L, R);
6333 // LR operator^(L, R);
6334 // LR operator|(L, R);
6335 // L operator<<(L, R);
6336 // L operator>>(L, R);
6337 //
6338 // where LR is the result of the usual arithmetic conversions
6339 // between types L and R.
6340 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006341 if (!HasArithmeticOrEnumeralCandidateType)
6342 return;
6343
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006344 for (unsigned Left = FirstPromotedIntegralType;
6345 Left < LastPromotedIntegralType; ++Left) {
6346 for (unsigned Right = FirstPromotedIntegralType;
6347 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006348 QualType LandR[2] = { getArithmeticType(Left),
6349 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006350 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6351 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006352 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006353 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6354 }
6355 }
6356 }
6357
6358 // C++ [over.built]p20:
6359 //
6360 // For every pair (T, VQ), where T is an enumeration or
6361 // pointer to member type and VQ is either volatile or
6362 // empty, there exist candidate operator functions of the form
6363 //
6364 // VQ T& operator=(VQ T&, T);
6365 void addAssignmentMemberPointerOrEnumeralOverloads() {
6366 /// Set of (canonical) types that we've already handled.
6367 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6368
6369 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6370 for (BuiltinCandidateTypeSet::iterator
6371 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6372 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6373 Enum != EnumEnd; ++Enum) {
6374 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6375 continue;
6376
6377 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6378 CandidateSet);
6379 }
6380
6381 for (BuiltinCandidateTypeSet::iterator
6382 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6383 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6384 MemPtr != MemPtrEnd; ++MemPtr) {
6385 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6386 continue;
6387
6388 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6389 CandidateSet);
6390 }
6391 }
6392 }
6393
6394 // C++ [over.built]p19:
6395 //
6396 // For every pair (T, VQ), where T is any type and VQ is either
6397 // volatile or empty, there exist candidate operator functions
6398 // of the form
6399 //
6400 // T*VQ& operator=(T*VQ&, T*);
6401 //
6402 // C++ [over.built]p21:
6403 //
6404 // For every pair (T, VQ), where T is a cv-qualified or
6405 // cv-unqualified object type and VQ is either volatile or
6406 // empty, there exist candidate operator functions of the form
6407 //
6408 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6409 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6410 void addAssignmentPointerOverloads(bool isEqualOp) {
6411 /// Set of (canonical) types that we've already handled.
6412 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6413
6414 for (BuiltinCandidateTypeSet::iterator
6415 Ptr = CandidateTypes[0].pointer_begin(),
6416 PtrEnd = CandidateTypes[0].pointer_end();
6417 Ptr != PtrEnd; ++Ptr) {
6418 // If this is operator=, keep track of the builtin candidates we added.
6419 if (isEqualOp)
6420 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006421 else if (!(*Ptr)->getPointeeType()->isObjectType())
6422 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006423
6424 // non-volatile version
6425 QualType ParamTypes[2] = {
6426 S.Context.getLValueReferenceType(*Ptr),
6427 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6428 };
6429 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6430 /*IsAssigmentOperator=*/ isEqualOp);
6431
6432 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6433 VisibleTypeConversionsQuals.hasVolatile()) {
6434 // volatile version
6435 ParamTypes[0] =
6436 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6437 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6438 /*IsAssigmentOperator=*/isEqualOp);
6439 }
6440 }
6441
6442 if (isEqualOp) {
6443 for (BuiltinCandidateTypeSet::iterator
6444 Ptr = CandidateTypes[1].pointer_begin(),
6445 PtrEnd = CandidateTypes[1].pointer_end();
6446 Ptr != PtrEnd; ++Ptr) {
6447 // Make sure we don't add the same candidate twice.
6448 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6449 continue;
6450
Chandler Carruth8e543b32010-12-12 08:17:55 +00006451 QualType ParamTypes[2] = {
6452 S.Context.getLValueReferenceType(*Ptr),
6453 *Ptr,
6454 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006455
6456 // non-volatile version
6457 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6458 /*IsAssigmentOperator=*/true);
6459
6460 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6461 VisibleTypeConversionsQuals.hasVolatile()) {
6462 // volatile version
6463 ParamTypes[0] =
6464 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006465 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6466 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006467 }
6468 }
6469 }
6470 }
6471
6472 // C++ [over.built]p18:
6473 //
6474 // For every triple (L, VQ, R), where L is an arithmetic type,
6475 // VQ is either volatile or empty, and R is a promoted
6476 // arithmetic type, there exist candidate operator functions of
6477 // the form
6478 //
6479 // VQ L& operator=(VQ L&, R);
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 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006485 if (!HasArithmeticOrEnumeralCandidateType)
6486 return;
6487
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006488 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6489 for (unsigned Right = FirstPromotedArithmeticType;
6490 Right < LastPromotedArithmeticType; ++Right) {
6491 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006492 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006493
6494 // Add this built-in operator as a candidate (VQ is empty).
6495 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006496 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006497 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6498 /*IsAssigmentOperator=*/isEqualOp);
6499
6500 // Add this built-in operator as a candidate (VQ is 'volatile').
6501 if (VisibleTypeConversionsQuals.hasVolatile()) {
6502 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006503 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006504 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006505 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6506 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006507 /*IsAssigmentOperator=*/isEqualOp);
6508 }
6509 }
6510 }
6511
6512 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6513 for (BuiltinCandidateTypeSet::iterator
6514 Vec1 = CandidateTypes[0].vector_begin(),
6515 Vec1End = CandidateTypes[0].vector_end();
6516 Vec1 != Vec1End; ++Vec1) {
6517 for (BuiltinCandidateTypeSet::iterator
6518 Vec2 = CandidateTypes[1].vector_begin(),
6519 Vec2End = CandidateTypes[1].vector_end();
6520 Vec2 != Vec2End; ++Vec2) {
6521 QualType ParamTypes[2];
6522 ParamTypes[1] = *Vec2;
6523 // Add this built-in operator as a candidate (VQ is empty).
6524 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6525 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6526 /*IsAssigmentOperator=*/isEqualOp);
6527
6528 // Add this built-in operator as a candidate (VQ is 'volatile').
6529 if (VisibleTypeConversionsQuals.hasVolatile()) {
6530 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6531 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6533 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006534 /*IsAssigmentOperator=*/isEqualOp);
6535 }
6536 }
6537 }
6538 }
6539
6540 // C++ [over.built]p22:
6541 //
6542 // For every triple (L, VQ, R), where L is an integral type, VQ
6543 // is either volatile or empty, and R is a promoted integral
6544 // type, there exist candidate operator functions of the form
6545 //
6546 // VQ L& operator%=(VQ L&, R);
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 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006553 if (!HasArithmeticOrEnumeralCandidateType)
6554 return;
6555
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006556 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6557 for (unsigned Right = FirstPromotedIntegralType;
6558 Right < LastPromotedIntegralType; ++Right) {
6559 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006560 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006561
6562 // Add this built-in operator as a candidate (VQ is empty).
6563 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006564 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006565 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6566 if (VisibleTypeConversionsQuals.hasVolatile()) {
6567 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006568 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006569 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6570 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6571 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6572 CandidateSet);
6573 }
6574 }
6575 }
6576 }
6577
6578 // C++ [over.operator]p23:
6579 //
6580 // There also exist candidate operator functions of the form
6581 //
6582 // bool operator!(bool);
6583 // bool operator&&(bool, bool);
6584 // bool operator||(bool, bool);
6585 void addExclaimOverload() {
6586 QualType ParamTy = S.Context.BoolTy;
6587 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6588 /*IsAssignmentOperator=*/false,
6589 /*NumContextualBoolArguments=*/1);
6590 }
6591 void addAmpAmpOrPipePipeOverload() {
6592 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6593 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6594 /*IsAssignmentOperator=*/false,
6595 /*NumContextualBoolArguments=*/2);
6596 }
6597
6598 // C++ [over.built]p13:
6599 //
6600 // For every cv-qualified or cv-unqualified object type T there
6601 // exist candidate operator functions of the form
6602 //
6603 // T* operator+(T*, ptrdiff_t); [ABOVE]
6604 // T& operator[](T*, ptrdiff_t);
6605 // T* operator-(T*, ptrdiff_t); [ABOVE]
6606 // T* operator+(ptrdiff_t, T*); [ABOVE]
6607 // T& operator[](ptrdiff_t, T*);
6608 void addSubscriptOverloads() {
6609 for (BuiltinCandidateTypeSet::iterator
6610 Ptr = CandidateTypes[0].pointer_begin(),
6611 PtrEnd = CandidateTypes[0].pointer_end();
6612 Ptr != PtrEnd; ++Ptr) {
6613 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6614 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006615 if (!PointeeType->isObjectType())
6616 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006617
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006618 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6619
6620 // T& operator[](T*, ptrdiff_t)
6621 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6622 }
6623
6624 for (BuiltinCandidateTypeSet::iterator
6625 Ptr = CandidateTypes[1].pointer_begin(),
6626 PtrEnd = CandidateTypes[1].pointer_end();
6627 Ptr != PtrEnd; ++Ptr) {
6628 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6629 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006630 if (!PointeeType->isObjectType())
6631 continue;
6632
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006633 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6634
6635 // T& operator[](ptrdiff_t, T*)
6636 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6637 }
6638 }
6639
6640 // C++ [over.built]p11:
6641 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6642 // C1 is the same type as C2 or is a derived class of C2, T is an object
6643 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6644 // there exist candidate operator functions of the form
6645 //
6646 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6647 //
6648 // where CV12 is the union of CV1 and CV2.
6649 void addArrowStarOverloads() {
6650 for (BuiltinCandidateTypeSet::iterator
6651 Ptr = CandidateTypes[0].pointer_begin(),
6652 PtrEnd = CandidateTypes[0].pointer_end();
6653 Ptr != PtrEnd; ++Ptr) {
6654 QualType C1Ty = (*Ptr);
6655 QualType C1;
6656 QualifierCollector Q1;
6657 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6658 if (!isa<RecordType>(C1))
6659 continue;
6660 // heuristic to reduce number of builtin candidates in the set.
6661 // Add volatile/restrict version only if there are conversions to a
6662 // volatile/restrict type.
6663 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6664 continue;
6665 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6666 continue;
6667 for (BuiltinCandidateTypeSet::iterator
6668 MemPtr = CandidateTypes[1].member_pointer_begin(),
6669 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6670 MemPtr != MemPtrEnd; ++MemPtr) {
6671 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6672 QualType C2 = QualType(mptr->getClass(), 0);
6673 C2 = C2.getUnqualifiedType();
6674 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6675 break;
6676 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6677 // build CV12 T&
6678 QualType T = mptr->getPointeeType();
6679 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6680 T.isVolatileQualified())
6681 continue;
6682 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6683 T.isRestrictQualified())
6684 continue;
6685 T = Q1.apply(S.Context, T);
6686 QualType ResultTy = S.Context.getLValueReferenceType(T);
6687 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6688 }
6689 }
6690 }
6691
6692 // Note that we don't consider the first argument, since it has been
6693 // contextually converted to bool long ago. The candidates below are
6694 // therefore added as binary.
6695 //
6696 // C++ [over.built]p25:
6697 // For every type T, where T is a pointer, pointer-to-member, or scoped
6698 // enumeration type, there exist candidate operator functions of the form
6699 //
6700 // T operator?(bool, T, T);
6701 //
6702 void addConditionalOperatorOverloads() {
6703 /// Set of (canonical) types that we've already handled.
6704 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6705
6706 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6707 for (BuiltinCandidateTypeSet::iterator
6708 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6709 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6710 Ptr != PtrEnd; ++Ptr) {
6711 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6712 continue;
6713
6714 QualType ParamTypes[2] = { *Ptr, *Ptr };
6715 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6716 }
6717
6718 for (BuiltinCandidateTypeSet::iterator
6719 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6720 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6721 MemPtr != MemPtrEnd; ++MemPtr) {
6722 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6723 continue;
6724
6725 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6726 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6727 }
6728
6729 if (S.getLangOptions().CPlusPlus0x) {
6730 for (BuiltinCandidateTypeSet::iterator
6731 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6732 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6733 Enum != EnumEnd; ++Enum) {
6734 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6735 continue;
6736
6737 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6738 continue;
6739
6740 QualType ParamTypes[2] = { *Enum, *Enum };
6741 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6742 }
6743 }
6744 }
6745 }
6746};
6747
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006748} // end anonymous namespace
6749
6750/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6751/// operator overloads to the candidate set (C++ [over.built]), based
6752/// on the operator @p Op and the arguments given. For example, if the
6753/// operator is a binary '+', this routine might add "int
6754/// operator+(int, int)" to cover integer addition.
6755void
6756Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6757 SourceLocation OpLoc,
6758 Expr **Args, unsigned NumArgs,
6759 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006760 // Find all of the types that the arguments can convert to, but only
6761 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006762 // that make use of these types. Also record whether we encounter non-record
6763 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006764 Qualifiers VisibleTypeConversionsQuals;
6765 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006766 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6767 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006768
6769 bool HasNonRecordCandidateType = false;
6770 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006771 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006772 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6773 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6774 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6775 OpLoc,
6776 true,
6777 (Op == OO_Exclaim ||
6778 Op == OO_AmpAmp ||
6779 Op == OO_PipePipe),
6780 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006781 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6782 CandidateTypes[ArgIdx].hasNonRecordTypes();
6783 HasArithmeticOrEnumeralCandidateType =
6784 HasArithmeticOrEnumeralCandidateType ||
6785 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006786 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006787
Chandler Carruth00a38332010-12-13 01:44:01 +00006788 // Exit early when no non-record types have been added to the candidate set
6789 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006790 //
6791 // We can't exit early for !, ||, or &&, since there we have always have
6792 // 'bool' overloads.
6793 if (!HasNonRecordCandidateType &&
6794 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006795 return;
6796
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006797 // Setup an object to manage the common state for building overloads.
6798 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6799 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006800 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006801 CandidateTypes, CandidateSet);
6802
6803 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006804 switch (Op) {
6805 case OO_None:
6806 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006807 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006808
Chandler Carruth5184de02010-12-12 08:51:33 +00006809 case OO_New:
6810 case OO_Delete:
6811 case OO_Array_New:
6812 case OO_Array_Delete:
6813 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006814 llvm_unreachable(
6815 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006816
6817 case OO_Comma:
6818 case OO_Arrow:
6819 // C++ [over.match.oper]p3:
6820 // -- For the operator ',', the unary operator '&', or the
6821 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006822 break;
6823
6824 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006825 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006826 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006827 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006828
6829 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006830 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006831 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006832 } else {
6833 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6834 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6835 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006836 break;
6837
Chandler Carruth5184de02010-12-12 08:51:33 +00006838 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006839 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006840 OpBuilder.addUnaryStarPointerOverloads();
6841 else
6842 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6843 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006844
Chandler Carruth5184de02010-12-12 08:51:33 +00006845 case OO_Slash:
6846 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006847 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006848
6849 case OO_PlusPlus:
6850 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006851 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6852 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006853 break;
6854
Douglas Gregor84605ae2009-08-24 13:43:27 +00006855 case OO_EqualEqual:
6856 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006857 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006858 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006859
Douglas Gregora11693b2008-11-12 17:17:38 +00006860 case OO_Less:
6861 case OO_Greater:
6862 case OO_LessEqual:
6863 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006864 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006865 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6866 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006867
Douglas Gregora11693b2008-11-12 17:17:38 +00006868 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006869 case OO_Caret:
6870 case OO_Pipe:
6871 case OO_LessLess:
6872 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006873 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006874 break;
6875
Chandler Carruth5184de02010-12-12 08:51:33 +00006876 case OO_Amp: // '&' is either unary or binary
6877 if (NumArgs == 1)
6878 // C++ [over.match.oper]p3:
6879 // -- For the operator ',', the unary operator '&', or the
6880 // operator '->', the built-in candidates set is empty.
6881 break;
6882
6883 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6884 break;
6885
6886 case OO_Tilde:
6887 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6888 break;
6889
Douglas Gregora11693b2008-11-12 17:17:38 +00006890 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006891 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006892 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006893
6894 case OO_PlusEqual:
6895 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006896 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006897 // Fall through.
6898
6899 case OO_StarEqual:
6900 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006901 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006902 break;
6903
6904 case OO_PercentEqual:
6905 case OO_LessLessEqual:
6906 case OO_GreaterGreaterEqual:
6907 case OO_AmpEqual:
6908 case OO_CaretEqual:
6909 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006910 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006911 break;
6912
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006913 case OO_Exclaim:
6914 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006915 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006916
Douglas Gregora11693b2008-11-12 17:17:38 +00006917 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006918 case OO_PipePipe:
6919 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006920 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006921
6922 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006923 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006924 break;
6925
6926 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006927 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006928 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006929
6930 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006931 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006932 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6933 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006934 }
6935}
6936
Douglas Gregore254f902009-02-04 00:32:51 +00006937/// \brief Add function candidates found via argument-dependent lookup
6938/// to the set of overloading candidates.
6939///
6940/// This routine performs argument-dependent name lookup based on the
6941/// given function name (which may also be an operator name) and adds
6942/// all of the overload candidates found by ADL to the overload
6943/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006944void
Douglas Gregore254f902009-02-04 00:32:51 +00006945Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006946 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006947 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006948 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006949 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006950 bool PartialOverloading,
6951 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006952 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006953
John McCall91f61fc2010-01-26 06:04:06 +00006954 // FIXME: This approach for uniquing ADL results (and removing
6955 // redundant candidates from the set) relies on pointer-equality,
6956 // which means we need to key off the canonical decl. However,
6957 // always going back to the canonical decl might not get us the
6958 // right set of default arguments. What default arguments are
6959 // we supposed to consider on ADL candidates, anyway?
6960
Douglas Gregorcabea402009-09-22 15:41:20 +00006961 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006962 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6963 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006964
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006965 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006966 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6967 CandEnd = CandidateSet.end();
6968 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006969 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006970 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006971 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006972 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006973 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006974
6975 // For each of the ADL candidates we found, add it to the overload
6976 // set.
John McCall8fe68082010-01-26 07:16:45 +00006977 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006978 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006979 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006980 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006981 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006982
John McCalla0296f72010-03-19 07:35:19 +00006983 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006984 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006985 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006986 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006987 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006988 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006989 }
Douglas Gregore254f902009-02-04 00:32:51 +00006990}
6991
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006992/// isBetterOverloadCandidate - Determines whether the first overload
6993/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006994bool
John McCall5c32be02010-08-24 20:38:10 +00006995isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006996 const OverloadCandidate &Cand1,
6997 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006998 SourceLocation Loc,
6999 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007000 // Define viable functions to be better candidates than non-viable
7001 // functions.
7002 if (!Cand2.Viable)
7003 return Cand1.Viable;
7004 else if (!Cand1.Viable)
7005 return false;
7006
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007007 // C++ [over.match.best]p1:
7008 //
7009 // -- if F is a static member function, ICS1(F) is defined such
7010 // that ICS1(F) is neither better nor worse than ICS1(G) for
7011 // any function G, and, symmetrically, ICS1(G) is neither
7012 // better nor worse than ICS1(F).
7013 unsigned StartArg = 0;
7014 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7015 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007016
Douglas Gregord3cb3562009-07-07 23:38:56 +00007017 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00007018 // A viable function F1 is defined to be a better function than another
7019 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00007020 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007021 unsigned NumArgs = Cand1.Conversions.size();
7022 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
7023 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007024 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00007025 switch (CompareImplicitConversionSequences(S,
7026 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007027 Cand2.Conversions[ArgIdx])) {
7028 case ImplicitConversionSequence::Better:
7029 // Cand1 has a better conversion sequence.
7030 HasBetterConversion = true;
7031 break;
7032
7033 case ImplicitConversionSequence::Worse:
7034 // Cand1 can't be better than Cand2.
7035 return false;
7036
7037 case ImplicitConversionSequence::Indistinguishable:
7038 // Do nothing.
7039 break;
7040 }
7041 }
7042
Mike Stump11289f42009-09-09 15:08:12 +00007043 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007044 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007045 if (HasBetterConversion)
7046 return true;
7047
Mike Stump11289f42009-09-09 15:08:12 +00007048 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007049 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007050 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007051 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7052 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007053
7054 // -- F1 and F2 are function template specializations, and the function
7055 // template for F1 is more specialized than the template for F2
7056 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007057 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007058 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007059 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007060 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007061 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7062 Cand2.Function->getPrimaryTemplate(),
7063 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007064 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007065 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007066 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007067 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007069
Douglas Gregora1f013e2008-11-07 22:36:19 +00007070 // -- the context is an initialization by user-defined conversion
7071 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7072 // from the return type of F1 to the destination type (i.e.,
7073 // the type of the entity being initialized) is a better
7074 // conversion sequence than the standard conversion sequence
7075 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007076 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007077 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007078 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00007079 switch (CompareStandardConversionSequences(S,
7080 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007081 Cand2.FinalConversion)) {
7082 case ImplicitConversionSequence::Better:
7083 // Cand1 has a better conversion sequence.
7084 return true;
7085
7086 case ImplicitConversionSequence::Worse:
7087 // Cand1 can't be better than Cand2.
7088 return false;
7089
7090 case ImplicitConversionSequence::Indistinguishable:
7091 // Do nothing
7092 break;
7093 }
7094 }
7095
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007096 return false;
7097}
7098
Mike Stump11289f42009-09-09 15:08:12 +00007099/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007100/// within an overload candidate set.
7101///
7102/// \param CandidateSet the set of candidate functions.
7103///
7104/// \param Loc the location of the function name (or operator symbol) for
7105/// which overload resolution occurs.
7106///
Mike Stump11289f42009-09-09 15:08:12 +00007107/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007108/// function, Best points to the candidate function found.
7109///
7110/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007111OverloadingResult
7112OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007113 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007114 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007115 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007116 Best = end();
7117 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7118 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007119 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007120 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007121 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007122 }
7123
7124 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007125 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007126 return OR_No_Viable_Function;
7127
7128 // Make sure that this function is better than every other viable
7129 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007130 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007131 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007132 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007133 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007134 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007135 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007136 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007137 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007138 }
Mike Stump11289f42009-09-09 15:08:12 +00007139
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007140 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007141 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007142 (Best->Function->isDeleted() ||
7143 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007144 return OR_Deleted;
7145
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007146 return OR_Success;
7147}
7148
John McCall53262c92010-01-12 02:15:36 +00007149namespace {
7150
7151enum OverloadCandidateKind {
7152 oc_function,
7153 oc_method,
7154 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007155 oc_function_template,
7156 oc_method_template,
7157 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007158 oc_implicit_default_constructor,
7159 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007160 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007161 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007162 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007163 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007164};
7165
John McCalle1ac8d12010-01-13 00:25:19 +00007166OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7167 FunctionDecl *Fn,
7168 std::string &Description) {
7169 bool isTemplate = false;
7170
7171 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7172 isTemplate = true;
7173 Description = S.getTemplateArgumentBindingsText(
7174 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7175 }
John McCallfd0b2f82010-01-06 09:43:14 +00007176
7177 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007178 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007179 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007180
Sebastian Redl08905022011-02-05 19:23:19 +00007181 if (Ctor->getInheritedConstructor())
7182 return oc_implicit_inherited_constructor;
7183
Alexis Hunt119c10e2011-05-25 23:16:36 +00007184 if (Ctor->isDefaultConstructor())
7185 return oc_implicit_default_constructor;
7186
7187 if (Ctor->isMoveConstructor())
7188 return oc_implicit_move_constructor;
7189
7190 assert(Ctor->isCopyConstructor() &&
7191 "unexpected sort of implicit constructor");
7192 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007193 }
7194
7195 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7196 // This actually gets spelled 'candidate function' for now, but
7197 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007198 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007199 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007200
Alexis Hunt119c10e2011-05-25 23:16:36 +00007201 if (Meth->isMoveAssignmentOperator())
7202 return oc_implicit_move_assignment;
7203
Douglas Gregorec3bec02010-09-27 22:37:28 +00007204 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007205 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007206 return oc_implicit_copy_assignment;
7207 }
7208
John McCalle1ac8d12010-01-13 00:25:19 +00007209 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007210}
7211
Sebastian Redl08905022011-02-05 19:23:19 +00007212void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7213 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7214 if (!Ctor) return;
7215
7216 Ctor = Ctor->getInheritedConstructor();
7217 if (!Ctor) return;
7218
7219 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7220}
7221
John McCall53262c92010-01-12 02:15:36 +00007222} // end anonymous namespace
7223
7224// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007225void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007226 std::string FnDesc;
7227 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007228 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7229 << (unsigned) K << FnDesc;
7230 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7231 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007232 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007233}
7234
Douglas Gregorb491ed32011-02-19 21:32:49 +00007235//Notes the location of all overload candidates designated through
7236// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007237void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007238 assert(OverloadedExpr->getType() == Context.OverloadTy);
7239
7240 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7241 OverloadExpr *OvlExpr = Ovl.Expression;
7242
7243 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7244 IEnd = OvlExpr->decls_end();
7245 I != IEnd; ++I) {
7246 if (FunctionTemplateDecl *FunTmpl =
7247 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007248 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007249 } else if (FunctionDecl *Fun
7250 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007251 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007252 }
7253 }
7254}
7255
John McCall0d1da222010-01-12 00:44:57 +00007256/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7257/// "lead" diagnostic; it will be given two arguments, the source and
7258/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007259void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7260 Sema &S,
7261 SourceLocation CaretLoc,
7262 const PartialDiagnostic &PDiag) const {
7263 S.Diag(CaretLoc, PDiag)
7264 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007265 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007266 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7267 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007268 }
John McCall12f97bc2010-01-08 04:41:39 +00007269}
7270
John McCall0d1da222010-01-12 00:44:57 +00007271namespace {
7272
John McCall6a61b522010-01-13 09:16:55 +00007273void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7274 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7275 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007276 assert(Cand->Function && "for now, candidate must be a function");
7277 FunctionDecl *Fn = Cand->Function;
7278
7279 // There's a conversion slot for the object argument if this is a
7280 // non-constructor method. Note that 'I' corresponds the
7281 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007282 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007283 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007284 if (I == 0)
7285 isObjectArgument = true;
7286 else
7287 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007288 }
7289
John McCalle1ac8d12010-01-13 00:25:19 +00007290 std::string FnDesc;
7291 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7292
John McCall6a61b522010-01-13 09:16:55 +00007293 Expr *FromExpr = Conv.Bad.FromExpr;
7294 QualType FromTy = Conv.Bad.getFromType();
7295 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007296
John McCallfb7ad0f2010-02-02 02:42:52 +00007297 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007298 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007299 Expr *E = FromExpr->IgnoreParens();
7300 if (isa<UnaryOperator>(E))
7301 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007302 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007303
7304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7305 << (unsigned) FnKind << FnDesc
7306 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7307 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007308 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007309 return;
7310 }
7311
John McCall6d174642010-01-23 08:10:49 +00007312 // Do some hand-waving analysis to see if the non-viability is due
7313 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007314 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7315 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7316 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7317 CToTy = RT->getPointeeType();
7318 else {
7319 // TODO: detect and diagnose the full richness of const mismatches.
7320 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7321 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7322 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7323 }
7324
7325 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7326 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7327 // It is dumb that we have to do this here.
7328 while (isa<ArrayType>(CFromTy))
7329 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7330 while (isa<ArrayType>(CToTy))
7331 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7332
7333 Qualifiers FromQs = CFromTy.getQualifiers();
7334 Qualifiers ToQs = CToTy.getQualifiers();
7335
7336 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7338 << (unsigned) FnKind << FnDesc
7339 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7340 << FromTy
7341 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7342 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007343 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007344 return;
7345 }
7346
John McCall31168b02011-06-15 23:02:42 +00007347 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007348 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007349 << (unsigned) FnKind << FnDesc
7350 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7351 << FromTy
7352 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7353 << (unsigned) isObjectArgument << I+1;
7354 MaybeEmitInheritedConstructorNote(S, Fn);
7355 return;
7356 }
7357
Douglas Gregoraec25842011-04-26 23:16:46 +00007358 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7359 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7360 << (unsigned) FnKind << FnDesc
7361 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7362 << FromTy
7363 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7364 << (unsigned) isObjectArgument << I+1;
7365 MaybeEmitInheritedConstructorNote(S, Fn);
7366 return;
7367 }
7368
John McCall47000992010-01-14 03:28:57 +00007369 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7370 assert(CVR && "unexpected qualifiers mismatch");
7371
7372 if (isObjectArgument) {
7373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7374 << (unsigned) FnKind << FnDesc
7375 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7376 << FromTy << (CVR - 1);
7377 } else {
7378 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7379 << (unsigned) FnKind << FnDesc
7380 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7381 << FromTy << (CVR - 1) << I+1;
7382 }
Sebastian Redl08905022011-02-05 19:23:19 +00007383 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007384 return;
7385 }
7386
Sebastian Redla72462c2011-09-24 17:48:32 +00007387 // Special diagnostic for failure to convert an initializer list, since
7388 // telling the user that it has type void is not useful.
7389 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7390 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7391 << (unsigned) FnKind << FnDesc
7392 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7393 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7394 MaybeEmitInheritedConstructorNote(S, Fn);
7395 return;
7396 }
7397
John McCall6d174642010-01-23 08:10:49 +00007398 // Diagnose references or pointers to incomplete types differently,
7399 // since it's far from impossible that the incompleteness triggered
7400 // the failure.
7401 QualType TempFromTy = FromTy.getNonReferenceType();
7402 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7403 TempFromTy = PTy->getPointeeType();
7404 if (TempFromTy->isIncompleteType()) {
7405 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7406 << (unsigned) FnKind << FnDesc
7407 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7408 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007409 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007410 return;
7411 }
7412
Douglas Gregor56f2e342010-06-30 23:01:39 +00007413 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007414 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007415 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7416 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7417 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7418 FromPtrTy->getPointeeType()) &&
7419 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7420 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007421 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007422 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007423 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007424 }
7425 } else if (const ObjCObjectPointerType *FromPtrTy
7426 = FromTy->getAs<ObjCObjectPointerType>()) {
7427 if (const ObjCObjectPointerType *ToPtrTy
7428 = ToTy->getAs<ObjCObjectPointerType>())
7429 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7430 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7431 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7432 FromPtrTy->getPointeeType()) &&
7433 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007434 BaseToDerivedConversion = 2;
7435 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7436 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7437 !FromTy->isIncompleteType() &&
7438 !ToRefTy->getPointeeType()->isIncompleteType() &&
7439 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7440 BaseToDerivedConversion = 3;
7441 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007442
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007443 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007444 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007445 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007446 << (unsigned) FnKind << FnDesc
7447 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007448 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007449 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007450 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007451 return;
7452 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007454 if (isa<ObjCObjectPointerType>(CFromTy) &&
7455 isa<PointerType>(CToTy)) {
7456 Qualifiers FromQs = CFromTy.getQualifiers();
7457 Qualifiers ToQs = CToTy.getQualifiers();
7458 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7459 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7460 << (unsigned) FnKind << FnDesc
7461 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7462 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7463 MaybeEmitInheritedConstructorNote(S, Fn);
7464 return;
7465 }
7466 }
7467
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007468 // Emit the generic diagnostic and, optionally, add the hints to it.
7469 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7470 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007471 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007472 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7473 << (unsigned) (Cand->Fix.Kind);
7474
7475 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007476 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007477 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7478 HI != HE; ++HI)
7479 FDiag << *HI;
7480 S.Diag(Fn->getLocation(), FDiag);
7481
Sebastian Redl08905022011-02-05 19:23:19 +00007482 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007483}
7484
7485void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7486 unsigned NumFormalArgs) {
7487 // TODO: treat calls to a missing default constructor as a special case
7488
7489 FunctionDecl *Fn = Cand->Function;
7490 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7491
7492 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007493
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007494 // With invalid overloaded operators, it's possible that we think we
7495 // have an arity mismatch when it fact it looks like we have the
7496 // right number of arguments, because only overloaded operators have
7497 // the weird behavior of overloading member and non-member functions.
7498 // Just don't report anything.
7499 if (Fn->isInvalidDecl() &&
7500 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7501 return;
7502
John McCall6a61b522010-01-13 09:16:55 +00007503 // at least / at most / exactly
7504 unsigned mode, modeCount;
7505 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007506 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7507 (Cand->FailureKind == ovl_fail_bad_deduction &&
7508 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007509 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007510 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007511 mode = 0; // "at least"
7512 else
7513 mode = 2; // "exactly"
7514 modeCount = MinParams;
7515 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007516 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7517 (Cand->FailureKind == ovl_fail_bad_deduction &&
7518 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007519 if (MinParams != FnTy->getNumArgs())
7520 mode = 1; // "at most"
7521 else
7522 mode = 2; // "exactly"
7523 modeCount = FnTy->getNumArgs();
7524 }
7525
7526 std::string Description;
7527 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7528
7529 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007530 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007531 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007532 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007533}
7534
John McCall8b9ed552010-02-01 18:53:26 +00007535/// Diagnose a failed template-argument deduction.
7536void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7537 Expr **Args, unsigned NumArgs) {
7538 FunctionDecl *Fn = Cand->Function; // pattern
7539
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007540 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007541 NamedDecl *ParamD;
7542 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7543 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7544 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007545 switch (Cand->DeductionFailure.Result) {
7546 case Sema::TDK_Success:
7547 llvm_unreachable("TDK_success while diagnosing bad deduction");
7548
7549 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007550 assert(ParamD && "no parameter found for incomplete deduction result");
7551 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7552 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007553 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007554 return;
7555 }
7556
John McCall42d7d192010-08-05 09:05:08 +00007557 case Sema::TDK_Underqualified: {
7558 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7559 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7560
7561 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7562
7563 // Param will have been canonicalized, but it should just be a
7564 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007565 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007566 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007567 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007568 assert(S.Context.hasSameType(Param, NonCanonParam));
7569
7570 // Arg has also been canonicalized, but there's nothing we can do
7571 // about that. It also doesn't matter as much, because it won't
7572 // have any template parameters in it (because deduction isn't
7573 // done on dependent types).
7574 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7575
7576 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7577 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007578 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007579 return;
7580 }
7581
7582 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007583 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007584 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007585 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007586 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007587 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007588 which = 1;
7589 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007590 which = 2;
7591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007592
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007593 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007594 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007595 << *Cand->DeductionFailure.getFirstArg()
7596 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007597 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007598 return;
7599 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007600
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007601 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007602 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007603 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007604 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007605 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7606 << ParamD->getDeclName();
7607 else {
7608 int index = 0;
7609 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7610 index = TTP->getIndex();
7611 else if (NonTypeTemplateParmDecl *NTTP
7612 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7613 index = NTTP->getIndex();
7614 else
7615 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007616 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007617 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7618 << (index + 1);
7619 }
Sebastian Redl08905022011-02-05 19:23:19 +00007620 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007621 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007622
Douglas Gregor02eb4832010-05-08 18:13:28 +00007623 case Sema::TDK_TooManyArguments:
7624 case Sema::TDK_TooFewArguments:
7625 DiagnoseArityMismatch(S, Cand, NumArgs);
7626 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007627
7628 case Sema::TDK_InstantiationDepth:
7629 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007630 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007631 return;
7632
7633 case Sema::TDK_SubstitutionFailure: {
7634 std::string ArgString;
7635 if (TemplateArgumentList *Args
7636 = Cand->DeductionFailure.getTemplateArgumentList())
7637 ArgString = S.getTemplateArgumentBindingsText(
7638 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7639 *Args);
7640 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7641 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007642 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007643 return;
7644 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007645
John McCall8b9ed552010-02-01 18:53:26 +00007646 // TODO: diagnose these individually, then kill off
7647 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007648 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007649 case Sema::TDK_FailedOverloadResolution:
7650 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007651 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007652 return;
7653 }
7654}
7655
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007656/// CUDA: diagnose an invalid call across targets.
7657void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7658 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7659 FunctionDecl *Callee = Cand->Function;
7660
7661 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7662 CalleeTarget = S.IdentifyCUDATarget(Callee);
7663
7664 std::string FnDesc;
7665 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7666
7667 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7668 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7669}
7670
John McCall8b9ed552010-02-01 18:53:26 +00007671/// Generates a 'note' diagnostic for an overload candidate. We've
7672/// already generated a primary error at the call site.
7673///
7674/// It really does need to be a single diagnostic with its caret
7675/// pointed at the candidate declaration. Yes, this creates some
7676/// major challenges of technical writing. Yes, this makes pointing
7677/// out problems with specific arguments quite awkward. It's still
7678/// better than generating twenty screens of text for every failed
7679/// overload.
7680///
7681/// It would be great to be able to express per-candidate problems
7682/// more richly for those diagnostic clients that cared, but we'd
7683/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007684void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7685 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007686 FunctionDecl *Fn = Cand->Function;
7687
John McCall12f97bc2010-01-08 04:41:39 +00007688 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007689 if (Cand->Viable && (Fn->isDeleted() ||
7690 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007691 std::string FnDesc;
7692 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007693
7694 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007695 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007696 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007697 return;
John McCall12f97bc2010-01-08 04:41:39 +00007698 }
7699
John McCalle1ac8d12010-01-13 00:25:19 +00007700 // We don't really have anything else to say about viable candidates.
7701 if (Cand->Viable) {
7702 S.NoteOverloadCandidate(Fn);
7703 return;
7704 }
John McCall0d1da222010-01-12 00:44:57 +00007705
John McCall6a61b522010-01-13 09:16:55 +00007706 switch (Cand->FailureKind) {
7707 case ovl_fail_too_many_arguments:
7708 case ovl_fail_too_few_arguments:
7709 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007710
John McCall6a61b522010-01-13 09:16:55 +00007711 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007712 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7713
John McCallfe796dd2010-01-23 05:17:32 +00007714 case ovl_fail_trivial_conversion:
7715 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007716 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007717 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007718
John McCall65eb8792010-02-25 01:37:24 +00007719 case ovl_fail_bad_conversion: {
7720 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7721 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007722 if (Cand->Conversions[I].isBad())
7723 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007724
John McCall6a61b522010-01-13 09:16:55 +00007725 // FIXME: this currently happens when we're called from SemaInit
7726 // when user-conversion overload fails. Figure out how to handle
7727 // those conditions and diagnose them well.
7728 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007729 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007730
7731 case ovl_fail_bad_target:
7732 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007733 }
John McCalld3224162010-01-08 00:58:21 +00007734}
7735
7736void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7737 // Desugar the type of the surrogate down to a function type,
7738 // retaining as many typedefs as possible while still showing
7739 // the function type (and, therefore, its parameter types).
7740 QualType FnType = Cand->Surrogate->getConversionType();
7741 bool isLValueReference = false;
7742 bool isRValueReference = false;
7743 bool isPointer = false;
7744 if (const LValueReferenceType *FnTypeRef =
7745 FnType->getAs<LValueReferenceType>()) {
7746 FnType = FnTypeRef->getPointeeType();
7747 isLValueReference = true;
7748 } else if (const RValueReferenceType *FnTypeRef =
7749 FnType->getAs<RValueReferenceType>()) {
7750 FnType = FnTypeRef->getPointeeType();
7751 isRValueReference = true;
7752 }
7753 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7754 FnType = FnTypePtr->getPointeeType();
7755 isPointer = true;
7756 }
7757 // Desugar down to a function type.
7758 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7759 // Reconstruct the pointer/reference as appropriate.
7760 if (isPointer) FnType = S.Context.getPointerType(FnType);
7761 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7762 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7763
7764 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7765 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007766 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007767}
7768
7769void NoteBuiltinOperatorCandidate(Sema &S,
7770 const char *Opc,
7771 SourceLocation OpLoc,
7772 OverloadCandidate *Cand) {
7773 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7774 std::string TypeStr("operator");
7775 TypeStr += Opc;
7776 TypeStr += "(";
7777 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7778 if (Cand->Conversions.size() == 1) {
7779 TypeStr += ")";
7780 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7781 } else {
7782 TypeStr += ", ";
7783 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7784 TypeStr += ")";
7785 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7786 }
7787}
7788
7789void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7790 OverloadCandidate *Cand) {
7791 unsigned NoOperands = Cand->Conversions.size();
7792 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7793 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007794 if (ICS.isBad()) break; // all meaningless after first invalid
7795 if (!ICS.isAmbiguous()) continue;
7796
John McCall5c32be02010-08-24 20:38:10 +00007797 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007798 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007799 }
7800}
7801
John McCall3712d9e2010-01-15 23:32:50 +00007802SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7803 if (Cand->Function)
7804 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007805 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007806 return Cand->Surrogate->getLocation();
7807 return SourceLocation();
7808}
7809
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007810static unsigned
7811RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007812 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007813 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007814 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007815
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007816 case Sema::TDK_Incomplete:
7817 return 1;
7818
7819 case Sema::TDK_Underqualified:
7820 case Sema::TDK_Inconsistent:
7821 return 2;
7822
7823 case Sema::TDK_SubstitutionFailure:
7824 case Sema::TDK_NonDeducedMismatch:
7825 return 3;
7826
7827 case Sema::TDK_InstantiationDepth:
7828 case Sema::TDK_FailedOverloadResolution:
7829 return 4;
7830
7831 case Sema::TDK_InvalidExplicitArguments:
7832 return 5;
7833
7834 case Sema::TDK_TooManyArguments:
7835 case Sema::TDK_TooFewArguments:
7836 return 6;
7837 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007838 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007839}
7840
John McCallad2587a2010-01-12 00:48:53 +00007841struct CompareOverloadCandidatesForDisplay {
7842 Sema &S;
7843 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007844
7845 bool operator()(const OverloadCandidate *L,
7846 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007847 // Fast-path this check.
7848 if (L == R) return false;
7849
John McCall12f97bc2010-01-08 04:41:39 +00007850 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007851 if (L->Viable) {
7852 if (!R->Viable) return true;
7853
7854 // TODO: introduce a tri-valued comparison for overload
7855 // candidates. Would be more worthwhile if we had a sort
7856 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007857 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7858 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007859 } else if (R->Viable)
7860 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007861
John McCall3712d9e2010-01-15 23:32:50 +00007862 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007863
John McCall3712d9e2010-01-15 23:32:50 +00007864 // Criteria by which we can sort non-viable candidates:
7865 if (!L->Viable) {
7866 // 1. Arity mismatches come after other candidates.
7867 if (L->FailureKind == ovl_fail_too_many_arguments ||
7868 L->FailureKind == ovl_fail_too_few_arguments)
7869 return false;
7870 if (R->FailureKind == ovl_fail_too_many_arguments ||
7871 R->FailureKind == ovl_fail_too_few_arguments)
7872 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007873
John McCallfe796dd2010-01-23 05:17:32 +00007874 // 2. Bad conversions come first and are ordered by the number
7875 // of bad conversions and quality of good conversions.
7876 if (L->FailureKind == ovl_fail_bad_conversion) {
7877 if (R->FailureKind != ovl_fail_bad_conversion)
7878 return true;
7879
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007880 // The conversion that can be fixed with a smaller number of changes,
7881 // comes first.
7882 unsigned numLFixes = L->Fix.NumConversionsFixed;
7883 unsigned numRFixes = R->Fix.NumConversionsFixed;
7884 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7885 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007886 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007887 if (numLFixes < numRFixes)
7888 return true;
7889 else
7890 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007891 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007892
John McCallfe796dd2010-01-23 05:17:32 +00007893 // If there's any ordering between the defined conversions...
7894 // FIXME: this might not be transitive.
7895 assert(L->Conversions.size() == R->Conversions.size());
7896
7897 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007898 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7899 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007900 switch (CompareImplicitConversionSequences(S,
7901 L->Conversions[I],
7902 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007903 case ImplicitConversionSequence::Better:
7904 leftBetter++;
7905 break;
7906
7907 case ImplicitConversionSequence::Worse:
7908 leftBetter--;
7909 break;
7910
7911 case ImplicitConversionSequence::Indistinguishable:
7912 break;
7913 }
7914 }
7915 if (leftBetter > 0) return true;
7916 if (leftBetter < 0) return false;
7917
7918 } else if (R->FailureKind == ovl_fail_bad_conversion)
7919 return false;
7920
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007921 if (L->FailureKind == ovl_fail_bad_deduction) {
7922 if (R->FailureKind != ovl_fail_bad_deduction)
7923 return true;
7924
7925 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7926 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007927 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007928 } else if (R->FailureKind == ovl_fail_bad_deduction)
7929 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007930
John McCall3712d9e2010-01-15 23:32:50 +00007931 // TODO: others?
7932 }
7933
7934 // Sort everything else by location.
7935 SourceLocation LLoc = GetLocationForCandidate(L);
7936 SourceLocation RLoc = GetLocationForCandidate(R);
7937
7938 // Put candidates without locations (e.g. builtins) at the end.
7939 if (LLoc.isInvalid()) return false;
7940 if (RLoc.isInvalid()) return true;
7941
7942 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007943 }
7944};
7945
John McCallfe796dd2010-01-23 05:17:32 +00007946/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007947/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007948void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7949 Expr **Args, unsigned NumArgs) {
7950 assert(!Cand->Viable);
7951
7952 // Don't do anything on failures other than bad conversion.
7953 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7954
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007955 // We only want the FixIts if all the arguments can be corrected.
7956 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007957 // Use a implicit copy initialization to check conversion fixes.
7958 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007959
John McCallfe796dd2010-01-23 05:17:32 +00007960 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007961 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007962 unsigned ConvCount = Cand->Conversions.size();
7963 while (true) {
7964 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7965 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007966 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007967 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007968 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007969 }
John McCallfe796dd2010-01-23 05:17:32 +00007970 }
7971
7972 if (ConvIdx == ConvCount)
7973 return;
7974
John McCall65eb8792010-02-25 01:37:24 +00007975 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7976 "remaining conversion is initialized?");
7977
Douglas Gregoradc7a702010-04-16 17:45:54 +00007978 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007979 // operation somehow.
7980 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007981
7982 const FunctionProtoType* Proto;
7983 unsigned ArgIdx = ConvIdx;
7984
7985 if (Cand->IsSurrogate) {
7986 QualType ConvType
7987 = Cand->Surrogate->getConversionType().getNonReferenceType();
7988 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7989 ConvType = ConvPtrType->getPointeeType();
7990 Proto = ConvType->getAs<FunctionProtoType>();
7991 ArgIdx--;
7992 } else if (Cand->Function) {
7993 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7994 if (isa<CXXMethodDecl>(Cand->Function) &&
7995 !isa<CXXConstructorDecl>(Cand->Function))
7996 ArgIdx--;
7997 } else {
7998 // Builtin binary operator with a bad first conversion.
7999 assert(ConvCount <= 3);
8000 for (; ConvIdx != ConvCount; ++ConvIdx)
8001 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008002 = TryCopyInitialization(S, Args[ConvIdx],
8003 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008004 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008005 /*InOverloadResolution*/ true,
8006 /*AllowObjCWritebackConversion=*/
8007 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00008008 return;
8009 }
8010
8011 // Fill in the rest of the conversions.
8012 unsigned NumArgsInProto = Proto->getNumArgs();
8013 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008014 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00008015 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00008016 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008017 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00008018 /*InOverloadResolution=*/true,
8019 /*AllowObjCWritebackConversion=*/
8020 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008021 // Store the FixIt in the candidate if it exists.
8022 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00008023 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008024 }
John McCallfe796dd2010-01-23 05:17:32 +00008025 else
8026 Cand->Conversions[ConvIdx].setEllipsis();
8027 }
8028}
8029
John McCalld3224162010-01-08 00:58:21 +00008030} // end anonymous namespace
8031
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008032/// PrintOverloadCandidates - When overload resolution fails, prints
8033/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00008034/// set.
John McCall5c32be02010-08-24 20:38:10 +00008035void OverloadCandidateSet::NoteCandidates(Sema &S,
8036 OverloadCandidateDisplayKind OCD,
8037 Expr **Args, unsigned NumArgs,
8038 const char *Opc,
8039 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008040 // Sort the candidates by viability and position. Sorting directly would
8041 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008042 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008043 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8044 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008045 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008046 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008047 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008048 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008049 if (Cand->Function || Cand->IsSurrogate)
8050 Cands.push_back(Cand);
8051 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8052 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008053 }
8054 }
8055
John McCallad2587a2010-01-12 00:48:53 +00008056 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008057 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008058
John McCall0d1da222010-01-12 00:44:57 +00008059 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008060
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008061 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008062 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8063 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008064 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008065 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8066 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008067
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008068 // Set an arbitrary limit on the number of candidate functions we'll spam
8069 // the user with. FIXME: This limit should depend on details of the
8070 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008071 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008072 break;
8073 }
8074 ++CandsShown;
8075
John McCalld3224162010-01-08 00:58:21 +00008076 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008077 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008078 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008079 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008080 else {
8081 assert(Cand->Viable &&
8082 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008083 // Generally we only see ambiguities including viable builtin
8084 // operators if overload resolution got screwed up by an
8085 // ambiguous user-defined conversion.
8086 //
8087 // FIXME: It's quite possible for different conversions to see
8088 // different ambiguities, though.
8089 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008090 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008091 ReportedAmbiguousConversions = true;
8092 }
John McCalld3224162010-01-08 00:58:21 +00008093
John McCall0d1da222010-01-12 00:44:57 +00008094 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008095 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008096 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008097 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008098
8099 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008100 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008101}
8102
Douglas Gregorb491ed32011-02-19 21:32:49 +00008103// [PossiblyAFunctionType] --> [Return]
8104// NonFunctionType --> NonFunctionType
8105// R (A) --> R(A)
8106// R (*)(A) --> R (A)
8107// R (&)(A) --> R (A)
8108// R (S::*)(A) --> R (A)
8109QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8110 QualType Ret = PossiblyAFunctionType;
8111 if (const PointerType *ToTypePtr =
8112 PossiblyAFunctionType->getAs<PointerType>())
8113 Ret = ToTypePtr->getPointeeType();
8114 else if (const ReferenceType *ToTypeRef =
8115 PossiblyAFunctionType->getAs<ReferenceType>())
8116 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008117 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008118 PossiblyAFunctionType->getAs<MemberPointerType>())
8119 Ret = MemTypePtr->getPointeeType();
8120 Ret =
8121 Context.getCanonicalType(Ret).getUnqualifiedType();
8122 return Ret;
8123}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008124
Douglas Gregorb491ed32011-02-19 21:32:49 +00008125// A helper class to help with address of function resolution
8126// - allows us to avoid passing around all those ugly parameters
8127class AddressOfFunctionResolver
8128{
8129 Sema& S;
8130 Expr* SourceExpr;
8131 const QualType& TargetType;
8132 QualType TargetFunctionType; // Extracted function type from target type
8133
8134 bool Complain;
8135 //DeclAccessPair& ResultFunctionAccessPair;
8136 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008137
Douglas Gregorb491ed32011-02-19 21:32:49 +00008138 bool TargetTypeIsNonStaticMemberFunction;
8139 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008140
Douglas Gregorb491ed32011-02-19 21:32:49 +00008141 OverloadExpr::FindResult OvlExprInfo;
8142 OverloadExpr *OvlExpr;
8143 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008144 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008145
Douglas Gregorb491ed32011-02-19 21:32:49 +00008146public:
8147 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8148 const QualType& TargetType, bool Complain)
8149 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8150 Complain(Complain), Context(S.getASTContext()),
8151 TargetTypeIsNonStaticMemberFunction(
8152 !!TargetType->getAs<MemberPointerType>()),
8153 FoundNonTemplateFunction(false),
8154 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8155 OvlExpr(OvlExprInfo.Expression)
8156 {
8157 ExtractUnqualifiedFunctionTypeFromTargetType();
8158
8159 if (!TargetFunctionType->isFunctionType()) {
8160 if (OvlExpr->hasExplicitTemplateArgs()) {
8161 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008162 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008163 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008164
8165 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8166 if (!Method->isStatic()) {
8167 // If the target type is a non-function type and the function
8168 // found is a non-static member function, pretend as if that was
8169 // the target, it's the only possible type to end up with.
8170 TargetTypeIsNonStaticMemberFunction = true;
8171
8172 // And skip adding the function if its not in the proper form.
8173 // We'll diagnose this due to an empty set of functions.
8174 if (!OvlExprInfo.HasFormOfMemberPointer)
8175 return;
8176 }
8177 }
8178
Douglas Gregorb491ed32011-02-19 21:32:49 +00008179 Matches.push_back(std::make_pair(dap,Fn));
8180 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008181 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008182 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008183 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008184
8185 if (OvlExpr->hasExplicitTemplateArgs())
8186 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008187
Douglas Gregorb491ed32011-02-19 21:32:49 +00008188 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8189 // C++ [over.over]p4:
8190 // If more than one function is selected, [...]
8191 if (Matches.size() > 1) {
8192 if (FoundNonTemplateFunction)
8193 EliminateAllTemplateMatches();
8194 else
8195 EliminateAllExceptMostSpecializedTemplate();
8196 }
8197 }
8198 }
8199
8200private:
8201 bool isTargetTypeAFunction() const {
8202 return TargetFunctionType->isFunctionType();
8203 }
8204
8205 // [ToType] [Return]
8206
8207 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8208 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8209 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8210 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8211 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8212 }
8213
8214 // return true if any matching specializations were found
8215 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8216 const DeclAccessPair& CurAccessFunPair) {
8217 if (CXXMethodDecl *Method
8218 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8219 // Skip non-static function templates when converting to pointer, and
8220 // static when converting to member pointer.
8221 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8222 return false;
8223 }
8224 else if (TargetTypeIsNonStaticMemberFunction)
8225 return false;
8226
8227 // C++ [over.over]p2:
8228 // If the name is a function template, template argument deduction is
8229 // done (14.8.2.2), and if the argument deduction succeeds, the
8230 // resulting template argument list is used to generate a single
8231 // function template specialization, which is added to the set of
8232 // overloaded functions considered.
8233 FunctionDecl *Specialization = 0;
8234 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8235 if (Sema::TemplateDeductionResult Result
8236 = S.DeduceTemplateArguments(FunctionTemplate,
8237 &OvlExplicitTemplateArgs,
8238 TargetFunctionType, Specialization,
8239 Info)) {
8240 // FIXME: make a note of the failed deduction for diagnostics.
8241 (void)Result;
8242 return false;
8243 }
8244
8245 // Template argument deduction ensures that we have an exact match.
8246 // This function template specicalization works.
8247 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8248 assert(TargetFunctionType
8249 == Context.getCanonicalType(Specialization->getType()));
8250 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8251 return true;
8252 }
8253
8254 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8255 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008256 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008257 // Skip non-static functions when converting to pointer, and static
8258 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008259 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8260 return false;
8261 }
8262 else if (TargetTypeIsNonStaticMemberFunction)
8263 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008264
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008265 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008266 if (S.getLangOptions().CUDA)
8267 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8268 if (S.CheckCUDATarget(Caller, FunDecl))
8269 return false;
8270
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008271 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008272 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8273 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008274 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8275 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008276 Matches.push_back(std::make_pair(CurAccessFunPair,
8277 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008278 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008279 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008280 }
Mike Stump11289f42009-09-09 15:08:12 +00008281 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008282
8283 return false;
8284 }
8285
8286 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8287 bool Ret = false;
8288
8289 // If the overload expression doesn't have the form of a pointer to
8290 // member, don't try to convert it to a pointer-to-member type.
8291 if (IsInvalidFormOfPointerToMemberFunction())
8292 return false;
8293
8294 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8295 E = OvlExpr->decls_end();
8296 I != E; ++I) {
8297 // Look through any using declarations to find the underlying function.
8298 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8299
8300 // C++ [over.over]p3:
8301 // Non-member functions and static member functions match
8302 // targets of type "pointer-to-function" or "reference-to-function."
8303 // Nonstatic member functions match targets of
8304 // type "pointer-to-member-function."
8305 // Note that according to DR 247, the containing class does not matter.
8306 if (FunctionTemplateDecl *FunctionTemplate
8307 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8308 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8309 Ret = true;
8310 }
8311 // If we have explicit template arguments supplied, skip non-templates.
8312 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8313 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8314 Ret = true;
8315 }
8316 assert(Ret || Matches.empty());
8317 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008318 }
8319
Douglas Gregorb491ed32011-02-19 21:32:49 +00008320 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008321 // [...] and any given function template specialization F1 is
8322 // eliminated if the set contains a second function template
8323 // specialization whose function template is more specialized
8324 // than the function template of F1 according to the partial
8325 // ordering rules of 14.5.5.2.
8326
8327 // The algorithm specified above is quadratic. We instead use a
8328 // two-pass algorithm (similar to the one used to identify the
8329 // best viable function in an overload set) that identifies the
8330 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008331
8332 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8333 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8334 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008335
John McCall58cc69d2010-01-27 01:50:18 +00008336 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008337 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8338 TPOC_Other, 0, SourceExpr->getLocStart(),
8339 S.PDiag(),
8340 S.PDiag(diag::err_addr_ovl_ambiguous)
8341 << Matches[0].second->getDeclName(),
8342 S.PDiag(diag::note_ovl_candidate)
8343 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008344 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008345
Douglas Gregorb491ed32011-02-19 21:32:49 +00008346 if (Result != MatchesCopy.end()) {
8347 // Make it the first and only element
8348 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8349 Matches[0].second = cast<FunctionDecl>(*Result);
8350 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008351 }
8352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008353
Douglas Gregorb491ed32011-02-19 21:32:49 +00008354 void EliminateAllTemplateMatches() {
8355 // [...] any function template specializations in the set are
8356 // eliminated if the set also contains a non-template function, [...]
8357 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8358 if (Matches[I].second->getPrimaryTemplate() == 0)
8359 ++I;
8360 else {
8361 Matches[I] = Matches[--N];
8362 Matches.set_size(N);
8363 }
8364 }
8365 }
8366
8367public:
8368 void ComplainNoMatchesFound() const {
8369 assert(Matches.empty());
8370 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8371 << OvlExpr->getName() << TargetFunctionType
8372 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008373 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008374 }
8375
8376 bool IsInvalidFormOfPointerToMemberFunction() const {
8377 return TargetTypeIsNonStaticMemberFunction &&
8378 !OvlExprInfo.HasFormOfMemberPointer;
8379 }
8380
8381 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8382 // TODO: Should we condition this on whether any functions might
8383 // have matched, or is it more appropriate to do that in callers?
8384 // TODO: a fixit wouldn't hurt.
8385 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8386 << TargetType << OvlExpr->getSourceRange();
8387 }
8388
8389 void ComplainOfInvalidConversion() const {
8390 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8391 << OvlExpr->getName() << TargetType;
8392 }
8393
8394 void ComplainMultipleMatchesFound() const {
8395 assert(Matches.size() > 1);
8396 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8397 << OvlExpr->getName()
8398 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008399 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008400 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008401
8402 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8403
Douglas Gregorb491ed32011-02-19 21:32:49 +00008404 int getNumMatches() const { return Matches.size(); }
8405
8406 FunctionDecl* getMatchingFunctionDecl() const {
8407 if (Matches.size() != 1) return 0;
8408 return Matches[0].second;
8409 }
8410
8411 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8412 if (Matches.size() != 1) return 0;
8413 return &Matches[0].first;
8414 }
8415};
8416
8417/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8418/// an overloaded function (C++ [over.over]), where @p From is an
8419/// expression with overloaded function type and @p ToType is the type
8420/// we're trying to resolve to. For example:
8421///
8422/// @code
8423/// int f(double);
8424/// int f(int);
8425///
8426/// int (*pfd)(double) = f; // selects f(double)
8427/// @endcode
8428///
8429/// This routine returns the resulting FunctionDecl if it could be
8430/// resolved, and NULL otherwise. When @p Complain is true, this
8431/// routine will emit diagnostics if there is an error.
8432FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008433Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8434 QualType TargetType,
8435 bool Complain,
8436 DeclAccessPair &FoundResult,
8437 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008438 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008439
8440 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8441 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008442 int NumMatches = Resolver.getNumMatches();
8443 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008444 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008445 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8446 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8447 else
8448 Resolver.ComplainNoMatchesFound();
8449 }
8450 else if (NumMatches > 1 && Complain)
8451 Resolver.ComplainMultipleMatchesFound();
8452 else if (NumMatches == 1) {
8453 Fn = Resolver.getMatchingFunctionDecl();
8454 assert(Fn);
8455 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8456 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008457 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008458 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008459 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008460
8461 if (pHadMultipleCandidates)
8462 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008463 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008464}
8465
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008466/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008467/// resolve that overloaded function expression down to a single function.
8468///
8469/// This routine can only resolve template-ids that refer to a single function
8470/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008471/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008472/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008473FunctionDecl *
8474Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8475 bool Complain,
8476 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008477 // C++ [over.over]p1:
8478 // [...] [Note: any redundant set of parentheses surrounding the
8479 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008480 // C++ [over.over]p1:
8481 // [...] The overloaded function name can be preceded by the &
8482 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008483
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008484 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008485 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008486 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008487
8488 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008489 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008490
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008491 // Look through all of the overloaded functions, searching for one
8492 // whose type matches exactly.
8493 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008494 for (UnresolvedSetIterator I = ovl->decls_begin(),
8495 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008496 // C++0x [temp.arg.explicit]p3:
8497 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008498 // where deduction is not done, if a template argument list is
8499 // specified and it, along with any default template arguments,
8500 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008501 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008502 FunctionTemplateDecl *FunctionTemplate
8503 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008504
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008505 // C++ [over.over]p2:
8506 // If the name is a function template, template argument deduction is
8507 // done (14.8.2.2), and if the argument deduction succeeds, the
8508 // resulting template argument list is used to generate a single
8509 // function template specialization, which is added to the set of
8510 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008511 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008512 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008513 if (TemplateDeductionResult Result
8514 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8515 Specialization, Info)) {
8516 // FIXME: make a note of the failed deduction for diagnostics.
8517 (void)Result;
8518 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008519 }
8520
John McCall0009fcc2011-04-26 20:42:42 +00008521 assert(Specialization && "no specialization and no error?");
8522
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008523 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008524 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008525 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008526 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8527 << ovl->getName();
8528 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008529 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008530 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008531 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008532
John McCall0009fcc2011-04-26 20:42:42 +00008533 Matched = Specialization;
8534 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008536
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008537 return Matched;
8538}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008539
Douglas Gregor1beec452011-03-12 01:48:56 +00008540
8541
8542
John McCall50a2c2c2011-10-11 23:14:30 +00008543// Resolve and fix an overloaded expression that can be resolved
8544// because it identifies a single function template specialization.
8545//
Douglas Gregor1beec452011-03-12 01:48:56 +00008546// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008547//
8548// Return true if it was logically possible to so resolve the
8549// expression, regardless of whether or not it succeeded. Always
8550// returns true if 'complain' is set.
8551bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8552 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8553 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008554 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008555 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008556 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008557
John McCall50a2c2c2011-10-11 23:14:30 +00008558 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008559
John McCall0009fcc2011-04-26 20:42:42 +00008560 DeclAccessPair found;
8561 ExprResult SingleFunctionExpression;
8562 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8563 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008564 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8565 SrcExpr = ExprError();
8566 return true;
8567 }
John McCall0009fcc2011-04-26 20:42:42 +00008568
8569 // It is only correct to resolve to an instance method if we're
8570 // resolving a form that's permitted to be a pointer to member.
8571 // Otherwise we'll end up making a bound member expression, which
8572 // is illegal in all the contexts we resolve like this.
8573 if (!ovl.HasFormOfMemberPointer &&
8574 isa<CXXMethodDecl>(fn) &&
8575 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008576 if (!complain) return false;
8577
8578 Diag(ovl.Expression->getExprLoc(),
8579 diag::err_bound_member_function)
8580 << 0 << ovl.Expression->getSourceRange();
8581
8582 // TODO: I believe we only end up here if there's a mix of
8583 // static and non-static candidates (otherwise the expression
8584 // would have 'bound member' type, not 'overload' type).
8585 // Ideally we would note which candidate was chosen and why
8586 // the static candidates were rejected.
8587 SrcExpr = ExprError();
8588 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008589 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008590
John McCall0009fcc2011-04-26 20:42:42 +00008591 // Fix the expresion to refer to 'fn'.
8592 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008593 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008594
8595 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008596 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008597 SingleFunctionExpression =
8598 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008599 if (SingleFunctionExpression.isInvalid()) {
8600 SrcExpr = ExprError();
8601 return true;
8602 }
8603 }
John McCall0009fcc2011-04-26 20:42:42 +00008604 }
8605
8606 if (!SingleFunctionExpression.isUsable()) {
8607 if (complain) {
8608 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8609 << ovl.Expression->getName()
8610 << DestTypeForComplaining
8611 << OpRangeForComplaining
8612 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008613 NoteAllOverloadCandidates(SrcExpr.get());
8614
8615 SrcExpr = ExprError();
8616 return true;
8617 }
8618
8619 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008620 }
8621
John McCall50a2c2c2011-10-11 23:14:30 +00008622 SrcExpr = SingleFunctionExpression;
8623 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008624}
8625
Douglas Gregorcabea402009-09-22 15:41:20 +00008626/// \brief Add a single candidate to the overload set.
8627static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008628 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008629 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008630 Expr **Args, unsigned NumArgs,
8631 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008632 bool PartialOverloading,
8633 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008634 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008635 if (isa<UsingShadowDecl>(Callee))
8636 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8637
Douglas Gregorcabea402009-09-22 15:41:20 +00008638 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008639 if (ExplicitTemplateArgs) {
8640 assert(!KnownValid && "Explicit template arguments?");
8641 return;
8642 }
John McCalla0296f72010-03-19 07:35:19 +00008643 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008644 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008645 return;
John McCalld14a8642009-11-21 08:51:07 +00008646 }
8647
8648 if (FunctionTemplateDecl *FuncTemplate
8649 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008650 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8651 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008652 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008653 return;
8654 }
8655
Richard Smith95ce4f62011-06-26 22:19:54 +00008656 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008657}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008658
Douglas Gregorcabea402009-09-22 15:41:20 +00008659/// \brief Add the overload candidates named by callee and/or found by argument
8660/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008661void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008662 Expr **Args, unsigned NumArgs,
8663 OverloadCandidateSet &CandidateSet,
8664 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008665
8666#ifndef NDEBUG
8667 // Verify that ArgumentDependentLookup is consistent with the rules
8668 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008669 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008670 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8671 // and let Y be the lookup set produced by argument dependent
8672 // lookup (defined as follows). If X contains
8673 //
8674 // -- a declaration of a class member, or
8675 //
8676 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008677 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008678 //
8679 // -- a declaration that is neither a function or a function
8680 // template
8681 //
8682 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008683
John McCall57500772009-12-16 12:17:52 +00008684 if (ULE->requiresADL()) {
8685 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8686 E = ULE->decls_end(); I != E; ++I) {
8687 assert(!(*I)->getDeclContext()->isRecord());
8688 assert(isa<UsingShadowDecl>(*I) ||
8689 !(*I)->getDeclContext()->isFunctionOrMethod());
8690 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008691 }
8692 }
8693#endif
8694
John McCall57500772009-12-16 12:17:52 +00008695 // It would be nice to avoid this copy.
8696 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008697 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008698 if (ULE->hasExplicitTemplateArgs()) {
8699 ULE->copyTemplateArgumentsInto(TABuffer);
8700 ExplicitTemplateArgs = &TABuffer;
8701 }
8702
8703 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8704 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008705 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008706 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008707 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008708
John McCall57500772009-12-16 12:17:52 +00008709 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008710 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8711 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008712 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008713 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008714 PartialOverloading,
8715 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008716}
John McCalld681c392009-12-16 08:11:27 +00008717
Richard Smith998a5912011-06-05 22:42:48 +00008718/// Attempt to recover from an ill-formed use of a non-dependent name in a
8719/// template, where the non-dependent name was declared after the template
8720/// was defined. This is common in code written for a compilers which do not
8721/// correctly implement two-stage name lookup.
8722///
8723/// Returns true if a viable candidate was found and a diagnostic was issued.
8724static bool
8725DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8726 const CXXScopeSpec &SS, LookupResult &R,
8727 TemplateArgumentListInfo *ExplicitTemplateArgs,
8728 Expr **Args, unsigned NumArgs) {
8729 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8730 return false;
8731
8732 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8733 SemaRef.LookupQualifiedName(R, DC);
8734
8735 if (!R.empty()) {
8736 R.suppressDiagnostics();
8737
8738 if (isa<CXXRecordDecl>(DC)) {
8739 // Don't diagnose names we find in classes; we get much better
8740 // diagnostics for these from DiagnoseEmptyLookup.
8741 R.clear();
8742 return false;
8743 }
8744
8745 OverloadCandidateSet Candidates(FnLoc);
8746 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8747 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8748 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008749 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008750
8751 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008752 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008753 // No viable functions. Don't bother the user with notes for functions
8754 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008755 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008756 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008757 }
Richard Smith998a5912011-06-05 22:42:48 +00008758
8759 // Find the namespaces where ADL would have looked, and suggest
8760 // declaring the function there instead.
8761 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8762 Sema::AssociatedClassSet AssociatedClasses;
8763 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8764 AssociatedNamespaces,
8765 AssociatedClasses);
8766 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008767 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008768 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008769 for (Sema::AssociatedNamespaceSet::iterator
8770 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008771 end = AssociatedNamespaces.end(); it != end; ++it) {
8772 if (!Std->Encloses(*it))
8773 SuggestedNamespaces.insert(*it);
8774 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008775 } else {
8776 // Lacking the 'std::' namespace, use all of the associated namespaces.
8777 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008778 }
8779
8780 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8781 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008782 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008783 SemaRef.Diag(Best->Function->getLocation(),
8784 diag::note_not_found_by_two_phase_lookup)
8785 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008786 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008787 SemaRef.Diag(Best->Function->getLocation(),
8788 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008789 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008790 } else {
8791 // FIXME: It would be useful to list the associated namespaces here,
8792 // but the diagnostics infrastructure doesn't provide a way to produce
8793 // a localized representation of a list of items.
8794 SemaRef.Diag(Best->Function->getLocation(),
8795 diag::note_not_found_by_two_phase_lookup)
8796 << R.getLookupName() << 2;
8797 }
8798
8799 // Try to recover by calling this function.
8800 return true;
8801 }
8802
8803 R.clear();
8804 }
8805
8806 return false;
8807}
8808
8809/// Attempt to recover from ill-formed use of a non-dependent operator in a
8810/// template, where the non-dependent operator was declared after the template
8811/// was defined.
8812///
8813/// Returns true if a viable candidate was found and a diagnostic was issued.
8814static bool
8815DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8816 SourceLocation OpLoc,
8817 Expr **Args, unsigned NumArgs) {
8818 DeclarationName OpName =
8819 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8820 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8821 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8822 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8823}
8824
John McCalld681c392009-12-16 08:11:27 +00008825/// Attempts to recover from a call where no functions were found.
8826///
8827/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008828static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008829BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008830 UnresolvedLookupExpr *ULE,
8831 SourceLocation LParenLoc,
8832 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008833 SourceLocation RParenLoc,
8834 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008835
8836 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008837 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008838
John McCall57500772009-12-16 12:17:52 +00008839 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008840 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008841 if (ULE->hasExplicitTemplateArgs()) {
8842 ULE->copyTemplateArgumentsInto(TABuffer);
8843 ExplicitTemplateArgs = &TABuffer;
8844 }
8845
John McCalld681c392009-12-16 08:11:27 +00008846 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8847 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008848 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8849 ExplicitTemplateArgs, Args, NumArgs) &&
8850 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008851 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008852 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008853 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008854
John McCall57500772009-12-16 12:17:52 +00008855 assert(!R.empty() && "lookup results empty despite recovery");
8856
8857 // Build an implicit member call if appropriate. Just drop the
8858 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008859 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008860 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008861 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8862 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008863 else if (ExplicitTemplateArgs)
8864 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8865 else
8866 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8867
8868 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008869 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008870
8871 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008872 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008873 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008874 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008875 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008876}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008877
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008878/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008879/// (which eventually refers to the declaration Func) and the call
8880/// arguments Args/NumArgs, attempt to resolve the function call down
8881/// to a specific function. If overload resolution succeeds, returns
8882/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008883/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008884/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008885ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008886Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008887 SourceLocation LParenLoc,
8888 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008889 SourceLocation RParenLoc,
8890 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008891#ifndef NDEBUG
8892 if (ULE->requiresADL()) {
8893 // To do ADL, we must have found an unqualified name.
8894 assert(!ULE->getQualifier() && "qualified name with ADL");
8895
8896 // We don't perform ADL for implicit declarations of builtins.
8897 // Verify that this was correctly set up.
8898 FunctionDecl *F;
8899 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8900 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8901 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008902 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008903
John McCall57500772009-12-16 12:17:52 +00008904 // We don't perform ADL in C.
8905 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008906 } else
8907 assert(!ULE->isStdAssociatedNamespace() &&
8908 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008909#endif
8910
John McCall4124c492011-10-17 18:40:02 +00008911 UnbridgedCastsSet UnbridgedCasts;
8912 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8913 return ExprError();
8914
John McCallbc077cf2010-02-08 23:07:23 +00008915 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008916
John McCall57500772009-12-16 12:17:52 +00008917 // Add the functions denoted by the callee to the set of candidate
8918 // functions, including those from argument-dependent lookup.
8919 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008920
8921 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008922 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8923 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008924 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008925 // In Microsoft mode, if we are inside a template class member function then
8926 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008927 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008928 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00008929 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00008930 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008931 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8932 Context.DependentTy, VK_RValue,
8933 RParenLoc);
8934 CE->setTypeDependent(true);
8935 return Owned(CE);
8936 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008937 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008938 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008939 }
John McCalld681c392009-12-16 08:11:27 +00008940
John McCall4124c492011-10-17 18:40:02 +00008941 UnbridgedCasts.restore();
8942
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008943 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008944 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008945 case OR_Success: {
8946 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008947 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008948 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008949 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008950 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008951 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8952 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008953 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008954
Richard Smith998a5912011-06-05 22:42:48 +00008955 case OR_No_Viable_Function: {
8956 // Try to recover by looking for viable functions which the user might
8957 // have meant to call.
8958 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8959 Args, NumArgs, RParenLoc,
8960 /*EmptyLookup=*/false);
8961 if (!Recovery.isInvalid())
8962 return Recovery;
8963
Chris Lattner45d9d602009-02-17 07:29:20 +00008964 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008965 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008966 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008967 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008968 break;
Richard Smith998a5912011-06-05 22:42:48 +00008969 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008970
8971 case OR_Ambiguous:
8972 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008973 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008974 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008975 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008976
8977 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008978 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008979 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8980 << Best->Function->isDeleted()
8981 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008982 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008983 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008984 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00008985
8986 // We emitted an error for the unvailable/deleted function call but keep
8987 // the call in the AST.
8988 FunctionDecl *FDecl = Best->Function;
8989 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8990 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8991 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008992 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008993 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008994 }
8995
Douglas Gregorb412e172010-07-25 18:17:45 +00008996 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008997 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008998}
8999
John McCall4c4c1df2010-01-26 03:27:55 +00009000static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00009001 return Functions.size() > 1 ||
9002 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9003}
9004
Douglas Gregor084d8552009-03-13 23:49:33 +00009005/// \brief Create a unary operation that may resolve to an overloaded
9006/// operator.
9007///
9008/// \param OpLoc The location of the operator itself (e.g., '*').
9009///
9010/// \param OpcIn The UnaryOperator::Opcode that describes this
9011/// operator.
9012///
9013/// \param Functions The set of non-member functions that will be
9014/// considered by overload resolution. The caller needs to build this
9015/// set based on the context using, e.g.,
9016/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9017/// set should not contain any member functions; those will be added
9018/// by CreateOverloadedUnaryOp().
9019///
9020/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00009021ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00009022Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9023 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00009024 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009025 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00009026
9027 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9028 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9029 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009030 // TODO: provide better source location info.
9031 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009032
John McCall4124c492011-10-17 18:40:02 +00009033 if (checkPlaceholderForOverload(*this, Input))
9034 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009035
Douglas Gregor084d8552009-03-13 23:49:33 +00009036 Expr *Args[2] = { Input, 0 };
9037 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00009038
Douglas Gregor084d8552009-03-13 23:49:33 +00009039 // For post-increment and post-decrement, add the implicit '0' as
9040 // the second argument, so that we know this is a post-increment or
9041 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009042 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009043 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009044 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9045 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009046 NumArgs = 2;
9047 }
9048
9049 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009050 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009051 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009052 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009053 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009054 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009055 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009056
John McCall58cc69d2010-01-27 01:50:18 +00009057 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009058 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009059 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009060 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009061 /*ADL*/ true, IsOverloaded(Fns),
9062 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009063 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009064 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009065 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009066 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009067 OpLoc));
9068 }
9069
9070 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009071 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009072
9073 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009074 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009075
9076 // Add operator candidates that are member functions.
9077 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9078
John McCall4c4c1df2010-01-26 03:27:55 +00009079 // Add candidates from ADL.
9080 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009081 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009082 /*ExplicitTemplateArgs*/ 0,
9083 CandidateSet);
9084
Douglas Gregor084d8552009-03-13 23:49:33 +00009085 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009086 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009087
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009088 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9089
Douglas Gregor084d8552009-03-13 23:49:33 +00009090 // Perform overload resolution.
9091 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009092 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009093 case OR_Success: {
9094 // We found a built-in operator or an overloaded operator.
9095 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009096
Douglas Gregor084d8552009-03-13 23:49:33 +00009097 if (FnDecl) {
9098 // We matched an overloaded operator. Build a call to that
9099 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009100
Chandler Carruth30141632011-02-25 19:41:05 +00009101 MarkDeclarationReferenced(OpLoc, FnDecl);
9102
Douglas Gregor084d8552009-03-13 23:49:33 +00009103 // Convert the arguments.
9104 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009105 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009106
John Wiegley01296292011-04-08 18:41:53 +00009107 ExprResult InputRes =
9108 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9109 Best->FoundDecl, Method);
9110 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009111 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009112 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009113 } else {
9114 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009115 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009116 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009117 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009118 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009119 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009120 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009121 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009122 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009123 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009124 }
9125
John McCall4fa0d5f2010-05-06 18:15:07 +00009126 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9127
John McCall7decc9e2010-11-18 06:31:45 +00009128 // Determine the result type.
9129 QualType ResultTy = FnDecl->getResultType();
9130 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9131 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009132
Douglas Gregor084d8552009-03-13 23:49:33 +00009133 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009134 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9135 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009136 if (FnExpr.isInvalid())
9137 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009138
Eli Friedman030eee42009-11-18 03:58:17 +00009139 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009140 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009141 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009142 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009143
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009144 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009145 FnDecl))
9146 return ExprError();
9147
John McCallb268a282010-08-23 23:25:46 +00009148 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009149 } else {
9150 // We matched a built-in operator. Convert the arguments, then
9151 // break out so that we will build the appropriate built-in
9152 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009153 ExprResult InputRes =
9154 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9155 Best->Conversions[0], AA_Passing);
9156 if (InputRes.isInvalid())
9157 return ExprError();
9158 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009159 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009160 }
John Wiegley01296292011-04-08 18:41:53 +00009161 }
9162
9163 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009164 // This is an erroneous use of an operator which can be overloaded by
9165 // a non-member function. Check for non-member operators which were
9166 // defined too late to be candidates.
9167 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9168 // FIXME: Recover by calling the found function.
9169 return ExprError();
9170
John Wiegley01296292011-04-08 18:41:53 +00009171 // No viable function; fall through to handling this as a
9172 // built-in operator, which will produce an error message for us.
9173 break;
9174
9175 case OR_Ambiguous:
9176 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9177 << UnaryOperator::getOpcodeStr(Opc)
9178 << Input->getType()
9179 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009180 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009181 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9182 return ExprError();
9183
9184 case OR_Deleted:
9185 Diag(OpLoc, diag::err_ovl_deleted_oper)
9186 << Best->Function->isDeleted()
9187 << UnaryOperator::getOpcodeStr(Opc)
9188 << getDeletedOrUnavailableSuffix(Best->Function)
9189 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009190 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9191 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009192 return ExprError();
9193 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009194
9195 // Either we found no viable overloaded operator or we matched a
9196 // built-in operator. In either case, fall through to trying to
9197 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009198 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009199}
9200
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009201/// \brief Create a binary operation that may resolve to an overloaded
9202/// operator.
9203///
9204/// \param OpLoc The location of the operator itself (e.g., '+').
9205///
9206/// \param OpcIn The BinaryOperator::Opcode that describes this
9207/// operator.
9208///
9209/// \param Functions The set of non-member functions that will be
9210/// considered by overload resolution. The caller needs to build this
9211/// set based on the context using, e.g.,
9212/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9213/// set should not contain any member functions; those will be added
9214/// by CreateOverloadedBinOp().
9215///
9216/// \param LHS Left-hand argument.
9217/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009218ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009219Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009220 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009221 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009222 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009223 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009224 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009225
9226 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9227 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9228 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9229
9230 // If either side is type-dependent, create an appropriate dependent
9231 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009232 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009233 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009234 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009235 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009236 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009237 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009238 Context.DependentTy,
9239 VK_RValue, OK_Ordinary,
9240 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009241
Douglas Gregor5287f092009-11-05 00:51:44 +00009242 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9243 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009244 VK_LValue,
9245 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009246 Context.DependentTy,
9247 Context.DependentTy,
9248 OpLoc));
9249 }
John McCall4c4c1df2010-01-26 03:27:55 +00009250
9251 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009252 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009253 // TODO: provide better source location info in DNLoc component.
9254 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009255 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009256 = UnresolvedLookupExpr::Create(Context, NamingClass,
9257 NestedNameSpecifierLoc(), OpNameInfo,
9258 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009259 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009260 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009261 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009262 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009263 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009264 OpLoc));
9265 }
9266
John McCall4124c492011-10-17 18:40:02 +00009267 // Always do placeholder-like conversions on the RHS.
9268 if (checkPlaceholderForOverload(*this, Args[1]))
9269 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009270
John McCall526ab472011-10-25 17:37:35 +00009271 // Do placeholder-like conversion on the LHS; note that we should
9272 // not get here with a PseudoObject LHS.
9273 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009274 if (checkPlaceholderForOverload(*this, Args[0]))
9275 return ExprError();
9276
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009277 // If this is the assignment operator, we only perform overload resolution
9278 // if the left-hand side is a class or enumeration type. This is actually
9279 // a hack. The standard requires that we do overload resolution between the
9280 // various built-in candidates, but as DR507 points out, this can lead to
9281 // problems. So we do it this way, which pretty much follows what GCC does.
9282 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009283 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009284 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009285
John McCalle26a8722010-12-04 08:14:53 +00009286 // If this is the .* operator, which is not overloadable, just
9287 // create a built-in binary operator.
9288 if (Opc == BO_PtrMemD)
9289 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9290
Douglas Gregor084d8552009-03-13 23:49:33 +00009291 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009292 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009293
9294 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009295 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009296
9297 // Add operator candidates that are member functions.
9298 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9299
John McCall4c4c1df2010-01-26 03:27:55 +00009300 // Add candidates from ADL.
9301 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9302 Args, 2,
9303 /*ExplicitTemplateArgs*/ 0,
9304 CandidateSet);
9305
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009306 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009307 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009308
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009309 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9310
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009311 // Perform overload resolution.
9312 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009313 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009314 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009315 // We found a built-in operator or an overloaded operator.
9316 FunctionDecl *FnDecl = Best->Function;
9317
9318 if (FnDecl) {
9319 // We matched an overloaded operator. Build a call to that
9320 // operator.
9321
Chandler Carruth30141632011-02-25 19:41:05 +00009322 MarkDeclarationReferenced(OpLoc, FnDecl);
9323
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009324 // Convert the arguments.
9325 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009326 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009327 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009328
Chandler Carruth8e543b32010-12-12 08:17:55 +00009329 ExprResult Arg1 =
9330 PerformCopyInitialization(
9331 InitializedEntity::InitializeParameter(Context,
9332 FnDecl->getParamDecl(0)),
9333 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009334 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009335 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009336
John Wiegley01296292011-04-08 18:41:53 +00009337 ExprResult Arg0 =
9338 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9339 Best->FoundDecl, Method);
9340 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009341 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009342 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009343 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009344 } else {
9345 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009346 ExprResult Arg0 = PerformCopyInitialization(
9347 InitializedEntity::InitializeParameter(Context,
9348 FnDecl->getParamDecl(0)),
9349 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009350 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009351 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009352
Chandler Carruth8e543b32010-12-12 08:17:55 +00009353 ExprResult Arg1 =
9354 PerformCopyInitialization(
9355 InitializedEntity::InitializeParameter(Context,
9356 FnDecl->getParamDecl(1)),
9357 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009358 if (Arg1.isInvalid())
9359 return ExprError();
9360 Args[0] = LHS = Arg0.takeAs<Expr>();
9361 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009362 }
9363
John McCall4fa0d5f2010-05-06 18:15:07 +00009364 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9365
John McCall7decc9e2010-11-18 06:31:45 +00009366 // Determine the result type.
9367 QualType ResultTy = FnDecl->getResultType();
9368 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9369 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009370
9371 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009372 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9373 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009374 if (FnExpr.isInvalid())
9375 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009376
John McCallb268a282010-08-23 23:25:46 +00009377 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009378 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009379 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009380
9381 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009382 FnDecl))
9383 return ExprError();
9384
John McCallb268a282010-08-23 23:25:46 +00009385 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009386 } else {
9387 // We matched a built-in operator. Convert the arguments, then
9388 // break out so that we will build the appropriate built-in
9389 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009390 ExprResult ArgsRes0 =
9391 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9392 Best->Conversions[0], AA_Passing);
9393 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009394 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009395 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009396
John Wiegley01296292011-04-08 18:41:53 +00009397 ExprResult ArgsRes1 =
9398 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9399 Best->Conversions[1], AA_Passing);
9400 if (ArgsRes1.isInvalid())
9401 return ExprError();
9402 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009403 break;
9404 }
9405 }
9406
Douglas Gregor66950a32009-09-30 21:46:01 +00009407 case OR_No_Viable_Function: {
9408 // C++ [over.match.oper]p9:
9409 // If the operator is the operator , [...] and there are no
9410 // viable functions, then the operator is assumed to be the
9411 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009412 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009413 break;
9414
Chandler Carruth8e543b32010-12-12 08:17:55 +00009415 // For class as left operand for assignment or compound assigment
9416 // operator do not fall through to handling in built-in, but report that
9417 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009418 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009419 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009420 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009421 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9422 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009423 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009424 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009425 // This is an erroneous use of an operator which can be overloaded by
9426 // a non-member function. Check for non-member operators which were
9427 // defined too late to be candidates.
9428 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9429 // FIXME: Recover by calling the found function.
9430 return ExprError();
9431
Douglas Gregor66950a32009-09-30 21:46:01 +00009432 // No viable function; try to create a built-in operation, which will
9433 // produce an error. Then, show the non-viable candidates.
9434 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009436 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009437 "C++ binary operator overloading is missing candidates!");
9438 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009439 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9440 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009441 return move(Result);
9442 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009443
9444 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009445 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009446 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009447 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009448 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009449 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9450 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009451 return ExprError();
9452
9453 case OR_Deleted:
9454 Diag(OpLoc, diag::err_ovl_deleted_oper)
9455 << Best->Function->isDeleted()
9456 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009457 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009458 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009459 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9460 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009461 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009462 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009463
Douglas Gregor66950a32009-09-30 21:46:01 +00009464 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009465 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009466}
9467
John McCalldadc5752010-08-24 06:29:42 +00009468ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009469Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9470 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009471 Expr *Base, Expr *Idx) {
9472 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009473 DeclarationName OpName =
9474 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9475
9476 // If either side is type-dependent, create an appropriate dependent
9477 // expression.
9478 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9479
John McCall58cc69d2010-01-27 01:50:18 +00009480 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009481 // CHECKME: no 'operator' keyword?
9482 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9483 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009484 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009485 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009486 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009487 /*ADL*/ true, /*Overloaded*/ false,
9488 UnresolvedSetIterator(),
9489 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009490 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009491
Sebastian Redladba46e2009-10-29 20:17:01 +00009492 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9493 Args, 2,
9494 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009495 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009496 RLoc));
9497 }
9498
John McCall4124c492011-10-17 18:40:02 +00009499 // Handle placeholders on both operands.
9500 if (checkPlaceholderForOverload(*this, Args[0]))
9501 return ExprError();
9502 if (checkPlaceholderForOverload(*this, Args[1]))
9503 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009504
Sebastian Redladba46e2009-10-29 20:17:01 +00009505 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009506 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009507
9508 // Subscript can only be overloaded as a member function.
9509
9510 // Add operator candidates that are member functions.
9511 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9512
9513 // Add builtin operator candidates.
9514 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9515
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009516 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9517
Sebastian Redladba46e2009-10-29 20:17:01 +00009518 // Perform overload resolution.
9519 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009520 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009521 case OR_Success: {
9522 // We found a built-in operator or an overloaded operator.
9523 FunctionDecl *FnDecl = Best->Function;
9524
9525 if (FnDecl) {
9526 // We matched an overloaded operator. Build a call to that
9527 // operator.
9528
Chandler Carruth30141632011-02-25 19:41:05 +00009529 MarkDeclarationReferenced(LLoc, FnDecl);
9530
John McCalla0296f72010-03-19 07:35:19 +00009531 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009532 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009533
Sebastian Redladba46e2009-10-29 20:17:01 +00009534 // Convert the arguments.
9535 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009536 ExprResult Arg0 =
9537 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9538 Best->FoundDecl, Method);
9539 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009540 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009541 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009542
Anders Carlssona68e51e2010-01-29 18:37:50 +00009543 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009544 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009545 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009546 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009547 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009548 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009549 Owned(Args[1]));
9550 if (InputInit.isInvalid())
9551 return ExprError();
9552
9553 Args[1] = InputInit.takeAs<Expr>();
9554
Sebastian Redladba46e2009-10-29 20:17:01 +00009555 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009556 QualType ResultTy = FnDecl->getResultType();
9557 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9558 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009559
9560 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009561 DeclarationNameLoc LocInfo;
9562 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9563 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009564 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9565 HadMultipleCandidates,
9566 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009567 if (FnExpr.isInvalid())
9568 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009569
John McCallb268a282010-08-23 23:25:46 +00009570 CXXOperatorCallExpr *TheCall =
9571 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009572 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009573 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009574
John McCallb268a282010-08-23 23:25:46 +00009575 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009576 FnDecl))
9577 return ExprError();
9578
John McCallb268a282010-08-23 23:25:46 +00009579 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009580 } else {
9581 // We matched a built-in operator. Convert the arguments, then
9582 // break out so that we will build the appropriate built-in
9583 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009584 ExprResult ArgsRes0 =
9585 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9586 Best->Conversions[0], AA_Passing);
9587 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009588 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009589 Args[0] = ArgsRes0.take();
9590
9591 ExprResult ArgsRes1 =
9592 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9593 Best->Conversions[1], AA_Passing);
9594 if (ArgsRes1.isInvalid())
9595 return ExprError();
9596 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009597
9598 break;
9599 }
9600 }
9601
9602 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009603 if (CandidateSet.empty())
9604 Diag(LLoc, diag::err_ovl_no_oper)
9605 << Args[0]->getType() << /*subscript*/ 0
9606 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9607 else
9608 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9609 << Args[0]->getType()
9610 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009611 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9612 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009613 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009614 }
9615
9616 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009617 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009618 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009619 << Args[0]->getType() << Args[1]->getType()
9620 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009621 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9622 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009623 return ExprError();
9624
9625 case OR_Deleted:
9626 Diag(LLoc, diag::err_ovl_deleted_oper)
9627 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009628 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009629 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009630 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9631 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009632 return ExprError();
9633 }
9634
9635 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009636 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009637}
9638
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009639/// BuildCallToMemberFunction - Build a call to a member
9640/// function. MemExpr is the expression that refers to the member
9641/// function (and includes the object parameter), Args/NumArgs are the
9642/// arguments to the function call (not including the object
9643/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009644/// expression refers to a non-static member function or an overloaded
9645/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009646ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009647Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9648 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009649 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009650 assert(MemExprE->getType() == Context.BoundMemberTy ||
9651 MemExprE->getType() == Context.OverloadTy);
9652
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009653 // Dig out the member expression. This holds both the object
9654 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009655 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009656
John McCall0009fcc2011-04-26 20:42:42 +00009657 // Determine whether this is a call to a pointer-to-member function.
9658 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9659 assert(op->getType() == Context.BoundMemberTy);
9660 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9661
9662 QualType fnType =
9663 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9664
9665 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9666 QualType resultType = proto->getCallResultType(Context);
9667 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9668
9669 // Check that the object type isn't more qualified than the
9670 // member function we're calling.
9671 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9672
9673 QualType objectType = op->getLHS()->getType();
9674 if (op->getOpcode() == BO_PtrMemI)
9675 objectType = objectType->castAs<PointerType>()->getPointeeType();
9676 Qualifiers objectQuals = objectType.getQualifiers();
9677
9678 Qualifiers difference = objectQuals - funcQuals;
9679 difference.removeObjCGCAttr();
9680 difference.removeAddressSpace();
9681 if (difference) {
9682 std::string qualsString = difference.getAsString();
9683 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9684 << fnType.getUnqualifiedType()
9685 << qualsString
9686 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9687 }
9688
9689 CXXMemberCallExpr *call
9690 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9691 resultType, valueKind, RParenLoc);
9692
9693 if (CheckCallReturnType(proto->getResultType(),
9694 op->getRHS()->getSourceRange().getBegin(),
9695 call, 0))
9696 return ExprError();
9697
9698 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9699 return ExprError();
9700
9701 return MaybeBindToTemporary(call);
9702 }
9703
John McCall4124c492011-10-17 18:40:02 +00009704 UnbridgedCastsSet UnbridgedCasts;
9705 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9706 return ExprError();
9707
John McCall10eae182009-11-30 22:42:35 +00009708 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009709 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009710 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009711 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009712 if (isa<MemberExpr>(NakedMemExpr)) {
9713 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009714 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009715 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009716 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009717 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009718 } else {
9719 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009720 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009721
John McCall6e9f8f62009-12-03 04:06:58 +00009722 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009723 Expr::Classification ObjectClassification
9724 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9725 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009726
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009727 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009728 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009729
John McCall2d74de92009-12-01 22:10:20 +00009730 // FIXME: avoid copy.
9731 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9732 if (UnresExpr->hasExplicitTemplateArgs()) {
9733 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9734 TemplateArgs = &TemplateArgsBuffer;
9735 }
9736
John McCall10eae182009-11-30 22:42:35 +00009737 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9738 E = UnresExpr->decls_end(); I != E; ++I) {
9739
John McCall6e9f8f62009-12-03 04:06:58 +00009740 NamedDecl *Func = *I;
9741 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9742 if (isa<UsingShadowDecl>(Func))
9743 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9744
Douglas Gregor02824322011-01-26 19:30:28 +00009745
Francois Pichet64225792011-01-18 05:04:39 +00009746 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009747 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009748 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9749 CandidateSet);
9750 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009751 // If explicit template arguments were provided, we can't call a
9752 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009753 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009754 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009755
John McCalla0296f72010-03-19 07:35:19 +00009756 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009757 ObjectClassification,
9758 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009759 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009760 } else {
John McCall10eae182009-11-30 22:42:35 +00009761 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009762 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009763 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009764 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009765 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009766 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009767 }
Mike Stump11289f42009-09-09 15:08:12 +00009768
John McCall10eae182009-11-30 22:42:35 +00009769 DeclarationName DeclName = UnresExpr->getMemberName();
9770
John McCall4124c492011-10-17 18:40:02 +00009771 UnbridgedCasts.restore();
9772
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009773 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009774 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009775 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009776 case OR_Success:
9777 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009778 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009779 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009780 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009781 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009782 break;
9783
9784 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009785 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009786 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009787 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009788 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009789 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009790 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009791
9792 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009793 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009794 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009795 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009796 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009797 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009798
9799 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009800 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009801 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009802 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009803 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009804 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009805 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009806 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009807 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009808 }
9809
John McCall16df1e52010-03-30 21:47:33 +00009810 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009811
John McCall2d74de92009-12-01 22:10:20 +00009812 // If overload resolution picked a static member, build a
9813 // non-member call based on that function.
9814 if (Method->isStatic()) {
9815 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9816 Args, NumArgs, RParenLoc);
9817 }
9818
John McCall10eae182009-11-30 22:42:35 +00009819 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009820 }
9821
John McCall7decc9e2010-11-18 06:31:45 +00009822 QualType ResultType = Method->getResultType();
9823 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9824 ResultType = ResultType.getNonLValueExprType(Context);
9825
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009826 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009827 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009828 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009829 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009830
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009831 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009832 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009833 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009834 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009835
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009836 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009837 // We only need to do this if there was actually an overload; otherwise
9838 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009839 if (!Method->isStatic()) {
9840 ExprResult ObjectArg =
9841 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9842 FoundDecl, Method);
9843 if (ObjectArg.isInvalid())
9844 return ExprError();
9845 MemExpr->setBase(ObjectArg.take());
9846 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009847
9848 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009849 const FunctionProtoType *Proto =
9850 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009851 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009852 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009853 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009854
John McCallb268a282010-08-23 23:25:46 +00009855 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009856 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009857
Anders Carlsson47061ee2011-05-06 14:25:31 +00009858 if ((isa<CXXConstructorDecl>(CurContext) ||
9859 isa<CXXDestructorDecl>(CurContext)) &&
9860 TheCall->getMethodDecl()->isPure()) {
9861 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9862
Chandler Carruth59259262011-06-27 08:31:58 +00009863 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009864 Diag(MemExpr->getLocStart(),
9865 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9866 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9867 << MD->getParent()->getDeclName();
9868
9869 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009870 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009871 }
John McCallb268a282010-08-23 23:25:46 +00009872 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009873}
9874
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009875/// BuildCallToObjectOfClassType - Build a call to an object of class
9876/// type (C++ [over.call.object]), which can end up invoking an
9877/// overloaded function call operator (@c operator()) or performing a
9878/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009879ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009880Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009881 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009882 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009883 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009884 if (checkPlaceholderForOverload(*this, Obj))
9885 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009886 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009887
9888 UnbridgedCastsSet UnbridgedCasts;
9889 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9890 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009891
John Wiegley01296292011-04-08 18:41:53 +00009892 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9893 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009894
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009895 // C++ [over.call.object]p1:
9896 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009897 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009898 // candidate functions includes at least the function call
9899 // operators of T. The function call operators of T are obtained by
9900 // ordinary lookup of the name operator() in the context of
9901 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009902 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009903 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009904
John Wiegley01296292011-04-08 18:41:53 +00009905 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009906 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009907 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009908 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009909
John McCall27b18f82009-11-17 02:14:36 +00009910 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9911 LookupQualifiedName(R, Record->getDecl());
9912 R.suppressDiagnostics();
9913
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009914 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009915 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009916 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9917 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009918 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009919 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009920
Douglas Gregorab7897a2008-11-19 22:57:39 +00009921 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009922 // In addition, for each (non-explicit in C++0x) conversion function
9923 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009924 //
9925 // operator conversion-type-id () cv-qualifier;
9926 //
9927 // where cv-qualifier is the same cv-qualification as, or a
9928 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009929 // denotes the type "pointer to function of (P1,...,Pn) returning
9930 // R", or the type "reference to pointer to function of
9931 // (P1,...,Pn) returning R", or the type "reference to function
9932 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009933 // is also considered as a candidate function. Similarly,
9934 // surrogate call functions are added to the set of candidate
9935 // functions for each conversion function declared in an
9936 // accessible base class provided the function is not hidden
9937 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009938 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009939 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009940 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009941 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009942 NamedDecl *D = *I;
9943 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9944 if (isa<UsingShadowDecl>(D))
9945 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009946
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009947 // Skip over templated conversion functions; they aren't
9948 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009949 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009950 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009951
John McCall6e9f8f62009-12-03 04:06:58 +00009952 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009953 if (!Conv->isExplicit()) {
9954 // Strip the reference type (if any) and then the pointer type (if
9955 // any) to get down to what might be a function type.
9956 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9957 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9958 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009959
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009960 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9961 {
9962 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9963 Object.get(), Args, NumArgs, CandidateSet);
9964 }
9965 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009966 }
Mike Stump11289f42009-09-09 15:08:12 +00009967
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9969
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009970 // Perform overload resolution.
9971 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009972 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009973 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009974 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009975 // Overload resolution succeeded; we'll build the appropriate call
9976 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009977 break;
9978
9979 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009980 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009981 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9982 << Object.get()->getType() << /*call*/ 1
9983 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009984 else
John Wiegley01296292011-04-08 18:41:53 +00009985 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009986 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009987 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009988 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009989 break;
9990
9991 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009992 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009993 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009994 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009995 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009996 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009997
9998 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009999 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000010000 diag::err_ovl_deleted_object_call)
10001 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000010002 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010003 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000010004 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010005 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +000010006 break;
Mike Stump11289f42009-09-09 15:08:12 +000010007 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010008
Douglas Gregorb412e172010-07-25 18:17:45 +000010009 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010010 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010011
John McCall4124c492011-10-17 18:40:02 +000010012 UnbridgedCasts.restore();
10013
Douglas Gregorab7897a2008-11-19 22:57:39 +000010014 if (Best->Function == 0) {
10015 // Since there is no function declaration, this is one of the
10016 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000010017 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000010018 = cast<CXXConversionDecl>(
10019 Best->Conversions[0].UserDefined.ConversionFunction);
10020
John Wiegley01296292011-04-08 18:41:53 +000010021 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010022 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010023
Douglas Gregorab7897a2008-11-19 22:57:39 +000010024 // We selected one of the surrogate functions that converts the
10025 // object parameter to a function pointer. Perform the conversion
10026 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010027
Fariborz Jahanian774cf792009-09-28 18:35:46 +000010028 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000010029 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010030 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10031 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000010032 if (Call.isInvalid())
10033 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000010034 // Record usage of conversion in an implicit cast.
10035 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10036 CK_UserDefinedConversion,
10037 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010038
Douglas Gregor668443e2011-01-20 00:18:04 +000010039 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010040 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010041 }
10042
Chandler Carruth30141632011-02-25 19:41:05 +000010043 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010044 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010045 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010046
Douglas Gregorab7897a2008-11-19 22:57:39 +000010047 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10048 // that calls this method, using Object for the implicit object
10049 // parameter and passing along the remaining arguments.
10050 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010051 const FunctionProtoType *Proto =
10052 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010053
10054 unsigned NumArgsInProto = Proto->getNumArgs();
10055 unsigned NumArgsToCheck = NumArgs;
10056
10057 // Build the full argument list for the method call (the
10058 // implicit object parameter is placed at the beginning of the
10059 // list).
10060 Expr **MethodArgs;
10061 if (NumArgs < NumArgsInProto) {
10062 NumArgsToCheck = NumArgsInProto;
10063 MethodArgs = new Expr*[NumArgsInProto + 1];
10064 } else {
10065 MethodArgs = new Expr*[NumArgs + 1];
10066 }
John Wiegley01296292011-04-08 18:41:53 +000010067 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010068 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10069 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010070
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010071 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10072 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010073 if (NewFn.isInvalid())
10074 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010075
10076 // Once we've built TheCall, all of the expressions are properly
10077 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010078 QualType ResultTy = Method->getResultType();
10079 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10080 ResultTy = ResultTy.getNonLValueExprType(Context);
10081
John McCallb268a282010-08-23 23:25:46 +000010082 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010083 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010084 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010085 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010086 delete [] MethodArgs;
10087
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010088 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010089 Method))
10090 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010091
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010092 // We may have default arguments. If so, we need to allocate more
10093 // slots in the call for them.
10094 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010095 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010096 else if (NumArgs > NumArgsInProto)
10097 NumArgsToCheck = NumArgsInProto;
10098
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010099 bool IsError = false;
10100
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010101 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010102 ExprResult ObjRes =
10103 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10104 Best->FoundDecl, Method);
10105 if (ObjRes.isInvalid())
10106 IsError = true;
10107 else
10108 Object = move(ObjRes);
10109 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010110
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010111 // Check the argument types.
10112 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010113 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010114 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010115 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010116
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010117 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010118
John McCalldadc5752010-08-24 06:29:42 +000010119 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010120 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010121 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010122 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010123 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010124
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010125 IsError |= InputInit.isInvalid();
10126 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010127 } else {
John McCalldadc5752010-08-24 06:29:42 +000010128 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010129 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10130 if (DefArg.isInvalid()) {
10131 IsError = true;
10132 break;
10133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010134
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010135 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010136 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010137
10138 TheCall->setArg(i + 1, Arg);
10139 }
10140
10141 // If this is a variadic call, handle args passed through "...".
10142 if (Proto->isVariadic()) {
10143 // Promote the arguments (C99 6.5.2.2p7).
10144 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010145 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10146 IsError |= Arg.isInvalid();
10147 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010148 }
10149 }
10150
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010151 if (IsError) return true;
10152
John McCallb268a282010-08-23 23:25:46 +000010153 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010154 return true;
10155
John McCalle172be52010-08-24 06:09:16 +000010156 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010157}
10158
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010159/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010160/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010161/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010162ExprResult
John McCallb268a282010-08-23 23:25:46 +000010163Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010164 assert(Base->getType()->isRecordType() &&
10165 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010166
John McCall4124c492011-10-17 18:40:02 +000010167 if (checkPlaceholderForOverload(*this, Base))
10168 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010169
John McCallbc077cf2010-02-08 23:07:23 +000010170 SourceLocation Loc = Base->getExprLoc();
10171
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010172 // C++ [over.ref]p1:
10173 //
10174 // [...] An expression x->m is interpreted as (x.operator->())->m
10175 // for a class object x of type T if T::operator->() exists and if
10176 // the operator is selected as the best match function by the
10177 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010178 DeclarationName OpName =
10179 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010180 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010181 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010182
John McCallbc077cf2010-02-08 23:07:23 +000010183 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010184 PDiag(diag::err_typecheck_incomplete_tag)
10185 << Base->getSourceRange()))
10186 return ExprError();
10187
John McCall27b18f82009-11-17 02:14:36 +000010188 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10189 LookupQualifiedName(R, BaseRecord->getDecl());
10190 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010191
10192 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010193 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010194 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10195 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010196 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010197
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010198 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10199
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010200 // Perform overload resolution.
10201 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010202 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010203 case OR_Success:
10204 // Overload resolution succeeded; we'll build the call below.
10205 break;
10206
10207 case OR_No_Viable_Function:
10208 if (CandidateSet.empty())
10209 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010210 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010211 else
10212 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010213 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010214 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010215 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010216
10217 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010218 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10219 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010220 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010221 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010222
10223 case OR_Deleted:
10224 Diag(OpLoc, diag::err_ovl_deleted_oper)
10225 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010226 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010227 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010228 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010229 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010230 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010231 }
10232
Chandler Carruth30141632011-02-25 19:41:05 +000010233 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010234 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010235 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010236
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010237 // Convert the object parameter.
10238 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010239 ExprResult BaseResult =
10240 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10241 Best->FoundDecl, Method);
10242 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010243 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010244 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010245
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010246 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010247 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10248 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010249 if (FnExpr.isInvalid())
10250 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010251
John McCall7decc9e2010-11-18 06:31:45 +000010252 QualType ResultTy = Method->getResultType();
10253 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10254 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010255 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010256 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010257 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010258
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010259 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010260 Method))
10261 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010262
10263 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010264}
10265
Douglas Gregorcd695e52008-11-10 20:40:00 +000010266/// FixOverloadedFunctionReference - E is an expression that refers to
10267/// a C++ overloaded function (possibly with some parentheses and
10268/// perhaps a '&' around it). We have resolved the overloaded function
10269/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010270/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010271Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010272 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010273 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010274 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10275 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010276 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010277 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010278
Douglas Gregor51c538b2009-11-20 19:42:02 +000010279 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010280 }
10281
Douglas Gregor51c538b2009-11-20 19:42:02 +000010282 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010283 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10284 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010285 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010286 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010287 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010288 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010289 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010290 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010291
10292 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010293 ICE->getCastKind(),
10294 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010295 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010296 }
10297
Douglas Gregor51c538b2009-11-20 19:42:02 +000010298 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010299 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010300 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010301 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10302 if (Method->isStatic()) {
10303 // Do nothing: static member functions aren't any different
10304 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010305 } else {
John McCalle66edc12009-11-24 19:00:30 +000010306 // Fix the sub expression, which really has to be an
10307 // UnresolvedLookupExpr holding an overloaded member function
10308 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010309 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10310 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010311 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010312 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010313
John McCalld14a8642009-11-21 08:51:07 +000010314 assert(isa<DeclRefExpr>(SubExpr)
10315 && "fixed to something other than a decl ref");
10316 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10317 && "fixed to a member ref with no nested name qualifier");
10318
10319 // We have taken the address of a pointer to member
10320 // function. Perform the computation here so that we get the
10321 // appropriate pointer to member type.
10322 QualType ClassType
10323 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10324 QualType MemPtrType
10325 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10326
John McCall7decc9e2010-11-18 06:31:45 +000010327 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10328 VK_RValue, OK_Ordinary,
10329 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010330 }
10331 }
John McCall16df1e52010-03-30 21:47:33 +000010332 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10333 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010334 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010335 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010336
John McCalle3027922010-08-25 11:45:40 +000010337 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010338 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010339 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010340 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010341 }
John McCalld14a8642009-11-21 08:51:07 +000010342
10343 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010344 // FIXME: avoid copy.
10345 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010346 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010347 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10348 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010349 }
10350
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010351 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10352 ULE->getQualifierLoc(),
10353 Fn,
10354 ULE->getNameLoc(),
10355 Fn->getType(),
10356 VK_LValue,
10357 Found.getDecl(),
10358 TemplateArgs);
10359 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10360 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010361 }
10362
John McCall10eae182009-11-30 22:42:35 +000010363 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010364 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010365 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10366 if (MemExpr->hasExplicitTemplateArgs()) {
10367 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10368 TemplateArgs = &TemplateArgsBuffer;
10369 }
John McCall6b51f282009-11-23 01:53:49 +000010370
John McCall2d74de92009-12-01 22:10:20 +000010371 Expr *Base;
10372
John McCall7decc9e2010-11-18 06:31:45 +000010373 // If we're filling in a static method where we used to have an
10374 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010375 if (MemExpr->isImplicitAccess()) {
10376 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010377 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10378 MemExpr->getQualifierLoc(),
10379 Fn,
10380 MemExpr->getMemberLoc(),
10381 Fn->getType(),
10382 VK_LValue,
10383 Found.getDecl(),
10384 TemplateArgs);
10385 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10386 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010387 } else {
10388 SourceLocation Loc = MemExpr->getMemberLoc();
10389 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010390 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000010391 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000010392 Base = new (Context) CXXThisExpr(Loc,
10393 MemExpr->getBaseType(),
10394 /*isImplicit=*/true);
10395 }
John McCall2d74de92009-12-01 22:10:20 +000010396 } else
John McCallc3007a22010-10-26 07:05:15 +000010397 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010398
John McCall4adb38c2011-04-27 00:36:17 +000010399 ExprValueKind valueKind;
10400 QualType type;
10401 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10402 valueKind = VK_LValue;
10403 type = Fn->getType();
10404 } else {
10405 valueKind = VK_RValue;
10406 type = Context.BoundMemberTy;
10407 }
10408
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010409 MemberExpr *ME = MemberExpr::Create(Context, Base,
10410 MemExpr->isArrow(),
10411 MemExpr->getQualifierLoc(),
10412 Fn,
10413 Found,
10414 MemExpr->getMemberNameInfo(),
10415 TemplateArgs,
10416 type, valueKind, OK_Ordinary);
10417 ME->setHadMultipleCandidates(true);
10418 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010420
John McCallc3007a22010-10-26 07:05:15 +000010421 llvm_unreachable("Invalid reference to overloaded function");
10422 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010423}
10424
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010425ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010426 DeclAccessPair Found,
10427 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010428 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010429}
10430
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010431} // end namespace clang