blob: ee846c3fc3dc24b8f1941315a3ee03308965a6da [file] [log] [blame]
Douglas Gregor8e9bebd2008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley429bb272011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Abramo Bagnara7cc58b42011-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 Wiegley429bb272011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000052}
53
John McCall120d63c2010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-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 McCall120d63c2010-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 Gregor8e9bebd2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-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 Lopes2550d702009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor60d62c22008-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 Gregora9bff302010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202}
203
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-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 Gregorad323a82010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-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 Gregorbc0805a2008-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 Stump1eb44332009-09-09 15:08:12 +0000242bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-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 Gregorf9af5242011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Douglas Gregor8e9bebd2008-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 Lattner5f9e2722011-07-23 10:55:15 +0000264 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 bool PrintedSomething = false;
266 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000267 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000268 PrintedSomething = true;
269 }
270
271 if (Second != ICK_Identity) {
272 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000273 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000274 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000275 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000276
277 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000278 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000279 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000280 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000281 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000282 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000283 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000284 PrintedSomething = true;
285 }
286
287 if (Third != ICK_Identity) {
288 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000289 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000290 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000291 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000292 PrintedSomething = true;
293 }
294
295 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000296 OS << "No conversions required";
Douglas Gregor8e9bebd2008-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 Lattner5f9e2722011-07-23 10:55:15 +0000303 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000304 if (Before.First || Before.Second || Before.Third) {
305 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000306 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000307 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000308 if (ConversionFunction)
309 OS << '\'' << *ConversionFunction << '\'';
310 else
311 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000312 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000313 OS << " -> ";
Douglas Gregor8e9bebd2008-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 Lattner5f9e2722011-07-23 10:55:15 +0000321 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000322 switch (ConversionKind) {
323 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000324 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000325 Standard.DebugPrint();
326 break;
327 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000328 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000329 UserDefined.DebugPrint();
330 break;
331 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000332 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000333 break;
John McCall1d318332010-01-12 00:44:57 +0000334 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000335 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000336 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000337 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000338 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339 break;
340 }
341
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000342 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000343}
344
John McCall1d318332010-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 Gregora9333192010-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 Takumidfbb02a2011-01-27 07:10:08 +0000369
Douglas Gregora9333192010-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 Gregorff5adac2010-05-08 20:18:54 +0000373static MakeDeductionFailureInfo(ASTContext &Context,
374 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000375 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000382 case Sema::TDK_TooManyArguments:
383 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000384 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000385
Douglas Gregora9333192010-05-08 17:41:32 +0000386 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000387 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000388 Result.Data = Info.Param.getOpaqueValue();
389 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390
Douglas Gregora9333192010-05-08 17:41:32 +0000391 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000392 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-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 Gregora9333192010-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 Takumidfbb02a2011-01-27 07:10:08 +0000401
Douglas Gregora9333192010-05-08 17:41:32 +0000402 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000403 Result.Data = Info.take();
404 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000405
Douglas Gregora9333192010-05-08 17:41:32 +0000406 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000407 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000408 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000409 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000410
Douglas Gregora9333192010-05-08 17:41:32 +0000411 return Result;
412}
John McCall1d318332010-01-12 00:44:57 +0000413
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000419 case Sema::TDK_TooManyArguments:
420 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000421 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000422 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423
Douglas Gregora9333192010-05-08 17:41:32 +0000424 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000425 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000426 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000427 Data = 0;
428 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000429
430 case Sema::TDK_SubstitutionFailure:
431 // FIXME: Destroy the template arugment list?
432 Data = 0;
433 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000434
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000441
442TemplateParameter
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000447 case Sema::TDK_TooManyArguments:
448 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000449 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000450 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451
Douglas Gregora9333192010-05-08 17:41:32 +0000452 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000453 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000454 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000455
456 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000458 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000459
Douglas Gregora9333192010-05-08 17:41:32 +0000460 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000465
Douglas Gregora9333192010-05-08 17:41:32 +0000466 return TemplateParameter();
467}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468
Douglas Gregorec20f462010-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 McCall57e97782010-08-05 09:05:08 +0000479 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000480 return 0;
481
482 case Sema::TDK_SubstitutionFailure:
483 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000484
Douglas Gregorec20f462010-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 Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000499 case Sema::TDK_TooManyArguments:
500 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000501 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000502 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000503 return 0;
504
Douglas Gregora9333192010-05-08 17:41:32 +0000505 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000506 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000507 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000508
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000509 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000510 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000511 case Sema::TDK_FailedOverloadResolution:
512 break;
513 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000514
Douglas Gregora9333192010-05-08 17:41:32 +0000515 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000516}
Douglas Gregora9333192010-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 Gregor0ca4c582010-05-08 18:20:53 +0000524 case Sema::TDK_TooManyArguments:
525 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000526 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000527 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000528 return 0;
529
Douglas Gregora9333192010-05-08 17:41:32 +0000530 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000531 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000532 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
533
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000534 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000535 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000536 case Sema::TDK_FailedOverloadResolution:
537 break;
538 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000539
Douglas Gregora9333192010-05-08 17:41:32 +0000540 return 0;
541}
542
543void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000544 inherited::clear();
545 Functions.clear();
546}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000547
John McCall5acb0c92011-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 McCall5acb0c92011-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 Gregor8e9bebd2008-10-21 16:13:35 +0000619// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-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 McCall871b2e72009-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 Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000635// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000636//
John McCall51fa86f2009-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 Gregor8e9bebd2008-10-21 16:13:35 +0000641//
John McCall51fa86f2009-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 Gregor8e9bebd2008-10-21 16:13:35 +0000646// signature), IsOverload returns false and MatchedDecl will be set to
647// point to the FunctionDecl for #2.
John McCallad00b772010-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 McCall871b2e72009-12-09 03:35:25 +0000653Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000654Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
655 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000656 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000657 I != E; ++I) {
John McCallad00b772010-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 McCall51fa86f2009-12-02 08:47:38 +0000679 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-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 McCall871b2e72009-12-09 03:35:25 +0000686 Match = *I;
687 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000688 }
John McCall51fa86f2009-12-02 08:47:38 +0000689 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-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 McCall871b2e72009-12-09 03:35:25 +0000696 Match = *I;
697 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000698 }
John McCalld7945c62010-11-10 03:01:53 +0000699 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-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 McCalld7945c62010-11-10 03:01:53 +0000703 } else if (isa<TagDecl>(OldD)) {
704 // We can always overload with tags by hiding them.
John McCall9f54ad42009-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 McCall68263142009-11-18 22:49:29 +0000710 // (C++ 13p1):
711 // Only function declarations can be overloaded; object and type
712 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000713 Match = *I;
714 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000715 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000716 }
John McCall68263142009-11-18 22:49:29 +0000717
John McCall871b2e72009-12-09 03:35:25 +0000718 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000719}
720
John McCallad00b772010-06-16 08:42:20 +0000721bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
722 bool UseUsingDeclRules) {
John McCall7b492022010-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 McCall68263142009-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 McCallf4c73712011-01-19 06:33:43 +0000751 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
752 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-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 Jahaniand8d34412010-05-03 21:06:18 +0000760 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-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 McCallad00b772010-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 McCall68263142009-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 Gregor57c9f4f2011-01-26 17:47:49 +0000783 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-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 Gregor57c9f4f2011-01-26 17:47:49 +0000794 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-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 Takumidfbb02a2011-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 Gregorb145ee62011-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 Takumidfbb02a2011-01-27 07:10:08 +0000810
John McCall68263142009-11-18 22:49:29 +0000811 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000813
John McCall68263142009-11-18 22:49:29 +0000814 // The signatures match; this is not an overload.
815 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816}
817
Argyrios Kyrtzidis572bbec2011-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 Redlcf15cef2011-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 Gregor27c8dc02008-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 Gregor8e9bebd2008-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 Gregor225c41e2008-11-03 19:09:14 +0000925///
926/// If @p SuppressUserConversions, then user-defined conversions are
927/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000928/// If @p AllowExplicit, then explicit user-defined conversions are
929/// permitted.
John McCallf85e1932011-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 McCall120d63c2010-08-24 20:38:10 +0000934static ImplicitConversionSequence
935TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
936 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000937 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000938 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +0000939 bool CStyle,
940 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000941 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000942 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +0000943 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +0000944 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000945 return ICS;
946 }
947
John McCall120d63c2010-08-24 20:38:10 +0000948 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000949 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000950 return ICS;
951 }
952
Douglas Gregor604eb652010-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 McCall120d63c2010-08-24 20:38:10 +0000962 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
963 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000964 ICS.setStandard();
965 ICS.Standard.setAsIdentityConversion();
966 ICS.Standard.setFromType(FromType);
967 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000968
Douglas Gregor3fbaf3e2010-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 Takumidfbb02a2011-01-27 07:10:08 +0000974
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000975 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000976 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000977 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000978
Douglas Gregor604eb652010-08-11 02:15:33 +0000979 return ICS;
980 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000981
Sebastian Redlcf15cef2011-12-22 18:58:38 +0000982 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
983 AllowExplicit, InOverloadResolution, CStyle,
984 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000985}
986
John McCallf85e1932011-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 McCall120d63c2010-08-24 20:38:10 +0000998}
999
Douglas Gregor575c63a2010-04-16 22:27:05 +00001000/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001001/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-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 Wiegley429bb272011-04-08 18:41:53 +00001005ExprResult
1006Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001007 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001008 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001009 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001010}
1011
John Wiegley429bb272011-04-08 18:41:53 +00001012ExprResult
1013Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001014 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001015 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001016 if (checkPlaceholderForOverload(*this, From))
1017 return ExprError();
1018
John McCallf85e1932011-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 McCallf85e1932011-06-15 23:02:42 +00001023
John McCall120d63c2010-08-24 20:38:10 +00001024 ICS = clang::TryImplicitConversion(*this, From, ToType,
1025 /*SuppressUserConversions=*/false,
1026 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001027 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001028 /*CStyle=*/false,
1029 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001030 return PerformImplicitConversion(From, ToType, ICS, Action);
1031}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001032
1033/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001034/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001035bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1036 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001037 if (Context.hasSameUnqualifiedType(FromType, ToType))
1038 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001039
John McCall00ccbef2010-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 Gregor43c79c22009-12-09 00:47:37 +00001062
John McCall00ccbef2010-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 Gregor43c79c22009-12-09 00:47:37 +00001078 return true;
1079}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001080
Douglas Gregorfb4a5432010-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 Takumidfbb02a2011-01-27 07:10:08 +00001086static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1087 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-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 Takumidfbb02a2011-01-27 07:10:08 +00001103
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001104 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001105 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001106 ICK = ICK_Vector_Splat;
1107 return true;
1108 }
1109 }
Douglas Gregor255210e2010-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 Carruthc45eb9c2010-08-08 05:02:51 +00001117 (Context.getLangOptions().LaxVectorConversions &&
1118 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001119 ICK = ICK_Vector_Conversion;
1120 return true;
1121 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001122 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001123
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001124 return false;
1125}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001126
Douglas Gregor60d62c22008-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 McCall120d63c2010-08-24 20:38:10 +00001135static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1136 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001137 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001138 bool CStyle,
1139 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001140 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001141
Douglas Gregor60d62c22008-10-31 16:23:19 +00001142 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001143 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001144 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001145 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001146 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001147 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001148
Douglas Gregorf9201e02009-02-11 23:02:49 +00001149 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001150 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001151 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001152 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001153 return false;
1154
Mike Stump1eb44332009-09-09 15:08:12 +00001155 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001156 }
1157
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00001162 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001163 DeclAccessPair AccessPair;
1164 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001165 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001166 AccessPair)) {
Douglas Gregorad4e02f2010-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 Gregor1be8eec2011-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 Carruth18e04612011-06-18 01:19:03 +00001177 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-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 Gregorad4e02f2010-04-29 18:24:40 +00001182 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001183
Chandler Carruth90434232011-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 Carruthfc5c8fc2011-03-29 18:38:10 +00001198 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1199 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1200 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001201 "Non-address-of operator for overloaded function expression");
1202 FromType = S.Context.getPointerType(FromType);
1203 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001204
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001205 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001206 assert(S.Context.hasSameType(
1207 FromType,
1208 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001209 } else {
1210 return false;
1211 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001212 }
John McCall21480112011-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 McCall7eb0a9e2010-11-24 05:12:34 +00001217 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001218 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001219 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001220 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-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 Gregorf9201e02009-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 Gregor60d62c22008-10-31 16:23:19 +00001226 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001227 } else if (FromType->isArrayType()) {
1228 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001229 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00001234 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001235
John McCall120d63c2010-08-24 20:38:10 +00001236 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001237 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001238 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-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 Gregor60d62c22008-10-31 16:23:19 +00001244 SCS.Second = ICK_Identity;
1245 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001246 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001247 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001248 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001249 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001250 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001251 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001252 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00001257 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001258 } else {
1259 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001260 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001261 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001262 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-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 Gregorf9201e02009-02-11 23:02:49 +00001268 // For overloading in C, this can also be a "compatible-type"
1269 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001270 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001271 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001272 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001273 // The unqualified versions of the types are the same: there's no
1274 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001275 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001276 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001277 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001278 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001279 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001280 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001281 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001282 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001283 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001284 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001285 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001286 SCS.Second = ICK_Complex_Promotion;
1287 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-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 Gregor1274ccd2010-10-08 23:50:27 +00001297 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001298 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001299 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001300 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001301 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001302 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001303 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001304 SCS.Second = ICK_Complex_Conversion;
1305 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001306 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1307 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-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 Gregor0c293ea2010-06-22 23:07:26 +00001311 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001312 // Floating point conversions (C++ 4.8).
1313 SCS.Second = ICK_Floating_Conversion;
1314 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001315 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001316 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001317 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001318 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001319 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001320 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001321 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001322 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-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 McCall120d63c2010-08-24 20:38:10 +00001327 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1328 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001329 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001330 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001331 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001332 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001333 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001334 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001335 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001336 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001337 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001338 SCS.Second = SecondICK;
1339 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001340 } else if (!S.getLangOptions().CPlusPlus &&
1341 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001342 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001343 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001344 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001345 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001346 // Treat a conversion that strips "noreturn" as an identity conversion.
1347 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-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 Gregor8e9bebd2008-10-21 16:13:35 +00001353 } else {
1354 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001355 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001356 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001357 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001358
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001359 QualType CanonFrom;
1360 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001361 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001362 bool ObjCLifetimeConversion;
1363 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1364 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001365 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001366 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001367 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001368 CanonFrom = S.Context.getCanonicalType(FromType);
1369 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001370 } else {
1371 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001372 SCS.Third = ICK_Identity;
1373
Mike Stump1eb44332009-09-09 15:08:12 +00001374 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-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 McCall120d63c2010-08-24 20:38:10 +00001378 CanonFrom = S.Context.getCanonicalType(FromType);
1379 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001380 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001381 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001382 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001383 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1384 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001385 FromType = ToType;
1386 CanonFrom = CanonTo;
1387 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001388 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001389 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-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 Gregor27c8dc02008-10-29 00:13:59 +00001393 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001394 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001395
Douglas Gregor60d62c22008-10-31 16:23:19 +00001396 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001397}
Fariborz Jahaniand97f5582011-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 McCallf85e1932011-06-15 23:02:42 +00001415 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1416 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001417 ToType = it->getType();
1418 return true;
1419 }
1420 }
1421 return false;
1422}
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00001428bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001429 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001430 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001431 if (!To) {
1432 return false;
1433 }
Douglas Gregor8e9bebd2008-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 Gregoraa74a1e2010-02-02 20:10:50 +00001440 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1441 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00001446 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001447 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001448 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001449 }
1450
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001451 return To->getKind() == BuiltinType::UInt;
1452 }
1453
NAKAMURA Takumidfbb02a2011-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 Gregor0b8ddb92010-10-21 18:04:08 +00001460 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001461 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001462 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-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 Gregor0b8ddb92010-10-21 18:04:08 +00001465 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-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 Gregor0b8ddb92010-10-21 18:04:08 +00001472 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001473 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001474 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001475 return Context.hasSameUnqualifiedType(ToType,
1476 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001477 }
John McCall842aef82009-12-09 09:09:27 +00001478
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001479 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-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 Gregor0b8ddb92010-10-21 18:04:08 +00001483 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001484 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001485 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001486 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001487 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001488 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001489 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001490 // Determine whether the type we're converting from is signed or
1491 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001492 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001493 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001494
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00001497 QualType PromoteTypes[6] = {
1498 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001499 Context.LongTy, Context.UnsignedLongTy ,
1500 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001502 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001503 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1504 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001505 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-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 Gregora4923eb2009-11-16 21:35:15 +00001510 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-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 Stump390b4cc2009-05-16 07:39:55 +00001522 // FIXME: We should delay checking of bit-fields until we actually perform the
1523 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001524 using llvm::APSInt;
1525 if (From)
1526 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001527 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001528 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001529 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1530 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1531 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001532
Douglas Gregor86f19402008-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 Stump1eb44332009-09-09 15:08:12 +00001538
Douglas Gregor86f19402008-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 Stump1eb44332009-09-09 15:08:12 +00001544
Douglas Gregor86f19402008-12-20 23:49:58 +00001545 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001546 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001547 }
Mike Stump1eb44332009-09-09 15:08:12 +00001548
Douglas Gregor8e9bebd2008-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 Redl07779722008-10-31 14:43:28 +00001551 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001552 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001553 }
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00001561bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001562 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1563 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-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 Gregor8e9bebd2008-10-21 16:13:35 +00001566 if (FromBuiltin->getKind() == BuiltinType::Float &&
1567 ToBuiltin->getKind() == BuiltinType::Double)
1568 return true;
1569
Douglas Gregor5cdf8212009-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 Korobeynikovaa4a99b2011-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 Gregor5cdf8212009-02-12 00:15:05 +00001583 }
1584
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001585 return false;
1586}
1587
Douglas Gregor5cdf8212009-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 Gregorb7b5d132009-02-12 00:26:06 +00001592/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001593bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001594 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001595 if (!FromComplex)
1596 return false;
1597
John McCall183700f2009-09-21 23:43:11 +00001598 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001599 if (!ToComplex)
1600 return false;
1601
1602 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001603 ToComplex->getElementType()) ||
1604 IsIntegralPromotion(0, FromComplex->getElementType(),
1605 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001606}
1607
Douglas Gregorcb7de522008-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 McCallf85e1932011-06-15 23:02:42 +00001613///
Mike Stump1eb44332009-09-09 15:08:12 +00001614static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001615BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001616 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001617 ASTContext &Context,
1618 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001619 assert((FromPtr->getTypeClass() == Type::Pointer ||
1620 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1621 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001622
John McCallf85e1932011-06-15 23:02:42 +00001623 /// Conversions to 'id' subsume cv-qualifier conversions.
1624 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001625 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001626
1627 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001628 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001629 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001630 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001631
John McCallf85e1932011-06-15 23:02:42 +00001632 if (StripObjCLifetime)
1633 Quals.removeObjCLifetime();
1634
Mike Stump1eb44332009-09-09 15:08:12 +00001635 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001636 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001637 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001638 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001639 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001640
1641 // Build a pointer to ToPointee. It has the right qualifiers
1642 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001643 if (isa<ObjCObjectPointerType>(ToType))
1644 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001645 return Context.getPointerType(ToPointee);
1646 }
1647
1648 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001649 QualType QualifiedCanonToPointee
1650 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001651
Douglas Gregorda80f742010-12-01 21:43:58 +00001652 if (isa<ObjCObjectPointerType>(ToType))
1653 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1654 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001655}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001656
Mike Stump1eb44332009-09-09 15:08:12 +00001657static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-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 Gregor2ade35e2010-06-16 00:17:44 +00001663 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001664 return !InOverloadResolution;
1665
Douglas Gregorce940492009-09-25 04:25:58 +00001666 return Expr->isNullPointerConstant(Context,
1667 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1668 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001669}
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Douglas Gregor8e9bebd2008-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 Gregor071f2ae2008-11-27 00:15:41 +00001677///
Douglas Gregor7ca09762008-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 Gregor45920e82008-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 Gregor8e9bebd2008-10-21 16:13:35 +00001687bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001688 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001689 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001690 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001691 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001692 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1693 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001694 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001695
Mike Stump1eb44332009-09-09 15:08:12 +00001696 // Conversion from a null pointer constant to any Objective-C pointer type.
1697 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001698 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001699 ConvertedType = ToType;
1700 return true;
1701 }
1702
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001703 // Blocks: Block pointers can be converted to void*.
1704 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001705 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-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 Stump1eb44332009-09-09 15:08:12 +00001711 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001712 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001713 ConvertedType = ToType;
1714 return true;
1715 }
1716
Sebastian Redl6e8ed162009-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 Stump1eb44332009-09-09 15:08:12 +00001719 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001720 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001721 ConvertedType = ToType;
1722 return true;
1723 }
1724
Ted Kremenek6217b802009-07-29 21:53:49 +00001725 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-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 Carlssonbbf306b2009-08-28 15:55:56 +00001730 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001731 ConvertedType = ToType;
1732 return true;
1733 }
Sebastian Redl07779722008-10-31 14:43:28 +00001734
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001735 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001736 // , including objective-c pointers.
1737 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001738 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1739 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001740 ConvertedType = BuildSimilarlyQualifiedPointerType(
1741 FromType->getAs<ObjCObjectPointerType>(),
1742 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001743 ToType, Context);
1744 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001745 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001746 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001747 if (!FromTypePtr)
1748 return false;
1749
1750 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001751
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001752 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-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 Gregor8e9bebd2008-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 Friedman13578692010-08-05 02:49:48 +00001760 if (FromPointeeType->isIncompleteOrObjectType() &&
1761 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001762 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001763 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001764 ToType, Context,
1765 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001766 return true;
1767 }
1768
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001769 // MSVC allows implicit function to void* type conversion.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001770 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001771 ToPointeeType->isVoidType()) {
1772 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1773 ToPointeeType,
1774 ToType, Context);
1775 return true;
1776 }
1777
Douglas Gregorf9201e02009-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 Stump1eb44332009-09-09 15:08:12 +00001780 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001781 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001782 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001783 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001784 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001785 return true;
1786 }
1787
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001788 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001789 //
Douglas Gregorbc0805a2008-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 Gregor94b1dd22008-10-24 04:54:22 +00001799 // Note that we do not check for ambiguity or inaccessibility
1800 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001801 if (getLangOptions().CPlusPlus &&
1802 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001803 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001804 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001805 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001806 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001807 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001808 ToType, Context);
1809 return true;
1810 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001811
Fariborz Jahanian5da3c082011-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 Gregorc7887512008-12-19 19:13:09 +00001820 return false;
1821}
Douglas Gregor028ea4b2011-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 Gregorc7887512008-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 Stump1eb44332009-09-09 15:08:12 +00001840bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001841 QualType& ConvertedType,
1842 bool &IncompatibleObjC) {
1843 if (!getLangOptions().ObjC1)
1844 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001845
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001846 // The set of qualifiers on the type we're converting from.
1847 Qualifiers FromQualifiers = FromType.getQualifiers();
1848
Steve Naroff14108da2009-07-10 23:34:53 +00001849 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001850 const ObjCObjectPointerType* ToObjCPtr =
1851 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001852 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001853 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001854
Steve Naroff14108da2009-07-10 23:34:53 +00001855 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-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 Gregor028ea4b2011-04-26 23:16:46 +00001862 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00001863 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001864 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001865 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001866 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001867 return true;
1868 }
1869 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001870 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001871 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001872 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001873 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001874 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-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 Jahanianee9ca692010-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 Takumidfbb02a2011-01-27 07:10:08 +00001886 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001887 ToObjCPtr->getPointeeType(),
1888 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001889 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-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 Takumidfbb02a2011-01-27 07:10:08 +00001898 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001899 ToObjCPtr->getPointeeType(),
1900 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001901 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001902 return true;
1903 }
Mike Stump1eb44332009-09-09 15:08:12 +00001904 }
Steve Naroff14108da2009-07-10 23:34:53 +00001905 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001906 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001907 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001908 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001909 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001910 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001911 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001912 // to a block pointer type.
1913 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001914 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001915 return true;
1916 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001917 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001918 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001919 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001920 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001922 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001923 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001924 return true;
1925 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001926 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001927 return false;
1928
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001929 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001930 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001931 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001932 else if (const BlockPointerType *FromBlockPtr =
1933 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001934 FromPointeeType = FromBlockPtr->getPointeeType();
1935 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001936 return false;
1937
Douglas Gregorc7887512008-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 Gregorda80f742010-12-01 21:43:58 +00001945 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001946 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00001947 return true;
1948 }
Fariborz Jahanian83b7b312010-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 McCallf85e1932011-06-15 23:02:42 +00001955
Douglas Gregorda80f742010-12-01 21:43:58 +00001956 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001957 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001958 return true;
1959 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001960
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001961 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-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 Stump1eb44332009-09-09 15:08:12 +00001965 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001966 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001967 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001968 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-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 Stump1eb44332009-09-09 15:08:12 +00001996
Douglas Gregorc7887512008-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 Gregor028ea4b2011-04-26 23:16:46 +00002018 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002019 IncompatibleObjC = true;
2020 return true;
2021 }
2022 }
2023
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002024 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002025}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002026
John McCallf85e1932011-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 Jahaniane3c8c642011-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 Jahanian569bd8f2011-02-13 20:01:48 +00002118 if (!FromFunctionType || !ToFunctionType)
2119 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002120
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002121 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002122 return true;
Fariborz Jahanian569bd8f2011-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 Jahanian462dae52011-02-13 20:11:42 +00002136 if (Context.hasSameType(FromFunctionType->getResultType(),
2137 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-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 Jahanian78213e42011-09-28 21:52:05 +00002175 if (LangOpts.ObjCAutoRefCount &&
2176 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2177 ToFunctionType))
2178 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002179
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002180 ConvertedType = ToType;
2181 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002182}
2183
Richard Trieu6efd4c52011-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 Trieua6dc7ef2011-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 Trieu6efd4c52011-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 Trieu6efd4c52011-11-23 22:32:32 +00002215 }
2216
Richard Trieua6dc7ef2011-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 Trieu6efd4c52011-11-23 22:32:32 +00002223 FromType = FromType.getNonReferenceType();
2224 ToType = ToType.getNonReferenceType();
2225
Richard Trieu6efd4c52011-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 Trieua6dc7ef2011-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 Trieu6efd4c52011-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 Jahaniand8d34412010-05-03 21:06:18 +00002282/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002283/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-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 Trieu6efd4c52011-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 Takumidfbb02a2011-01-27 07:10:08 +00002288bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-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 Takumidfbb02a2011-01-27 07:10:08 +00002302
Fariborz Jahaniand8d34412010-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 Trieu6efd4c52011-11-23 22:32:32 +00002308 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002309 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2310 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002311 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2312 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2313 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2314 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002315 continue;
2316 }
John McCallc12c5bb2010-05-15 11:32:37 +00002317 else if (const ObjCObjectPointerType *PTTo =
2318 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002319 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002320 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002321 if (Context.hasSameUnqualifiedType(
2322 PTTo->getObjectType()->getBaseType(),
2323 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002324 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002325 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002326 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002327 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002328 }
2329 }
2330 return true;
2331}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002332
Douglas Gregor94b1dd22008-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 Redl9cc11e72009-07-25 15:41:38 +00002335/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-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 Carlsson61faec12009-09-12 04:46:44 +00002339bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002340 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002341 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002342 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002343 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002344 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002345
John McCalldaa8e4e2010-11-15 09:13:47 +00002346 Kind = CK_BitCast;
2347
Chandler Carruth88f0aed2011-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 Carruthb6006692011-04-09 07:48:17 +00002352 PDiag(diag::warn_impcast_bool_to_null_pointer)
2353 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002354
John McCall1d9b3b22011-09-09 05:25:32 +00002355 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2356 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002357 QualType FromPointeeType = FromPtrType->getPointeeType(),
2358 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002359
Douglas Gregor5fccd362010-03-03 23:55:11 +00002360 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2361 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002362 // We must have a derived-to-base conversion. Check an
2363 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002364 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2365 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002366 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002367 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002368 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002369
Anders Carlsson61faec12009-09-12 04:46:44 +00002370 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002371 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002372 }
2373 }
John McCall1d9b3b22011-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 Naroff14108da2009-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 Naroffde2e22d2009-07-15 18:40:39 +00002381 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002382 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002383 } else if (FromType->isBlockPointerType()) {
2384 Kind = CK_BlockPointerToObjCPointerCast;
2385 } else {
2386 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002387 }
John McCall1d9b3b22011-09-09 05:25:32 +00002388 } else if (ToType->isBlockPointerType()) {
2389 if (!FromType->isBlockPointerType())
2390 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002391 }
John McCalldaa8e4e2010-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 Gregor94b1dd22008-10-24 04:54:22 +00002398 return false;
2399}
2400
Sebastian Redl4433aaf2009-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 Takumidfbb02a2011-01-27 07:10:08 +00002407 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002408 bool InOverloadResolution,
2409 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002410 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-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 Gregorce940492009-09-25 04:25:58 +00002415 if (From->isNullPointerConstant(Context,
2416 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2417 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002418 ConvertedType = ToType;
2419 return true;
2420 }
2421
2422 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002423 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-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 Redl4433aaf2009-01-25 19:43:20 +00002431
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002432 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2433 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2434 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002435 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2436 ToClass.getTypePtr());
2437 return true;
2438 }
2439
2440 return false;
2441}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002442
Sebastian Redl4433aaf2009-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 McCall6b2accb2010-02-10 09:31:12 +00002445/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-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 Stump1eb44332009-09-09 15:08:12 +00002449bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002450 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002451 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002452 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002453 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002454 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002455 if (!FromPtrType) {
2456 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002457 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002458 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002459 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002460 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002461 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002462 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002463
Ted Kremenek6217b802009-07-29 21:53:49 +00002464 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002465 assert(ToPtrType && "No member pointer cast has a target type "
2466 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002467
Sebastian Redl21593ac2009-01-28 18:33:18 +00002468 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2469 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002470
Sebastian Redl21593ac2009-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 Redl4433aaf2009-01-25 19:43:20 +00002474
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002475 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002476 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-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 Redl4433aaf2009-01-25 19:43:20 +00002481
Sebastian Redl21593ac2009-01-28 18:33:18 +00002482 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2483 getUnqualifiedType())) {
Sebastian Redl21593ac2009-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 Redl4433aaf2009-01-25 19:43:20 +00002488 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002489
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002490 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-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 McCall6b2accb2010-02-10 09:31:12 +00002497 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002498 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2499 Paths.front(),
2500 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002501
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002502 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002503 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002504 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002505 return false;
2506}
2507
Douglas Gregor98cd5992008-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 McCallf85e1932011-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 Stump1eb44332009-09-09 15:08:12 +00002515bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002516Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002517 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002518 FromType = Context.getCanonicalType(FromType);
2519 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002520 ObjCLifetimeConversion = false;
2521
Douglas Gregor98cd5992008-10-21 23:43:52 +00002522 // If FromType and ToType are the same type, this is not a
2523 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002524 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002525 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002526
Douglas Gregor98cd5992008-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 Gregor98cd5992008-10-21 23:43:52 +00002531 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002532 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-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 Gregorf8268ae2008-10-22 17:49:05 +00002536 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002537 // until there are no more pointers or pointers-to-members left to
2538 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002539 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002540
Douglas Gregor621c92a2011-04-25 18:40:17 +00002541 Qualifiers FromQuals = FromType.getQualifiers();
2542 Qualifiers ToQuals = ToType.getQualifiers();
2543
John McCallf85e1932011-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 Gregor377e1bd2011-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 Gregor98cd5992008-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 Gregor621c92a2011-04-25 18:40:17 +00002568 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002569 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002570
Douglas Gregor98cd5992008-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 Gregor621c92a2011-04-25 18:40:17 +00002573 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002574 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002575 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002576
Douglas Gregor98cd5992008-10-21 23:43:52 +00002577 // Keep track of whether all prior cv-qualifiers in the "to" type
2578 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002579 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002580 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002581 }
Douglas Gregor98cd5992008-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 Gregora4923eb2009-11-16 21:35:15 +00002588 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002589}
2590
Douglas Gregor734d9862009-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 Gregor734d9862009-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 McCall120d63c2010-08-24 20:38:10 +00002601static OverloadingResult
2602IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2603 UserDefinedConversionSequence& User,
2604 OverloadCandidateSet& CandidateSet,
2605 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-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 Kremenek6217b802009-07-29 21:53:49 +00002611 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-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 McCall120d63c2010-08-24 20:38:10 +00002620 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002621 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002622 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002623 ConstructorsOnly = true;
2624
Argyrios Kyrtzidise36bca62011-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 Gregor393896f2009-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 Redlcf15cef2011-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 Gregorc1efaec2009-02-28 01:32:25 +00002645 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002646 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002647 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002648 NamedDecl *D = *Con;
2649 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2650
Douglas Gregordec06662009-08-21 18:42:58 +00002651 // Find the constructor (which may be a template).
2652 CXXConstructorDecl *Constructor = 0;
2653 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002654 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002655 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002656 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002657 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2658 else
John McCall9aa472c2010-03-19 07:35:19 +00002659 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002660
Sebastian Redlcf15cef2011-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 Gregordec06662009-08-21 18:42:58 +00002667 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002668 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2669 /*ExplicitArgs*/ 0,
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002670 Args, NumArgs, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002671 /*SuppressUserConversions=*/
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002672 !ConstructorsOnly &&
2673 !ListInitializing);
Douglas Gregordec06662009-08-21 18:42:58 +00002674 else
Fariborz Jahanian249cead2009-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 McCall120d63c2010-08-24 20:38:10 +00002677 S.AddOverloadCandidate(Constructor, FoundDecl,
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002678 Args, NumArgs, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002679 /*SuppressUserConversions=*/
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002680 !ConstructorsOnly && !ListInitializing);
Douglas Gregordec06662009-08-21 18:42:58 +00002681 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002682 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002683 }
2684 }
2685
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002686 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002687 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall120d63c2010-08-24 20:38:10 +00002688 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2689 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002690 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002691 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002692 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002693 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002694 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2695 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002696 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002697 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002698 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002699 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002700 DeclAccessPair FoundDecl = I.getPair();
2701 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-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 Jahanian8664ad52009-09-11 18:46:22 +00002706 CXXConversionDecl *Conv;
2707 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002708 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2709 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002710 else
John McCall32daa422010-03-31 01:36:47 +00002711 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002712
2713 if (AllowExplicit || !Conv->isExplicit()) {
2714 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002715 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2716 ActingContext, From, ToType,
2717 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002718 else
John McCall120d63c2010-08-24 20:38:10 +00002719 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2720 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002721 }
2722 }
2723 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002724 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002725
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002726 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2727
Douglas Gregor60d62c22008-10-31 16:23:19 +00002728 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002729 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-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 Carruth25ca4212011-02-25 19:41:05 +00002734 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2735
John McCall120d63c2010-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 Redlcf15cef2011-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 Gregor60d62c22008-10-31 16:23:19 +00002753 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002754 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002755 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00002756 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-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 Carruth25ca4212011-02-25 19:41:05 +00002763 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2764
John McCall120d63c2010-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 Bagnara7cc58b42011-10-05 07:56:41 +00002772 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002773 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00002774 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002775 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002776
John McCall120d63c2010-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 Jahanian34acd3e2009-09-15 19:12:21 +00002790 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002791 }
2792
John McCall120d63c2010-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 Takumidfbb02a2011-01-27 07:10:08 +00002798
John McCall120d63c2010-08-24 20:38:10 +00002799 case OR_Ambiguous:
2800 return OR_Ambiguous;
2801 }
2802
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002803 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002804}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002806bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002807Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002808 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002809 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002811 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002812 CandidateSet, false);
Fariborz Jahaniancc5306a2009-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 Jahanian17c7a5d2009-09-22 20:24:30 +00002822 return false;
John McCall120d63c2010-08-24 20:38:10 +00002823 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002824 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002825}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002826
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00002830static ImplicitConversionSequence::CompareKind
2831CompareImplicitConversionSequences(Sema &S,
2832 const ImplicitConversionSequence& ICS1,
2833 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00002843 //
John McCall1d318332010-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 Gregor3fbaf3e2010-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 Gregor8e9bebd2008-10-21 16:13:35 +00002853
Benjamin Kramerb6eee072010-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 Redlcc7a6482011-11-01 15:53:09 +00002859 ImplicitConversionSequence::CompareKind Result =
2860 ImplicitConversionSequence::Indistinguishable;
2861
Douglas Gregor8e9bebd2008-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 McCall1d318332010-01-12 00:44:57 +00002865 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002866 Result = CompareStandardConversionSequences(S,
2867 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002868 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +00002875 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002876 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002877 Result = CompareStandardConversionSequences(S,
2878 ICS1.UserDefined.After,
2879 ICS2.UserDefined.After);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002880 }
2881
Sebastian Redlcc7a6482011-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 Gregor8e9bebd2008-10-21 16:13:35 +00002892}
2893
Douglas Gregor5a57efd2010-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 Takumidfbb02a2011-01-27 07:10:08 +00002898 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002899 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002900
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002901 return Context.hasSameUnqualifiedType(T1, T2);
2902}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002903
Douglas Gregorad323a82010-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 Takumidfbb02a2011-01-27 07:10:08 +00002913 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002914 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-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 Takumidfbb02a2011-01-27 07:10:08 +00002919
Douglas Gregorad323a82010-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 Gregor5a57efd2010-06-09 03:53:18 +00002927 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-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 Takumidfbb02a2011-01-27 07:10:08 +00002944
Douglas Gregorad323a82010-01-27 03:51:04 +00002945 return ImplicitConversionSequence::Indistinguishable;
2946}
2947
Douglas Gregor440a4832011-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 Takumidfbb02a2011-01-27 07:10:08 +00002955 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00002956 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002957 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-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 Gregorfcab48b2011-01-26 19:41:18 +00002965 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2966 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2967 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002968
Douglas Gregor440a4832011-01-26 14:52:12 +00002969 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2970 SCS2.IsLvalueReference) ||
2971 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2972 !SCS2.IsLvalueReference);
2973}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002974
Douglas Gregor8e9bebd2008-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 McCall120d63c2010-08-24 20:38:10 +00002978static ImplicitConversionSequence::CompareKind
2979CompareStandardConversionSequences(Sema &S,
2980 const StandardConversionSequence& SCS1,
2981 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-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 Gregorad323a82010-01-27 03:51:04 +00002991 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002992 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002993 return CK;
Douglas Gregor8e9bebd2008-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 Gregor8e9bebd2008-10-21 16:13:35 +00003003
Douglas Gregor57373262008-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 Stump1eb44332009-09-09 15:08:12 +00003007
Douglas Gregor57373262008-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 Gregorbc0805a2008-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 Gregorf70bdb92008-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 Stump1eb44332009-09-09 15:08:12 +00003022 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003023 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003024 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003025 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-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 Gregorbc0805a2008-10-23 00:40:37 +00003029 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3030 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-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 Gregorbc0805a2008-10-23 00:40:37 +00003034 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003035 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003036 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003037 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3038 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-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 McCall1d318332010-01-12 00:44:57 +00003042 QualType FromType1 = SCS1.getFromType();
3043 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-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 McCall120d63c2010-08-24 20:38:10 +00003048 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003049 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003050 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003051
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003052 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3053 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003054
John McCall120d63c2010-08-24 20:38:10 +00003055 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003056 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003057 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-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 Gregor0f7b3dc2011-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 Gregor01919692009-12-13 21:37:05 +00003075 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003076 }
Douglas Gregor57373262008-10-22 14:17:15 +00003077
3078 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3079 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003080 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003081 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003082 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003083
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003084 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-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 Takumidfbb02a2011-01-27 07:10:08 +00003090
Sebastian Redlf2e21e52009-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 Gregorad323a82010-01-27 03:51:04 +00003097 QualType T1 = SCS1.getToType(2);
3098 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003099 T1 = S.Context.getCanonicalType(T1);
3100 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003101 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003102 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3103 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003104 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-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 Carruth6df868e2010-12-12 08:17:55 +00003114 // If the type is an array type, promote the element qualifiers to the
3115 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003116 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003117 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003118 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003119 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003120 if (T2.isMoreQualifiedThan(T1))
3121 return ImplicitConversionSequence::Better;
3122 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003123 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003124 }
3125 }
Douglas Gregor57373262008-10-22 14:17:15 +00003126
Francois Pichet1c98d622011-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 Gregor57373262008-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 Stump1eb44332009-09-09 15:08:12 +00003151/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3152ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003153CompareQualificationConversions(Sema &S,
3154 const StandardConversionSequence& SCS1,
3155 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003156 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-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 Gregorad323a82010-01-27 03:51:04 +00003168 QualType T1 = SCS1.getToType(2);
3169 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003170 T1 = S.Context.getCanonicalType(T1);
3171 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003172 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003173 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3174 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003175
3176 // If the types are the same, we won't learn anything by unwrapped
3177 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003178 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003179 return ImplicitConversionSequence::Indistinguishable;
3180
Chandler Carruth28e318c2009-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 McCall120d63c2010-08-24 20:38:10 +00003184 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003185 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003186 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003187
Mike Stump1eb44332009-09-09 15:08:12 +00003188 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003189 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-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 McCall120d63c2010-08-24 20:38:10 +00003201 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-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 Gregorf8268ae2008-10-22 17:49:05 +00003205 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-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 Stump1eb44332009-09-09 15:08:12 +00003220
Douglas Gregor57373262008-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 Stump1eb44332009-09-09 15:08:12 +00003228
Douglas Gregor57373262008-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 McCall120d63c2010-08-24 20:38:10 +00003236 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003237 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003238 }
3239
Douglas Gregor57373262008-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 Gregora9bff302010-02-28 18:30:25 +00003244 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003245 Result = ImplicitConversionSequence::Indistinguishable;
3246 break;
3247
3248 case ImplicitConversionSequence::Indistinguishable:
3249 break;
3250
3251 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003252 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003253 Result = ImplicitConversionSequence::Indistinguishable;
3254 break;
3255 }
3256
3257 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003258}
3259
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003260/// CompareDerivedToBaseConversions - Compares two standard conversion
3261/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-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 Gregorbc0805a2008-10-23 00:40:37 +00003265ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003266CompareDerivedToBaseConversions(Sema &S,
3267 const StandardConversionSequence& SCS1,
3268 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003269 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003270 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003271 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003272 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-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 McCall120d63c2010-08-24 20:38:10 +00003277 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003278 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003279 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003280
3281 // Canonicalize all of the types.
John McCall120d63c2010-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 Gregorbc0805a2008-10-23 00:40:37 +00003286
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003287 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-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 Gregorcb7de522008-11-26 23:31:11 +00003291 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003292 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003293 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-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 Stump1eb44332009-09-09 15:08:12 +00003298 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003299 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003300 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003301 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003302 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003303 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003304 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003305 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003306
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003307 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003308 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003309 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003310 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003311 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003312 return ImplicitConversionSequence::Worse;
3313 }
Douglas Gregorf70bdb92008-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 McCall120d63c2010-08-24 20:38:10 +00003317 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003318 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003319 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003320 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-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 Stump1eb44332009-09-09 15:08:12 +00003378
Douglas Gregor395cc372011-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 Gregorf70bdb92008-10-29 14:50:44 +00003391 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003392 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003393
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003394 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-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 Takumidfbb02a2011-01-27 07:10:08 +00003398 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003399 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003400 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003401 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003402 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003403 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003404 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-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 Jahanian2357da02009-10-20 20:07:35 +00003414 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003415 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003416 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003417 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003418 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-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 McCall120d63c2010-08-24 20:38:10 +00003423 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003424 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003425 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003426 return ImplicitConversionSequence::Worse;
3427 }
3428 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003429
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003430 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003431 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-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 McCall120d63c2010-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 Gregor225c41e2008-11-03 19:09:14 +00003438 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003439 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003440 return ImplicitConversionSequence::Worse;
3441 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003442
Douglas Gregor225c41e2008-11-03 19:09:14 +00003443 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-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 McCall120d63c2010-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 Gregor225c41e2008-11-03 19:09:14 +00003450 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003451 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003452 return ImplicitConversionSequence::Worse;
3453 }
3454 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003455
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003456 return ImplicitConversionSequence::Indistinguishable;
3457}
3458
Douglas Gregorabe183d2010-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 Gregor569c3162010-08-07 11:51:51 +00003469 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003470 bool &ObjCConversion,
3471 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-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 Gregor569c3162010-08-07 11:51:51 +00003486 DerivedToBase = false;
3487 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003488 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003489 if (UnqualT1 == UnqualT2) {
3490 // Nothing to do.
3491 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003492 IsDerivedFrom(UnqualT2, UnqualT1))
3493 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003494 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3495 UnqualT2->isObjCObjectOrInterfaceType() &&
3496 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3497 ObjCConversion = true;
Douglas Gregorabe183d2010-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 Gregora6ce3e62011-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 McCallf85e1932011-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 Gregora6ce3e62011-04-28 17:56:11 +00003530 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003531 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003532 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003533 return Ref_Compatible_With_Added_Qualification;
3534 else
3535 return Ref_Related;
3536}
3537
Douglas Gregor604eb652010-08-11 02:15:33 +00003538/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003539/// with DeclType. Return true if something definite is found.
3540static bool
Douglas Gregor604eb652010-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 Redl4680bf22010-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 Takumidfbb02a2011-01-27 07:10:08 +00003567 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003568 // explicit conversions, skip it.
3569 if (!AllowExplicit && Conv->isExplicit())
3570 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003571
Douglas Gregor604eb652010-08-11 02:15:33 +00003572 if (AllowRvalues) {
3573 bool DerivedToBase = false;
3574 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003575 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-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 Gregor604eb652010-08-11 02:15:33 +00003586 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003587 S.CompareReferenceRelationship(
3588 DeclLoc,
3589 Conv->getConversionType().getNonReferenceType()
3590 .getUnqualifiedType(),
3591 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003592 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003593 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-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 Redl4680bf22010-06-30 18:13:39 +00003606 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003607
Douglas Gregor604eb652010-08-11 02:15:33 +00003608 if (ConvTemplate)
3609 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003610 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003611 else
3612 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003613 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003614 }
3615
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003616 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3617
Sebastian Redl4680bf22010-06-30 18:13:39 +00003618 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003619 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-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 Carruth25ca4212011-02-25 19:41:05 +00003634 if (Best->Function)
3635 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003636 ICS.setUserDefined();
3637 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3638 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003639 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003640 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00003641 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-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 Takumidfbb02a2011-01-27 07:10:08 +00003662
Eric Christopher1c3d5022010-06-30 18:36:32 +00003663 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003664}
3665
Douglas Gregorabe183d2010-04-13 16:31:36 +00003666/// \brief Compute an implicit conversion sequence for reference
3667/// initialization.
3668static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00003669TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003670 SourceLocation DeclLoc,
3671 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003672 bool AllowExplicit) {
Douglas Gregorabe183d2010-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 Gregor569c3162010-08-07 11:51:51 +00003695 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003696 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003697 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003698 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003699 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003700 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003701
Douglas Gregorabe183d2010-04-13 16:31:36 +00003702
Sebastian Redl4680bf22010-06-30 18:13:39 +00003703 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-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 Redl4680bf22010-06-30 18:13:39 +00003707 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003708 if (!isRValRef) {
Sebastian Redl4680bf22010-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 Gregorabe183d2010-04-13 16:31:36 +00003715 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-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 Gregor569c3162010-08-07 11:51:51 +00003724 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3725 : ObjCConversion? ICK_Compatible_Conversion
3726 : ICK_Identity;
Sebastian Redl4680bf22010-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 Gregor440a4832011-01-26 14:52:12 +00003734 ICS.Standard.IsLvalueReference = !isRValRef;
3735 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3736 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003737 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003738 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003739 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003740
Sebastian Redl4680bf22010-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 Gregorabe183d2010-04-13 16:31:36 +00003745 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003746 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003747
Sebastian Redl4680bf22010-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 Takumidfbb02a2011-01-27 07:10:08 +00003756 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003757 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003758 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3759 Init, T2, /*AllowRvalues=*/false,
3760 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00003761 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003762 }
3763 }
3764
Sebastian Redl4680bf22010-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 Gregor8dde14e2011-01-24 16:14:37 +00003767 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003768 //
Douglas Gregor66821b52010-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 Redl4680bf22010-06-30 18:13:39 +00003776 // This is also the point where rvalue references and lvalue inits no longer
3777 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003778 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00003779 return ICS;
3780
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003781 // -- If the initializer expression
3782 //
3783 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00003784 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-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 Takumidfbb02a2011-01-27 07:10:08 +00003791 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-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 Takumidfbb02a2011-01-27 07:10:08 +00003805 ICS.Standard.DirectBinding =
3806 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003807 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00003808 ICS.Standard.IsLvalueReference = !isRValRef;
3809 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003810 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003811 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003812 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003813 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003815 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816
Douglas Gregor8dde14e2011-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 Takumidfbb02a2011-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 Gregor8dde14e2011-01-24 16:14:37 +00003821 // "cv3 T3",
3822 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003823 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003824 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003825 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003826 // class subobject).
3827 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003828 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-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 Takumidfbb02a2011-01-27 07:10:08 +00003836 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003837 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3838 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3839
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003840 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00003841 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003842
Douglas Gregorabe183d2010-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 McCallf85e1932011-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 Gregorabe183d2010-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 Gregor2ad746a2011-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 Gregorabe183d2010-04-13 16:31:36 +00003883 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-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 McCall120d63c2010-08-24 20:38:10 +00003893 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3894 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003895 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003896 /*CStyle=*/false,
3897 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-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 Gregor440a4832011-01-26 14:52:12 +00003902 ICS.Standard.IsLvalueReference = !isRValRef;
3903 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3904 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003905 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003906 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003907 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-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 Gregorabe183d2010-04-13 16:31:36 +00003921 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-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 Gregorabe183d2010-04-13 16:31:36 +00003927 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003928
Douglas Gregorabe183d2010-04-13 16:31:36 +00003929 return ICS;
3930}
3931
Sebastian Redl5405b812011-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 Redlcc7a6482011-11-01 15:53:09 +00003951 Result.setListInitializationSequence();
Sebastian Redl5405b812011-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 Redlcf15cef2011-12-22 18:58:38 +00003959 // FIXME: Implement arrays.
Sebastian Redl5405b812011-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 Redlcf15cef2011-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 Redl5405b812011-10-16 18:19:34 +00003976 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003977 }
Sebastian Redl5405b812011-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 Redl5405b812011-10-16 18:19:34 +00003983 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-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 Redl5405b812011-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 Redl1cdb70b2011-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 Redl5405b812011-10-16 18:19:34 +00004069 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004070 }
Sebastian Redl5405b812011-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 Gregor27c8dc02008-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 Gregor225c41e2008-11-03 19:09:14 +00004103/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004104/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004105static ImplicitConversionSequence
4106TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004107 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004108 bool InOverloadResolution,
4109 bool AllowObjCWritebackConversion) {
Sebastian Redl5405b812011-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 Gregorabe183d2010-04-13 16:31:36 +00004114 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004115 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004116 /*FIXME:*/From->getLocStart(),
4117 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004118 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004119
John McCall120d63c2010-08-24 20:38:10 +00004120 return TryImplicitConversion(S, From, ToType,
4121 SuppressUserConversions,
4122 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004123 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004124 /*CStyle=*/false,
4125 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004126}
4127
Anna Zaksf3546ee2011-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 Gregor96176b32008-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 McCall120d63c2010-08-24 20:38:10 +00004143static ImplicitConversionSequence
4144TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004145 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004146 CXXMethodDecl *Method,
4147 CXXRecordDecl *ActingContext) {
4148 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-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 McCall120d63c2010-08-24 20:38:10 +00004153 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-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 Gregor96176b32008-11-18 23:14:02 +00004158
4159 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004160 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004161 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004162 FromType = PT->getPointeeType();
4163
Douglas Gregor2c9a03f2011-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 Carlssona552f7c2009-05-01 18:34:30 +00004169 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004170
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004171 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004172 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004173 // parameter is
4174 //
NAKAMURA Takumi00995302011-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 Gregor2c9a03f2011-01-26 19:30:28 +00004178 // ref-qualifier
4179 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004180 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004181 // cv-qualification on the member function declaration.
4182 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004183 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004184 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-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 Gregor2c9a03f2011-01-26 19:30:28 +00004189 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004190 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004191 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004192 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004193 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004194 ICS.setBad(BadConversionSequence::bad_qualifiers,
4195 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004196 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004197 }
Douglas Gregor96176b32008-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 McCall120d63c2010-08-24 20:38:10 +00004201 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004202 ImplicitConversionKind SecondKind;
4203 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4204 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004205 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004206 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004207 else {
John McCallb1bdc622010-02-25 01:37:24 +00004208 ICS.setBad(BadConversionSequence::unrelated_class,
4209 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004210 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004211 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004212
Douglas Gregor2c9a03f2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004218
Douglas Gregor2c9a03f2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004222 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-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 Takumidfbb02a2011-01-27 07:10:08 +00004231 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004232 ImplicitParamType);
4233 return ICS;
4234 }
4235 break;
4236 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004237
Douglas Gregor96176b32008-11-18 23:14:02 +00004238 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004239 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004240 ICS.Standard.setAsIdentityConversion();
4241 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004242 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004243 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004244 ICS.Standard.ReferenceBinding = true;
4245 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004247 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004248 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4249 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4250 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-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 Wiegley429bb272011-04-08 18:41:53 +00004257ExprResult
4258Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004259 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004260 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004261 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004262 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004263 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004264 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004265
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004266 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004267 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004268 FromRecordType = PT->getPointeeType();
4269 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004270 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004271 } else {
4272 FromRecordType = From->getType();
4273 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004274 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004275 }
4276
John McCall701c89e2009-12-03 04:06:58 +00004277 // Note that we always use the true parent context when performing
4278 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004279 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004280 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4281 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-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 Wiegley429bb272011-04-08 18:41:53 +00004294 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004295 }
4296 }
4297
Douglas Gregor96176b32008-11-18 23:14:02 +00004298 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004299 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004300 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004301 }
Mike Stump1eb44332009-09-09 15:08:12 +00004302
John Wiegley429bb272011-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 Gregor96176b32008-11-18 23:14:02 +00004310
Douglas Gregor5fccd362010-03-03 23:55:11 +00004311 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004312 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004313 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004314 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004315}
4316
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004317/// TryContextuallyConvertToBool - Attempt to contextually convert the
4318/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004319static ImplicitConversionSequence
4320TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004321 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004322 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004323 // FIXME: Are these flags correct?
4324 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004325 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004326 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004327 /*CStyle=*/false,
4328 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-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 Wiegley429bb272011-04-08 18:41:53 +00004333ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004334 if (checkPlaceholderForOverload(*this, From))
4335 return ExprError();
4336
John McCall120d63c2010-08-24 20:38:10 +00004337 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004338 if (!ICS.isBad())
4339 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004340
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004341 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00004342 return Diag(From->getSourceRange().getBegin(),
4343 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004344 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004345 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004346}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004347
John McCall0bcc9bc2011-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 Jahanian79d3f042010-05-12 23:29:11 +00004357}
John McCall120d63c2010-08-24 20:38:10 +00004358
John McCall0bcc9bc2011-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 McCall3c3b7f92011-10-25 17:37:35 +00004396 if (checkPlaceholderForOverload(*this, From))
4397 return ExprError();
4398
John McCallc12c5bb2010-05-15 11:32:37 +00004399 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004400 ImplicitConversionSequence ICS =
4401 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004402 if (!ICS.isBad())
4403 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004404 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004405}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004406
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004407/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-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 Gregor6bc574d2010-06-30 00:20:43 +00004414/// \param Loc The source location of the construct that requires the
4415/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004416///
Douglas Gregor6bc574d2010-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 Takumidfbb02a2011-01-27 07:10:08 +00004435/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-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 Takumidfbb02a2011-01-27 07:10:08 +00004443ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004444Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-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 Gregor6bc574d2010-06-30 00:20:43 +00004450 const PartialDiagnostic &AmbigNote,
4451 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004452 // We can't perform any more checking for type-dependent expressions.
4453 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00004454 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004455
Douglas Gregorc30614b2010-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 McCall9ae2f072010-08-23 23:25:46 +00004459 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004460
4461 // FIXME: Check for missing '()' if T is a function type?
4462
NAKAMURA Takumidfbb02a2011-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 Gregorc30614b2010-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 McCall9ae2f072010-08-23 23:25:46 +00004469 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004470 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004471
Douglas Gregorc30614b2010-06-29 23:17:37 +00004472 // We must have a complete class type.
4473 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00004474 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475
Douglas Gregorc30614b2010-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 Takumidfbb02a2011-01-27 07:10:08 +00004481
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004482 bool HadMultipleCandidates = (Conversions->size() > 1);
4483
Douglas Gregorc30614b2010-06-29 23:17:37 +00004484 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004485 E = Conversions->end();
4486 I != E;
Douglas Gregorc30614b2010-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 Takumidfbb02a2011-01-27 07:10:08 +00004498
Douglas Gregorc30614b2010-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 Takumidfbb02a2011-01-27 07:10:08 +00004505
Douglas Gregorc30614b2010-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 Gregor8987b232011-09-27 23:30:47 +00004511 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512
Douglas Gregorc30614b2010-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 Takumidfbb02a2011-01-27 07:10:08 +00004521
4522 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00004523 // explicit conversion function.
4524 if (isSFINAEContext())
4525 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004526
Douglas Gregorc30614b2010-06-29 23:17:37 +00004527 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004528 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4529 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004530 if (Result.isInvalid())
4531 return ExprError();
Abramo Bagnara960809e2011-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 Gregorc30614b2010-06-29 23:17:37 +00004537 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004538
Douglas Gregorc30614b2010-06-29 23:17:37 +00004539 // We'll complain below about a non-integral condition type.
4540 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004541
Douglas Gregorc30614b2010-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 Takumidfbb02a2011-01-27 07:10:08 +00004546
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004547 CXXConversionDecl *Conversion
4548 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4549 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004550 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004551 if (ConvDiag.getDiagID()) {
4552 if (isSFINAEContext())
4553 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004554
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004555 Diag(Loc, ConvDiag)
4556 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4557 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004558
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004559 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4560 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004561 if (Result.isInvalid())
4562 return ExprError();
Abramo Bagnara960809e2011-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 Gregorc30614b2010-06-29 23:17:37 +00004568 break;
4569 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004570
Douglas Gregorc30614b2010-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 McCall9ae2f072010-08-23 23:25:46 +00004581 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004582 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004583
Douglas Gregoracb0bd82010-06-29 23:25:20 +00004584 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00004585 Diag(Loc, NotIntDiag)
4586 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004587
John McCall9ae2f072010-08-23 23:25:46 +00004588 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004589}
4590
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004591/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-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 Gregor9c6a0e92009-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 Stump1eb44332009-09-09 15:08:12 +00004599void
4600Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00004601 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004602 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00004603 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00004604 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004605 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00004606 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004607 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004608 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00004609 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004610 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00004611
Douglas Gregor88a35142008-12-22 05:46:06 +00004612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-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 McCall701c89e2009-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 McCall9aa472c2010-03-19 07:35:19 +00004621 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004622 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004623 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004624 SuppressUserConversions);
Sebastian Redl3201f6b2009-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 Gregor88a35142008-12-22 05:46:06 +00004629 }
4630
Douglas Gregorfd476482009-11-13 23:59:09 +00004631 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00004632 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00004633
Douglas Gregor7edfb692009-11-23 12:27:39 +00004634 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004635 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004636
Douglas Gregor66724ea2009-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 Takumidfbb02a2011-01-27 07:10:08 +00004642 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00004643 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00004644 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4645 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00004646 return;
4647 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004648
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004649 // Add this candidate
4650 CandidateSet.push_back(OverloadCandidate());
4651 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004652 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004653 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00004654 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004655 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004656 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004657 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004659 unsigned NumArgsInProto = Proto->getNumArgs();
4660
4661 // (C++ 13.3.2p2): A candidate function having fewer than m
4662 // parameters is viable only if it has an ellipsis in its parameter
4663 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004664 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00004665 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004666 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004667 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004668 return;
4669 }
4670
4671 // (C++ 13.3.2p2): A candidate function having more than m parameters
4672 // is viable only if the (m+1)st parameter has a default argument
4673 // (8.3.6). For the purposes of overload resolution, the
4674 // parameter list is truncated on the right, so that there are
4675 // exactly m parameters.
4676 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004677 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004678 // Not enough arguments.
4679 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004680 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004681 return;
4682 }
4683
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00004684 // (CUDA B.1): Check for invalid calls between targets.
4685 if (getLangOptions().CUDA)
4686 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4687 if (CheckCUDATarget(Caller, Function)) {
4688 Candidate.Viable = false;
4689 Candidate.FailureKind = ovl_fail_bad_target;
4690 return;
4691 }
4692
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004693 // Determine the implicit conversion sequences for each of the
4694 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004695 Candidate.Conversions.resize(NumArgs);
4696 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4697 if (ArgIdx < NumArgsInProto) {
4698 // (C++ 13.3.2p3): for F to be a viable function, there shall
4699 // exist for each argument an implicit conversion sequence
4700 // (13.3.3.1) that converts that argument to the corresponding
4701 // parameter of F.
4702 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004703 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004704 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004705 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004706 /*InOverloadResolution=*/true,
4707 /*AllowObjCWritebackConversion=*/
4708 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004709 if (Candidate.Conversions[ArgIdx].isBad()) {
4710 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004711 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00004712 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00004713 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004714 } else {
4715 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4716 // argument for which there is no corresponding parameter is
4717 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004718 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004719 }
4720 }
4721}
4722
Douglas Gregor063daf62009-03-13 18:40:31 +00004723/// \brief Add all of the function declarations in the given function set to
4724/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00004725void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00004726 Expr **Args, unsigned NumArgs,
4727 OverloadCandidateSet& CandidateSet,
4728 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00004729 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00004730 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4731 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004732 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004733 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004734 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004735 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004736 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004737 CandidateSet, SuppressUserConversions);
4738 else
John McCall9aa472c2010-03-19 07:35:19 +00004739 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00004740 SuppressUserConversions);
4741 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004742 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00004743 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4744 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004745 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004746 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00004747 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004748 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004749 Args[0]->Classify(Context),
4750 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004751 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00004752 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00004753 else
John McCall9aa472c2010-03-19 07:35:19 +00004754 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00004755 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00004756 Args, NumArgs, CandidateSet,
4757 SuppressUserConversions);
4758 }
Douglas Gregor364e0212009-06-27 21:05:07 +00004759 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004760}
4761
John McCall314be4e2009-11-17 07:50:12 +00004762/// AddMethodCandidate - Adds a named decl (which is some kind of
4763/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00004764void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004765 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004766 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00004767 Expr **Args, unsigned NumArgs,
4768 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004769 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00004770 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00004771 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00004772
4773 if (isa<UsingShadowDecl>(Decl))
4774 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004775
John McCall314be4e2009-11-17 07:50:12 +00004776 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4777 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4778 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00004779 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4780 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004781 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00004782 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004783 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004784 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004785 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004786 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004787 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004788 }
4789}
4790
Douglas Gregor96176b32008-11-18 23:14:02 +00004791/// AddMethodCandidate - Adds the given C++ member function to the set
4792/// of candidate functions, using the given function call arguments
4793/// and the object argument (@c Object). For example, in a call
4794/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4795/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4796/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00004797/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00004798void
John McCall9aa472c2010-03-19 07:35:19 +00004799Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00004800 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004801 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00004802 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00004803 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004804 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00004805 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004806 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00004807 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004808 assert(!isa<CXXConstructorDecl>(Method) &&
4809 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00004810
Douglas Gregor3f396022009-09-28 04:47:19 +00004811 if (!CandidateSet.isNewCandidate(Method))
4812 return;
4813
Douglas Gregor7edfb692009-11-23 12:27:39 +00004814 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004815 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004816
Douglas Gregor96176b32008-11-18 23:14:02 +00004817 // Add this candidate
4818 CandidateSet.push_back(OverloadCandidate());
4819 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004820 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00004821 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004822 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004823 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004824 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00004825
4826 unsigned NumArgsInProto = Proto->getNumArgs();
4827
4828 // (C++ 13.3.2p2): A candidate function having fewer than m
4829 // parameters is viable only if it has an ellipsis in its parameter
4830 // list (8.3.5).
4831 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4832 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004833 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004834 return;
4835 }
4836
4837 // (C++ 13.3.2p2): A candidate function having more than m parameters
4838 // is viable only if the (m+1)st parameter has a default argument
4839 // (8.3.6). For the purposes of overload resolution, the
4840 // parameter list is truncated on the right, so that there are
4841 // exactly m parameters.
4842 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4843 if (NumArgs < MinRequiredArgs) {
4844 // Not enough arguments.
4845 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004846 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004847 return;
4848 }
4849
4850 Candidate.Viable = true;
4851 Candidate.Conversions.resize(NumArgs + 1);
4852
John McCall701c89e2009-12-03 04:06:58 +00004853 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00004854 // The implicit object argument is ignored.
4855 Candidate.IgnoreObjectArgument = true;
4856 else {
4857 // Determine the implicit conversion sequence for the object
4858 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00004859 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004860 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4861 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004862 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004863 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004864 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00004865 return;
4866 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004867 }
4868
4869 // Determine the implicit conversion sequences for each of the
4870 // arguments.
4871 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4872 if (ArgIdx < NumArgsInProto) {
4873 // (C++ 13.3.2p3): for F to be a viable function, there shall
4874 // exist for each argument an implicit conversion sequence
4875 // (13.3.3.1) that converts that argument to the corresponding
4876 // parameter of F.
4877 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004878 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004879 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004880 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004881 /*InOverloadResolution=*/true,
4882 /*AllowObjCWritebackConversion=*/
4883 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004884 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004885 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004886 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004887 break;
4888 }
4889 } else {
4890 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4891 // argument for which there is no corresponding parameter is
4892 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004893 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00004894 }
4895 }
4896}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004897
Douglas Gregor6b906862009-08-21 00:16:32 +00004898/// \brief Add a C++ member function template as a candidate to the candidate
4899/// set, using template argument deduction to produce an appropriate member
4900/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004901void
Douglas Gregor6b906862009-08-21 00:16:32 +00004902Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00004903 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004904 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00004905 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00004906 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004907 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00004908 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004909 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004910 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004911 if (!CandidateSet.isNewCandidate(MethodTmpl))
4912 return;
4913
Douglas Gregor6b906862009-08-21 00:16:32 +00004914 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004915 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00004916 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004917 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00004918 // candidate functions in the usual way.113) A given name can refer to one
4919 // or more function templates and also to a set of overloaded non-template
4920 // functions. In such a case, the candidate functions generated from each
4921 // function template are combined with the set of non-template candidate
4922 // functions.
John McCall5769d612010-02-08 23:07:23 +00004923 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00004924 FunctionDecl *Specialization = 0;
4925 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004926 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004927 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004928 CandidateSet.push_back(OverloadCandidate());
4929 OverloadCandidate &Candidate = CandidateSet.back();
4930 Candidate.FoundDecl = FoundDecl;
4931 Candidate.Function = MethodTmpl->getTemplatedDecl();
4932 Candidate.Viable = false;
4933 Candidate.FailureKind = ovl_fail_bad_deduction;
4934 Candidate.IsSurrogate = false;
4935 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004936 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004937 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004938 Info);
4939 return;
4940 }
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Douglas Gregor6b906862009-08-21 00:16:32 +00004942 // Add the function template specialization produced by template argument
4943 // deduction as a candidate.
4944 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00004945 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00004946 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00004947 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004948 ActingContext, ObjectType, ObjectClassification,
4949 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00004950}
4951
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004952/// \brief Add a C++ function template specialization as a candidate
4953/// in the candidate set, using template argument deduction to produce
4954/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004955void
Douglas Gregore53060f2009-06-25 22:08:12 +00004956Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004957 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00004958 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00004959 Expr **Args, unsigned NumArgs,
4960 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004961 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004962 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4963 return;
4964
Douglas Gregore53060f2009-06-25 22:08:12 +00004965 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004966 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00004967 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004968 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00004969 // candidate functions in the usual way.113) A given name can refer to one
4970 // or more function templates and also to a set of overloaded non-template
4971 // functions. In such a case, the candidate functions generated from each
4972 // function template are combined with the set of non-template candidate
4973 // functions.
John McCall5769d612010-02-08 23:07:23 +00004974 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00004975 FunctionDecl *Specialization = 0;
4976 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004977 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004978 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00004979 CandidateSet.push_back(OverloadCandidate());
4980 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004981 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00004982 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4983 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004984 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00004985 Candidate.IsSurrogate = false;
4986 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004987 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004988 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004989 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00004990 return;
4991 }
Mike Stump1eb44332009-09-09 15:08:12 +00004992
Douglas Gregore53060f2009-06-25 22:08:12 +00004993 // Add the function template specialization produced by template argument
4994 // deduction as a candidate.
4995 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004996 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004997 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00004998}
Mike Stump1eb44332009-09-09 15:08:12 +00004999
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005000/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005001/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005002/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005003/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005004/// (which may or may not be the same type as the type that the
5005/// conversion function produces).
5006void
5007Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005008 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005009 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005010 Expr *From, QualType ToType,
5011 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005012 assert(!Conversion->getDescribedFunctionTemplate() &&
5013 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005014 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005015 if (!CandidateSet.isNewCandidate(Conversion))
5016 return;
5017
Douglas Gregor7edfb692009-11-23 12:27:39 +00005018 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005019 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005020
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005021 // Add this candidate
5022 CandidateSet.push_back(OverloadCandidate());
5023 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00005024 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005025 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005026 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005027 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005028 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005029 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005030 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005031 Candidate.Viable = true;
5032 Candidate.Conversions.resize(1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00005033 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005034
Douglas Gregorbca39322010-08-19 15:37:02 +00005035 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005036 // For conversion functions, the function is considered to be a member of
5037 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005038 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005039 //
5040 // Determine the implicit conversion sequence for the implicit
5041 // object parameter.
5042 QualType ImplicitParamType = From->getType();
5043 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5044 ImplicitParamType = FromPtrType->getPointeeType();
5045 CXXRecordDecl *ConversionContext
5046 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005047
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005048 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005049 = TryObjectArgumentInitialization(*this, From->getType(),
5050 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005051 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005052
John McCall1d318332010-01-12 00:44:57 +00005053 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005054 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005055 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005056 return;
5057 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005058
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005059 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005060 // derived to base as such conversions are given Conversion Rank. They only
5061 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5062 QualType FromCanon
5063 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5064 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5065 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5066 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005067 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005068 return;
5069 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005070
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005071 // To determine what the conversion from the result of calling the
5072 // conversion function to the type we're eventually trying to
5073 // convert to (ToType), we need to synthesize a call to the
5074 // conversion function and attempt copy initialization from it. This
5075 // makes sure that we get the right semantics with respect to
5076 // lvalues/rvalues and the type. Fortunately, we can allocate this
5077 // call on the stack and we don't need its arguments to be
5078 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00005079 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005080 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005081 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5082 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005083 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005084 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005085
Richard Smith87c1f1f2011-07-13 22:53:21 +00005086 QualType ConversionType = Conversion->getConversionType();
5087 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005088 Candidate.Viable = false;
5089 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5090 return;
5091 }
5092
Richard Smith87c1f1f2011-07-13 22:53:21 +00005093 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005094
Mike Stump1eb44332009-09-09 15:08:12 +00005095 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005096 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5097 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005098 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005099 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005100 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005101 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005102 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005103 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005104 /*InOverloadResolution=*/false,
5105 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005106
John McCall1d318332010-01-12 00:44:57 +00005107 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005108 case ImplicitConversionSequence::StandardConversion:
5109 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005110
Douglas Gregorc520c842010-04-12 23:42:09 +00005111 // C++ [over.ics.user]p3:
5112 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005113 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005114 // shall have exact match rank.
5115 if (Conversion->getPrimaryTemplate() &&
5116 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5117 Candidate.Viable = false;
5118 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005120
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005121 // C++0x [dcl.init.ref]p5:
5122 // In the second case, if the reference is an rvalue reference and
5123 // the second standard conversion sequence of the user-defined
5124 // conversion sequence includes an lvalue-to-rvalue conversion, the
5125 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005126 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005127 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5128 Candidate.Viable = false;
5129 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5130 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005131 break;
5132
5133 case ImplicitConversionSequence::BadConversion:
5134 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005135 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005136 break;
5137
5138 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005139 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005140 "Can only end up with a standard conversion sequence or failure");
5141 }
5142}
5143
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005144/// \brief Adds a conversion function template specialization
5145/// candidate to the overload set, using template argument deduction
5146/// to deduce the template arguments of the conversion function
5147/// template from the type that we are converting to (C++
5148/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005149void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005150Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005151 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005152 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005153 Expr *From, QualType ToType,
5154 OverloadCandidateSet &CandidateSet) {
5155 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5156 "Only conversion function templates permitted here");
5157
Douglas Gregor3f396022009-09-28 04:47:19 +00005158 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5159 return;
5160
John McCall5769d612010-02-08 23:07:23 +00005161 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005162 CXXConversionDecl *Specialization = 0;
5163 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005164 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005165 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00005166 CandidateSet.push_back(OverloadCandidate());
5167 OverloadCandidate &Candidate = CandidateSet.back();
5168 Candidate.FoundDecl = FoundDecl;
5169 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5170 Candidate.Viable = false;
5171 Candidate.FailureKind = ovl_fail_bad_deduction;
5172 Candidate.IsSurrogate = false;
5173 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005174 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005175 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005176 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005177 return;
5178 }
Mike Stump1eb44332009-09-09 15:08:12 +00005179
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005180 // Add the conversion function template specialization produced by
5181 // template argument deduction as a candidate.
5182 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005183 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005184 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005185}
5186
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005187/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5188/// converts the given @c Object to a function pointer via the
5189/// conversion function @c Conversion, and then attempts to call it
5190/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5191/// the type of function that we'll eventually be calling.
5192void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005193 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005194 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005195 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005196 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00005197 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005198 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005199 if (!CandidateSet.isNewCandidate(Conversion))
5200 return;
5201
Douglas Gregor7edfb692009-11-23 12:27:39 +00005202 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005203 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005204
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005205 CandidateSet.push_back(OverloadCandidate());
5206 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00005207 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005208 Candidate.Function = 0;
5209 Candidate.Surrogate = Conversion;
5210 Candidate.Viable = true;
5211 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005212 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005213 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00005214 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005215
5216 // Determine the implicit conversion sequence for the implicit
5217 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005218 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005219 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005220 Object->Classify(Context),
5221 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005222 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005223 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005224 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005225 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005226 return;
5227 }
5228
5229 // The first conversion is actually a user-defined conversion whose
5230 // first conversion is ObjectInit's standard conversion (which is
5231 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005232 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005233 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005234 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005235 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005236 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005237 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005238 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005239 = Candidate.Conversions[0].UserDefined.Before;
5240 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5241
Mike Stump1eb44332009-09-09 15:08:12 +00005242 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005243 unsigned NumArgsInProto = Proto->getNumArgs();
5244
5245 // (C++ 13.3.2p2): A candidate function having fewer than m
5246 // parameters is viable only if it has an ellipsis in its parameter
5247 // list (8.3.5).
5248 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5249 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005250 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005251 return;
5252 }
5253
5254 // Function types don't have any default arguments, so just check if
5255 // we have enough arguments.
5256 if (NumArgs < NumArgsInProto) {
5257 // Not enough arguments.
5258 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005259 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005260 return;
5261 }
5262
5263 // Determine the implicit conversion sequences for each of the
5264 // arguments.
5265 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5266 if (ArgIdx < NumArgsInProto) {
5267 // (C++ 13.3.2p3): for F to be a viable function, there shall
5268 // exist for each argument an implicit conversion sequence
5269 // (13.3.3.1) that converts that argument to the corresponding
5270 // parameter of F.
5271 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005272 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005273 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005274 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005275 /*InOverloadResolution=*/false,
5276 /*AllowObjCWritebackConversion=*/
5277 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005278 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005279 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005280 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005281 break;
5282 }
5283 } else {
5284 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5285 // argument for which there is no corresponding parameter is
5286 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005287 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005288 }
5289 }
5290}
5291
Douglas Gregor063daf62009-03-13 18:40:31 +00005292/// \brief Add overload candidates for overloaded operators that are
5293/// member functions.
5294///
5295/// Add the overloaded operator candidates that are member functions
5296/// for the operator Op that was used in an operator expression such
5297/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5298/// CandidateSet will store the added overload candidates. (C++
5299/// [over.match.oper]).
5300void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5301 SourceLocation OpLoc,
5302 Expr **Args, unsigned NumArgs,
5303 OverloadCandidateSet& CandidateSet,
5304 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005305 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5306
5307 // C++ [over.match.oper]p3:
5308 // For a unary operator @ with an operand of a type whose
5309 // cv-unqualified version is T1, and for a binary operator @ with
5310 // a left operand of a type whose cv-unqualified version is T1 and
5311 // a right operand of a type whose cv-unqualified version is T2,
5312 // three sets of candidate functions, designated member
5313 // candidates, non-member candidates and built-in candidates, are
5314 // constructed as follows:
5315 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005316
5317 // -- If T1 is a class type, the set of member candidates is the
5318 // result of the qualified lookup of T1::operator@
5319 // (13.3.1.1.1); otherwise, the set of member candidates is
5320 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005321 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005322 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005323 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005324 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005325
John McCalla24dc2e2009-11-17 02:14:36 +00005326 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5327 LookupQualifiedName(Operators, T1Rec->getDecl());
5328 Operators.suppressDiagnostics();
5329
Mike Stump1eb44332009-09-09 15:08:12 +00005330 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005331 OperEnd = Operators.end();
5332 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005333 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005334 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005335 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005336 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005337 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005338 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005339}
5340
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005341/// AddBuiltinCandidate - Add a candidate for a built-in
5342/// operator. ResultTy and ParamTys are the result and parameter types
5343/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005344/// arguments being passed to the candidate. IsAssignmentOperator
5345/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005346/// operator. NumContextualBoolArguments is the number of arguments
5347/// (at the beginning of the argument list) that will be contextually
5348/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005349void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005350 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005351 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005352 bool IsAssignmentOperator,
5353 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005354 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005355 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005356
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005357 // Add this candidate
5358 CandidateSet.push_back(OverloadCandidate());
5359 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00005360 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005361 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005362 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005363 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005364 Candidate.BuiltinTypes.ResultTy = ResultTy;
5365 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5366 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5367
5368 // Determine the implicit conversion sequences for each of the
5369 // arguments.
5370 Candidate.Viable = true;
5371 Candidate.Conversions.resize(NumArgs);
Douglas Gregordfc331e2011-01-19 23:54:39 +00005372 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005373 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005374 // C++ [over.match.oper]p4:
5375 // For the built-in assignment operators, conversions of the
5376 // left operand are restricted as follows:
5377 // -- no temporaries are introduced to hold the left operand, and
5378 // -- no user-defined conversions are applied to the left
5379 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005380 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005381 //
5382 // We block these conversions by turning off user-defined
5383 // conversions, since that is the only way that initialization of
5384 // a reference to a non-class type can occur from something that
5385 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005386 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005387 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005388 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005389 Candidate.Conversions[ArgIdx]
5390 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005391 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005392 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005393 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005394 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005395 /*InOverloadResolution=*/false,
5396 /*AllowObjCWritebackConversion=*/
5397 getLangOptions().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005398 }
John McCall1d318332010-01-12 00:44:57 +00005399 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005400 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005401 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005402 break;
5403 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005404 }
5405}
5406
5407/// BuiltinCandidateTypeSet - A set of types that will be used for the
5408/// candidate operator functions for built-in operators (C++
5409/// [over.built]). The types are separated into pointer types and
5410/// enumeration types.
5411class BuiltinCandidateTypeSet {
5412 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005413 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005414
5415 /// PointerTypes - The set of pointer types that will be used in the
5416 /// built-in candidates.
5417 TypeSet PointerTypes;
5418
Sebastian Redl78eb8742009-04-19 21:53:20 +00005419 /// MemberPointerTypes - The set of member pointer types that will be
5420 /// used in the built-in candidates.
5421 TypeSet MemberPointerTypes;
5422
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005423 /// EnumerationTypes - The set of enumeration types that will be
5424 /// used in the built-in candidates.
5425 TypeSet EnumerationTypes;
5426
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005427 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00005428 /// candidates.
5429 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00005430
5431 /// \brief A flag indicating non-record types are viable candidates
5432 bool HasNonRecordTypes;
5433
5434 /// \brief A flag indicating whether either arithmetic or enumeration types
5435 /// were present in the candidate set.
5436 bool HasArithmeticOrEnumeralTypes;
5437
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005438 /// \brief A flag indicating whether the nullptr type was present in the
5439 /// candidate set.
5440 bool HasNullPtrType;
5441
Douglas Gregor5842ba92009-08-24 15:23:48 +00005442 /// Sema - The semantic analysis instance where we are building the
5443 /// candidate type set.
5444 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00005445
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005446 /// Context - The AST context in which we will build the type sets.
5447 ASTContext &Context;
5448
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005449 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5450 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00005451 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005452
5453public:
5454 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005455 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005456
Mike Stump1eb44332009-09-09 15:08:12 +00005457 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00005458 : HasNonRecordTypes(false),
5459 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005460 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00005461 SemaRef(SemaRef),
5462 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005463
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005464 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005465 SourceLocation Loc,
5466 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005467 bool AllowExplicitConversions,
5468 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005469
5470 /// pointer_begin - First pointer type found;
5471 iterator pointer_begin() { return PointerTypes.begin(); }
5472
Sebastian Redl78eb8742009-04-19 21:53:20 +00005473 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005474 iterator pointer_end() { return PointerTypes.end(); }
5475
Sebastian Redl78eb8742009-04-19 21:53:20 +00005476 /// member_pointer_begin - First member pointer type found;
5477 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5478
5479 /// member_pointer_end - Past the last member pointer type found;
5480 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5481
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005482 /// enumeration_begin - First enumeration type found;
5483 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5484
Sebastian Redl78eb8742009-04-19 21:53:20 +00005485 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005486 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005487
Douglas Gregor26bcf672010-05-19 03:21:00 +00005488 iterator vector_begin() { return VectorTypes.begin(); }
5489 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00005490
5491 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5492 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005493 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005494};
5495
Sebastian Redl78eb8742009-04-19 21:53:20 +00005496/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005497/// the set of pointer types along with any more-qualified variants of
5498/// that type. For example, if @p Ty is "int const *", this routine
5499/// will add "int const *", "int const volatile *", "int const
5500/// restrict *", and "int const volatile restrict *" to the set of
5501/// pointer types. Returns true if the add of @p Ty itself succeeded,
5502/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005503///
5504/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005505bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00005506BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5507 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00005508
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005509 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005510 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005511 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005512
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005513 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00005514 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005515 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005516 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005517 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005518 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005519 buildObjCPtr = true;
5520 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005521 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005522 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005523 }
5524 else
5525 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005526
Sebastian Redla9efada2009-11-18 20:39:26 +00005527 // Don't add qualified variants of arrays. For one, they're not allowed
5528 // (the qualifier would sink to the element type), and for another, the
5529 // only overload situation where it matters is subscript or pointer +- int,
5530 // and those shouldn't have qualifier variants anyway.
5531 if (PointeeTy->isArrayType())
5532 return true;
John McCall0953e762009-09-24 19:53:00 +00005533 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00005534 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00005535 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005536 bool hasVolatile = VisibleQuals.hasVolatile();
5537 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005538
John McCall0953e762009-09-24 19:53:00 +00005539 // Iterate through all strict supersets of BaseCVR.
5540 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5541 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005542 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5543 // in the types.
5544 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5545 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00005546 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005547 if (!buildObjCPtr)
5548 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5549 else
5550 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005551 }
5552
5553 return true;
5554}
5555
Sebastian Redl78eb8742009-04-19 21:53:20 +00005556/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5557/// to the set of pointer types along with any more-qualified variants of
5558/// that type. For example, if @p Ty is "int const *", this routine
5559/// will add "int const *", "int const volatile *", "int const
5560/// restrict *", and "int const volatile restrict *" to the set of
5561/// pointer types. Returns true if the add of @p Ty itself succeeded,
5562/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005563///
5564/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005565bool
5566BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5567 QualType Ty) {
5568 // Insert this type.
5569 if (!MemberPointerTypes.insert(Ty))
5570 return false;
5571
John McCall0953e762009-09-24 19:53:00 +00005572 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5573 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00005574
John McCall0953e762009-09-24 19:53:00 +00005575 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00005576 // Don't add qualified variants of arrays. For one, they're not allowed
5577 // (the qualifier would sink to the element type), and for another, the
5578 // only overload situation where it matters is subscript or pointer +- int,
5579 // and those shouldn't have qualifier variants anyway.
5580 if (PointeeTy->isArrayType())
5581 return true;
John McCall0953e762009-09-24 19:53:00 +00005582 const Type *ClassTy = PointerTy->getClass();
5583
5584 // Iterate through all strict supersets of the pointee type's CVR
5585 // qualifiers.
5586 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5587 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5588 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005589
John McCall0953e762009-09-24 19:53:00 +00005590 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005591 MemberPointerTypes.insert(
5592 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00005593 }
5594
5595 return true;
5596}
5597
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005598/// AddTypesConvertedFrom - Add each of the types to which the type @p
5599/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00005600/// primarily interested in pointer types and enumeration types. We also
5601/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005602/// AllowUserConversions is true if we should look at the conversion
5603/// functions of a class type, and AllowExplicitConversions if we
5604/// should also include the explicit conversion functions of a class
5605/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00005606void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005607BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005608 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005609 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005610 bool AllowExplicitConversions,
5611 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005612 // Only deal with canonical types.
5613 Ty = Context.getCanonicalType(Ty);
5614
5615 // Look through reference types; they aren't part of the type of an
5616 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005617 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005618 Ty = RefTy->getPointeeType();
5619
John McCall3b657512011-01-19 10:06:00 +00005620 // If we're dealing with an array type, decay to the pointer.
5621 if (Ty->isArrayType())
5622 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5623
5624 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005625 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005626
Chandler Carruth6a577462010-12-13 01:44:01 +00005627 // Flag if we ever add a non-record type.
5628 const RecordType *TyRec = Ty->getAs<RecordType>();
5629 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5630
Chandler Carruth6a577462010-12-13 01:44:01 +00005631 // Flag if we encounter an arithmetic type.
5632 HasArithmeticOrEnumeralTypes =
5633 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5634
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005635 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5636 PointerTypes.insert(Ty);
5637 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005638 // Insert our type, and its more-qualified variants, into the set
5639 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005640 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005641 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00005642 } else if (Ty->isMemberPointerType()) {
5643 // Member pointers are far easier, since the pointee can't be converted.
5644 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5645 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005646 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005647 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00005648 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005649 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005650 // We treat vector types as arithmetic types in many contexts as an
5651 // extension.
5652 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00005653 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005654 } else if (Ty->isNullPtrType()) {
5655 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00005656 } else if (AllowUserConversions && TyRec) {
5657 // No conversion functions in incomplete types.
5658 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5659 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005660
Chandler Carruth6a577462010-12-13 01:44:01 +00005661 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5662 const UnresolvedSetImpl *Conversions
5663 = ClassDecl->getVisibleConversionFunctions();
5664 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5665 E = Conversions->end(); I != E; ++I) {
5666 NamedDecl *D = I.getDecl();
5667 if (isa<UsingShadowDecl>(D))
5668 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005669
Chandler Carruth6a577462010-12-13 01:44:01 +00005670 // Skip conversion function templates; they don't tell us anything
5671 // about which builtin types we can convert to.
5672 if (isa<FunctionTemplateDecl>(D))
5673 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005674
Chandler Carruth6a577462010-12-13 01:44:01 +00005675 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5676 if (AllowExplicitConversions || !Conv->isExplicit()) {
5677 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5678 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005679 }
5680 }
5681 }
5682}
5683
Douglas Gregor19b7b152009-08-24 13:43:27 +00005684/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5685/// the volatile- and non-volatile-qualified assignment operators for the
5686/// given type to the candidate set.
5687static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5688 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00005689 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00005690 unsigned NumArgs,
5691 OverloadCandidateSet &CandidateSet) {
5692 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00005693
Douglas Gregor19b7b152009-08-24 13:43:27 +00005694 // T& operator=(T&, T)
5695 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5696 ParamTypes[1] = T;
5697 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5698 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00005699
Douglas Gregor19b7b152009-08-24 13:43:27 +00005700 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5701 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00005702 ParamTypes[0]
5703 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00005704 ParamTypes[1] = T;
5705 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00005706 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00005707 }
5708}
Mike Stump1eb44332009-09-09 15:08:12 +00005709
Sebastian Redl9994a342009-10-25 17:03:50 +00005710/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5711/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005712static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5713 Qualifiers VRQuals;
5714 const RecordType *TyRec;
5715 if (const MemberPointerType *RHSMPType =
5716 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005717 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005718 else
5719 TyRec = ArgExpr->getType()->getAs<RecordType>();
5720 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005721 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005722 VRQuals.addVolatile();
5723 VRQuals.addRestrict();
5724 return VRQuals;
5725 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005726
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005727 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00005728 if (!ClassDecl->hasDefinition())
5729 return VRQuals;
5730
John McCalleec51cf2010-01-20 00:46:10 +00005731 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00005732 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005733
John McCalleec51cf2010-01-20 00:46:10 +00005734 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00005735 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00005736 NamedDecl *D = I.getDecl();
5737 if (isa<UsingShadowDecl>(D))
5738 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5739 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005740 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5741 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5742 CanTy = ResTypeRef->getPointeeType();
5743 // Need to go down the pointer/mempointer chain and add qualifiers
5744 // as see them.
5745 bool done = false;
5746 while (!done) {
5747 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5748 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005749 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005750 CanTy->getAs<MemberPointerType>())
5751 CanTy = ResTypeMPtr->getPointeeType();
5752 else
5753 done = true;
5754 if (CanTy.isVolatileQualified())
5755 VRQuals.addVolatile();
5756 if (CanTy.isRestrictQualified())
5757 VRQuals.addRestrict();
5758 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5759 return VRQuals;
5760 }
5761 }
5762 }
5763 return VRQuals;
5764}
John McCall00071ec2010-11-13 05:51:15 +00005765
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005766namespace {
John McCall00071ec2010-11-13 05:51:15 +00005767
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005768/// \brief Helper class to manage the addition of builtin operator overload
5769/// candidates. It provides shared state and utility methods used throughout
5770/// the process, as well as a helper method to add each group of builtin
5771/// operator overloads from the standard to a candidate set.
5772class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00005773 // Common instance state available to all overload candidate addition methods.
5774 Sema &S;
5775 Expr **Args;
5776 unsigned NumArgs;
5777 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00005778 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005779 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00005780 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005781
Chandler Carruth6d695582010-12-12 10:35:00 +00005782 // Define some constants used to index and iterate over the arithemetic types
5783 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00005784 // The "promoted arithmetic types" are the arithmetic
5785 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00005786 static const unsigned FirstIntegralType = 3;
5787 static const unsigned LastIntegralType = 18;
5788 static const unsigned FirstPromotedIntegralType = 3,
5789 LastPromotedIntegralType = 9;
5790 static const unsigned FirstPromotedArithmeticType = 0,
5791 LastPromotedArithmeticType = 9;
5792 static const unsigned NumArithmeticTypes = 18;
5793
Chandler Carruth6d695582010-12-12 10:35:00 +00005794 /// \brief Get the canonical type for a given arithmetic type index.
5795 CanQualType getArithmeticType(unsigned index) {
5796 assert(index < NumArithmeticTypes);
5797 static CanQualType ASTContext::* const
5798 ArithmeticTypes[NumArithmeticTypes] = {
5799 // Start of promoted types.
5800 &ASTContext::FloatTy,
5801 &ASTContext::DoubleTy,
5802 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00005803
Chandler Carruth6d695582010-12-12 10:35:00 +00005804 // Start of integral types.
5805 &ASTContext::IntTy,
5806 &ASTContext::LongTy,
5807 &ASTContext::LongLongTy,
5808 &ASTContext::UnsignedIntTy,
5809 &ASTContext::UnsignedLongTy,
5810 &ASTContext::UnsignedLongLongTy,
5811 // End of promoted types.
5812
5813 &ASTContext::BoolTy,
5814 &ASTContext::CharTy,
5815 &ASTContext::WCharTy,
5816 &ASTContext::Char16Ty,
5817 &ASTContext::Char32Ty,
5818 &ASTContext::SignedCharTy,
5819 &ASTContext::ShortTy,
5820 &ASTContext::UnsignedCharTy,
5821 &ASTContext::UnsignedShortTy,
5822 // End of integral types.
5823 // FIXME: What about complex?
5824 };
5825 return S.Context.*ArithmeticTypes[index];
5826 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005827
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005828 /// \brief Gets the canonical type resulting from the usual arithemetic
5829 /// converions for the given arithmetic types.
5830 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5831 // Accelerator table for performing the usual arithmetic conversions.
5832 // The rules are basically:
5833 // - if either is floating-point, use the wider floating-point
5834 // - if same signedness, use the higher rank
5835 // - if same size, use unsigned of the higher rank
5836 // - use the larger type
5837 // These rules, together with the axiom that higher ranks are
5838 // never smaller, are sufficient to precompute all of these results
5839 // *except* when dealing with signed types of higher rank.
5840 // (we could precompute SLL x UI for all known platforms, but it's
5841 // better not to make any assumptions).
5842 enum PromotedType {
5843 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5844 };
5845 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5846 [LastPromotedArithmeticType] = {
5847 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5848 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5849 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5850 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5851 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5852 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5853 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5854 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5855 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5856 };
5857
5858 assert(L < LastPromotedArithmeticType);
5859 assert(R < LastPromotedArithmeticType);
5860 int Idx = ConversionsTable[L][R];
5861
5862 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00005863 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005864
5865 // Slow path: we need to compare widths.
5866 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00005867 CanQualType LT = getArithmeticType(L),
5868 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005869 unsigned LW = S.Context.getIntWidth(LT),
5870 RW = S.Context.getIntWidth(RT);
5871
5872 // If they're different widths, use the signed type.
5873 if (LW > RW) return LT;
5874 else if (LW < RW) return RT;
5875
5876 // Otherwise, use the unsigned type of the signed type's rank.
5877 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5878 assert(L == SLL || R == SLL);
5879 return S.Context.UnsignedLongLongTy;
5880 }
5881
Chandler Carruth3c69dc42010-12-12 09:22:45 +00005882 /// \brief Helper method to factor out the common pattern of adding overloads
5883 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005884 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5885 bool HasVolatile) {
5886 QualType ParamTypes[2] = {
5887 S.Context.getLValueReferenceType(CandidateTy),
5888 S.Context.IntTy
5889 };
5890
5891 // Non-volatile version.
5892 if (NumArgs == 1)
5893 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5894 else
5895 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5896
5897 // Use a heuristic to reduce number of builtin candidates in the set:
5898 // add volatile version only if there are conversions to a volatile type.
5899 if (HasVolatile) {
5900 ParamTypes[0] =
5901 S.Context.getLValueReferenceType(
5902 S.Context.getVolatileType(CandidateTy));
5903 if (NumArgs == 1)
5904 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5905 else
5906 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5907 }
5908 }
5909
5910public:
5911 BuiltinOperatorOverloadBuilder(
5912 Sema &S, Expr **Args, unsigned NumArgs,
5913 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005914 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005915 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005916 OverloadCandidateSet &CandidateSet)
5917 : S(S), Args(Args), NumArgs(NumArgs),
5918 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00005919 HasArithmeticOrEnumeralCandidateType(
5920 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005921 CandidateTypes(CandidateTypes),
5922 CandidateSet(CandidateSet) {
5923 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00005924 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005925 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005926 assert(getArithmeticType(LastPromotedIntegralType - 1)
5927 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005928 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005929 assert(getArithmeticType(FirstPromotedArithmeticType)
5930 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005931 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005932 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5933 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005934 "Invalid last promoted arithmetic type");
5935 }
5936
5937 // C++ [over.built]p3:
5938 //
5939 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5940 // is either volatile or empty, there exist candidate operator
5941 // functions of the form
5942 //
5943 // VQ T& operator++(VQ T&);
5944 // T operator++(VQ T&, int);
5945 //
5946 // C++ [over.built]p4:
5947 //
5948 // For every pair (T, VQ), where T is an arithmetic type other
5949 // than bool, and VQ is either volatile or empty, there exist
5950 // candidate operator functions of the form
5951 //
5952 // VQ T& operator--(VQ T&);
5953 // T operator--(VQ T&, int);
5954 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005955 if (!HasArithmeticOrEnumeralCandidateType)
5956 return;
5957
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005958 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5959 Arith < NumArithmeticTypes; ++Arith) {
5960 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00005961 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005962 VisibleTypeConversionsQuals.hasVolatile());
5963 }
5964 }
5965
5966 // C++ [over.built]p5:
5967 //
5968 // For every pair (T, VQ), where T is a cv-qualified or
5969 // cv-unqualified object type, and VQ is either volatile or
5970 // empty, there exist candidate operator functions of the form
5971 //
5972 // T*VQ& operator++(T*VQ&);
5973 // T*VQ& operator--(T*VQ&);
5974 // T* operator++(T*VQ&, int);
5975 // T* operator--(T*VQ&, int);
5976 void addPlusPlusMinusMinusPointerOverloads() {
5977 for (BuiltinCandidateTypeSet::iterator
5978 Ptr = CandidateTypes[0].pointer_begin(),
5979 PtrEnd = CandidateTypes[0].pointer_end();
5980 Ptr != PtrEnd; ++Ptr) {
5981 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005982 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005983 continue;
5984
5985 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5986 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5987 VisibleTypeConversionsQuals.hasVolatile()));
5988 }
5989 }
5990
5991 // C++ [over.built]p6:
5992 // For every cv-qualified or cv-unqualified object type T, there
5993 // exist candidate operator functions of the form
5994 //
5995 // T& operator*(T*);
5996 //
5997 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005998 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005999 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006000 // T& operator*(T*);
6001 void addUnaryStarPointerOverloads() {
6002 for (BuiltinCandidateTypeSet::iterator
6003 Ptr = CandidateTypes[0].pointer_begin(),
6004 PtrEnd = CandidateTypes[0].pointer_end();
6005 Ptr != PtrEnd; ++Ptr) {
6006 QualType ParamTy = *Ptr;
6007 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006008 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6009 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006010
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006011 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6012 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6013 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006014
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006015 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6016 &ParamTy, Args, 1, CandidateSet);
6017 }
6018 }
6019
6020 // C++ [over.built]p9:
6021 // For every promoted arithmetic type T, there exist candidate
6022 // operator functions of the form
6023 //
6024 // T operator+(T);
6025 // T operator-(T);
6026 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006027 if (!HasArithmeticOrEnumeralCandidateType)
6028 return;
6029
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006030 for (unsigned Arith = FirstPromotedArithmeticType;
6031 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006032 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006033 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6034 }
6035
6036 // Extension: We also add these operators for vector types.
6037 for (BuiltinCandidateTypeSet::iterator
6038 Vec = CandidateTypes[0].vector_begin(),
6039 VecEnd = CandidateTypes[0].vector_end();
6040 Vec != VecEnd; ++Vec) {
6041 QualType VecTy = *Vec;
6042 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6043 }
6044 }
6045
6046 // C++ [over.built]p8:
6047 // For every type T, there exist candidate operator functions of
6048 // the form
6049 //
6050 // T* operator+(T*);
6051 void addUnaryPlusPointerOverloads() {
6052 for (BuiltinCandidateTypeSet::iterator
6053 Ptr = CandidateTypes[0].pointer_begin(),
6054 PtrEnd = CandidateTypes[0].pointer_end();
6055 Ptr != PtrEnd; ++Ptr) {
6056 QualType ParamTy = *Ptr;
6057 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6058 }
6059 }
6060
6061 // C++ [over.built]p10:
6062 // For every promoted integral type T, there exist candidate
6063 // operator functions of the form
6064 //
6065 // T operator~(T);
6066 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006067 if (!HasArithmeticOrEnumeralCandidateType)
6068 return;
6069
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006070 for (unsigned Int = FirstPromotedIntegralType;
6071 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006072 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006073 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6074 }
6075
6076 // Extension: We also add this operator for vector types.
6077 for (BuiltinCandidateTypeSet::iterator
6078 Vec = CandidateTypes[0].vector_begin(),
6079 VecEnd = CandidateTypes[0].vector_end();
6080 Vec != VecEnd; ++Vec) {
6081 QualType VecTy = *Vec;
6082 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6083 }
6084 }
6085
6086 // C++ [over.match.oper]p16:
6087 // For every pointer to member type T, there exist candidate operator
6088 // functions of the form
6089 //
6090 // bool operator==(T,T);
6091 // bool operator!=(T,T);
6092 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6093 /// Set of (canonical) types that we've already handled.
6094 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6095
6096 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6097 for (BuiltinCandidateTypeSet::iterator
6098 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6099 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6100 MemPtr != MemPtrEnd;
6101 ++MemPtr) {
6102 // Don't add the same builtin candidate twice.
6103 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6104 continue;
6105
6106 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6107 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6108 CandidateSet);
6109 }
6110 }
6111 }
6112
6113 // C++ [over.built]p15:
6114 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006115 // For every T, where T is an enumeration type, a pointer type, or
6116 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006117 //
6118 // bool operator<(T, T);
6119 // bool operator>(T, T);
6120 // bool operator<=(T, T);
6121 // bool operator>=(T, T);
6122 // bool operator==(T, T);
6123 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006124 void addRelationalPointerOrEnumeralOverloads() {
6125 // C++ [over.built]p1:
6126 // If there is a user-written candidate with the same name and parameter
6127 // types as a built-in candidate operator function, the built-in operator
6128 // function is hidden and is not included in the set of candidate
6129 // functions.
6130 //
6131 // The text is actually in a note, but if we don't implement it then we end
6132 // up with ambiguities when the user provides an overloaded operator for
6133 // an enumeration type. Note that only enumeration types have this problem,
6134 // so we track which enumeration types we've seen operators for. Also, the
6135 // only other overloaded operator with enumeration argumenst, operator=,
6136 // cannot be overloaded for enumeration types, so this is the only place
6137 // where we must suppress candidates like this.
6138 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6139 UserDefinedBinaryOperators;
6140
6141 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6142 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6143 CandidateTypes[ArgIdx].enumeration_end()) {
6144 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6145 CEnd = CandidateSet.end();
6146 C != CEnd; ++C) {
6147 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6148 continue;
6149
6150 QualType FirstParamType =
6151 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6152 QualType SecondParamType =
6153 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6154
6155 // Skip if either parameter isn't of enumeral type.
6156 if (!FirstParamType->isEnumeralType() ||
6157 !SecondParamType->isEnumeralType())
6158 continue;
6159
6160 // Add this operator to the set of known user-defined operators.
6161 UserDefinedBinaryOperators.insert(
6162 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6163 S.Context.getCanonicalType(SecondParamType)));
6164 }
6165 }
6166 }
6167
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006168 /// Set of (canonical) types that we've already handled.
6169 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6170
6171 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6172 for (BuiltinCandidateTypeSet::iterator
6173 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6174 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6175 Ptr != PtrEnd; ++Ptr) {
6176 // Don't add the same builtin candidate twice.
6177 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6178 continue;
6179
6180 QualType ParamTypes[2] = { *Ptr, *Ptr };
6181 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6182 CandidateSet);
6183 }
6184 for (BuiltinCandidateTypeSet::iterator
6185 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6186 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6187 Enum != EnumEnd; ++Enum) {
6188 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6189
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006190 // Don't add the same builtin candidate twice, or if a user defined
6191 // candidate exists.
6192 if (!AddedTypes.insert(CanonType) ||
6193 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6194 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006195 continue;
6196
6197 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006198 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6199 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006200 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006201
6202 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6203 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6204 if (AddedTypes.insert(NullPtrTy) &&
6205 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6206 NullPtrTy))) {
6207 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6208 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6209 CandidateSet);
6210 }
6211 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006212 }
6213 }
6214
6215 // C++ [over.built]p13:
6216 //
6217 // For every cv-qualified or cv-unqualified object type T
6218 // there exist candidate operator functions of the form
6219 //
6220 // T* operator+(T*, ptrdiff_t);
6221 // T& operator[](T*, ptrdiff_t); [BELOW]
6222 // T* operator-(T*, ptrdiff_t);
6223 // T* operator+(ptrdiff_t, T*);
6224 // T& operator[](ptrdiff_t, T*); [BELOW]
6225 //
6226 // C++ [over.built]p14:
6227 //
6228 // For every T, where T is a pointer to object type, there
6229 // exist candidate operator functions of the form
6230 //
6231 // ptrdiff_t operator-(T, T);
6232 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6233 /// Set of (canonical) types that we've already handled.
6234 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6235
6236 for (int Arg = 0; Arg < 2; ++Arg) {
6237 QualType AsymetricParamTypes[2] = {
6238 S.Context.getPointerDiffType(),
6239 S.Context.getPointerDiffType(),
6240 };
6241 for (BuiltinCandidateTypeSet::iterator
6242 Ptr = CandidateTypes[Arg].pointer_begin(),
6243 PtrEnd = CandidateTypes[Arg].pointer_end();
6244 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006245 QualType PointeeTy = (*Ptr)->getPointeeType();
6246 if (!PointeeTy->isObjectType())
6247 continue;
6248
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006249 AsymetricParamTypes[Arg] = *Ptr;
6250 if (Arg == 0 || Op == OO_Plus) {
6251 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6252 // T* operator+(ptrdiff_t, T*);
6253 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6254 CandidateSet);
6255 }
6256 if (Op == OO_Minus) {
6257 // ptrdiff_t operator-(T, T);
6258 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6259 continue;
6260
6261 QualType ParamTypes[2] = { *Ptr, *Ptr };
6262 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6263 Args, 2, CandidateSet);
6264 }
6265 }
6266 }
6267 }
6268
6269 // C++ [over.built]p12:
6270 //
6271 // For every pair of promoted arithmetic types L and R, there
6272 // exist candidate operator functions of the form
6273 //
6274 // LR operator*(L, R);
6275 // LR operator/(L, R);
6276 // LR operator+(L, R);
6277 // LR operator-(L, R);
6278 // bool operator<(L, R);
6279 // bool operator>(L, R);
6280 // bool operator<=(L, R);
6281 // bool operator>=(L, R);
6282 // bool operator==(L, R);
6283 // bool operator!=(L, R);
6284 //
6285 // where LR is the result of the usual arithmetic conversions
6286 // between types L and R.
6287 //
6288 // C++ [over.built]p24:
6289 //
6290 // For every pair of promoted arithmetic types L and R, there exist
6291 // candidate operator functions of the form
6292 //
6293 // LR operator?(bool, L, R);
6294 //
6295 // where LR is the result of the usual arithmetic conversions
6296 // between types L and R.
6297 // Our candidates ignore the first parameter.
6298 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006299 if (!HasArithmeticOrEnumeralCandidateType)
6300 return;
6301
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006302 for (unsigned Left = FirstPromotedArithmeticType;
6303 Left < LastPromotedArithmeticType; ++Left) {
6304 for (unsigned Right = FirstPromotedArithmeticType;
6305 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006306 QualType LandR[2] = { getArithmeticType(Left),
6307 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006308 QualType Result =
6309 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006310 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006311 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6312 }
6313 }
6314
6315 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6316 // conditional operator for vector types.
6317 for (BuiltinCandidateTypeSet::iterator
6318 Vec1 = CandidateTypes[0].vector_begin(),
6319 Vec1End = CandidateTypes[0].vector_end();
6320 Vec1 != Vec1End; ++Vec1) {
6321 for (BuiltinCandidateTypeSet::iterator
6322 Vec2 = CandidateTypes[1].vector_begin(),
6323 Vec2End = CandidateTypes[1].vector_end();
6324 Vec2 != Vec2End; ++Vec2) {
6325 QualType LandR[2] = { *Vec1, *Vec2 };
6326 QualType Result = S.Context.BoolTy;
6327 if (!isComparison) {
6328 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6329 Result = *Vec1;
6330 else
6331 Result = *Vec2;
6332 }
6333
6334 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6335 }
6336 }
6337 }
6338
6339 // C++ [over.built]p17:
6340 //
6341 // For every pair of promoted integral types L and R, there
6342 // exist candidate operator functions of the form
6343 //
6344 // LR operator%(L, R);
6345 // LR operator&(L, R);
6346 // LR operator^(L, R);
6347 // LR operator|(L, R);
6348 // L operator<<(L, R);
6349 // L operator>>(L, R);
6350 //
6351 // where LR is the result of the usual arithmetic conversions
6352 // between types L and R.
6353 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006354 if (!HasArithmeticOrEnumeralCandidateType)
6355 return;
6356
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006357 for (unsigned Left = FirstPromotedIntegralType;
6358 Left < LastPromotedIntegralType; ++Left) {
6359 for (unsigned Right = FirstPromotedIntegralType;
6360 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006361 QualType LandR[2] = { getArithmeticType(Left),
6362 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006363 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6364 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006365 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006366 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6367 }
6368 }
6369 }
6370
6371 // C++ [over.built]p20:
6372 //
6373 // For every pair (T, VQ), where T is an enumeration or
6374 // pointer to member type and VQ is either volatile or
6375 // empty, there exist candidate operator functions of the form
6376 //
6377 // VQ T& operator=(VQ T&, T);
6378 void addAssignmentMemberPointerOrEnumeralOverloads() {
6379 /// Set of (canonical) types that we've already handled.
6380 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6381
6382 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6383 for (BuiltinCandidateTypeSet::iterator
6384 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6385 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6386 Enum != EnumEnd; ++Enum) {
6387 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6388 continue;
6389
6390 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6391 CandidateSet);
6392 }
6393
6394 for (BuiltinCandidateTypeSet::iterator
6395 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6396 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6397 MemPtr != MemPtrEnd; ++MemPtr) {
6398 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6399 continue;
6400
6401 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6402 CandidateSet);
6403 }
6404 }
6405 }
6406
6407 // C++ [over.built]p19:
6408 //
6409 // For every pair (T, VQ), where T is any type and VQ is either
6410 // volatile or empty, there exist candidate operator functions
6411 // of the form
6412 //
6413 // T*VQ& operator=(T*VQ&, T*);
6414 //
6415 // C++ [over.built]p21:
6416 //
6417 // For every pair (T, VQ), where T is a cv-qualified or
6418 // cv-unqualified object type and VQ is either volatile or
6419 // empty, there exist candidate operator functions of the form
6420 //
6421 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6422 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6423 void addAssignmentPointerOverloads(bool isEqualOp) {
6424 /// Set of (canonical) types that we've already handled.
6425 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6426
6427 for (BuiltinCandidateTypeSet::iterator
6428 Ptr = CandidateTypes[0].pointer_begin(),
6429 PtrEnd = CandidateTypes[0].pointer_end();
6430 Ptr != PtrEnd; ++Ptr) {
6431 // If this is operator=, keep track of the builtin candidates we added.
6432 if (isEqualOp)
6433 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006434 else if (!(*Ptr)->getPointeeType()->isObjectType())
6435 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006436
6437 // non-volatile version
6438 QualType ParamTypes[2] = {
6439 S.Context.getLValueReferenceType(*Ptr),
6440 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6441 };
6442 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6443 /*IsAssigmentOperator=*/ isEqualOp);
6444
6445 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6446 VisibleTypeConversionsQuals.hasVolatile()) {
6447 // volatile version
6448 ParamTypes[0] =
6449 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6450 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6451 /*IsAssigmentOperator=*/isEqualOp);
6452 }
6453 }
6454
6455 if (isEqualOp) {
6456 for (BuiltinCandidateTypeSet::iterator
6457 Ptr = CandidateTypes[1].pointer_begin(),
6458 PtrEnd = CandidateTypes[1].pointer_end();
6459 Ptr != PtrEnd; ++Ptr) {
6460 // Make sure we don't add the same candidate twice.
6461 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6462 continue;
6463
Chandler Carruth6df868e2010-12-12 08:17:55 +00006464 QualType ParamTypes[2] = {
6465 S.Context.getLValueReferenceType(*Ptr),
6466 *Ptr,
6467 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006468
6469 // non-volatile version
6470 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6471 /*IsAssigmentOperator=*/true);
6472
6473 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6474 VisibleTypeConversionsQuals.hasVolatile()) {
6475 // volatile version
6476 ParamTypes[0] =
6477 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00006478 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6479 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006480 }
6481 }
6482 }
6483 }
6484
6485 // C++ [over.built]p18:
6486 //
6487 // For every triple (L, VQ, R), where L is an arithmetic type,
6488 // VQ is either volatile or empty, and R is a promoted
6489 // arithmetic type, there exist candidate operator functions of
6490 // the form
6491 //
6492 // VQ L& operator=(VQ L&, R);
6493 // VQ L& operator*=(VQ L&, R);
6494 // VQ L& operator/=(VQ L&, R);
6495 // VQ L& operator+=(VQ L&, R);
6496 // VQ L& operator-=(VQ L&, R);
6497 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006498 if (!HasArithmeticOrEnumeralCandidateType)
6499 return;
6500
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006501 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6502 for (unsigned Right = FirstPromotedArithmeticType;
6503 Right < LastPromotedArithmeticType; ++Right) {
6504 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006505 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006506
6507 // Add this built-in operator as a candidate (VQ is empty).
6508 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006509 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006510 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6511 /*IsAssigmentOperator=*/isEqualOp);
6512
6513 // Add this built-in operator as a candidate (VQ is 'volatile').
6514 if (VisibleTypeConversionsQuals.hasVolatile()) {
6515 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006516 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006517 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006518 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6519 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006520 /*IsAssigmentOperator=*/isEqualOp);
6521 }
6522 }
6523 }
6524
6525 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6526 for (BuiltinCandidateTypeSet::iterator
6527 Vec1 = CandidateTypes[0].vector_begin(),
6528 Vec1End = CandidateTypes[0].vector_end();
6529 Vec1 != Vec1End; ++Vec1) {
6530 for (BuiltinCandidateTypeSet::iterator
6531 Vec2 = CandidateTypes[1].vector_begin(),
6532 Vec2End = CandidateTypes[1].vector_end();
6533 Vec2 != Vec2End; ++Vec2) {
6534 QualType ParamTypes[2];
6535 ParamTypes[1] = *Vec2;
6536 // Add this built-in operator as a candidate (VQ is empty).
6537 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6538 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6539 /*IsAssigmentOperator=*/isEqualOp);
6540
6541 // Add this built-in operator as a candidate (VQ is 'volatile').
6542 if (VisibleTypeConversionsQuals.hasVolatile()) {
6543 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6544 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006545 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6546 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006547 /*IsAssigmentOperator=*/isEqualOp);
6548 }
6549 }
6550 }
6551 }
6552
6553 // C++ [over.built]p22:
6554 //
6555 // For every triple (L, VQ, R), where L is an integral type, VQ
6556 // is either volatile or empty, and R is a promoted integral
6557 // type, there exist candidate operator functions of the form
6558 //
6559 // VQ L& operator%=(VQ L&, R);
6560 // VQ L& operator<<=(VQ L&, R);
6561 // VQ L& operator>>=(VQ L&, R);
6562 // VQ L& operator&=(VQ L&, R);
6563 // VQ L& operator^=(VQ L&, R);
6564 // VQ L& operator|=(VQ L&, R);
6565 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006566 if (!HasArithmeticOrEnumeralCandidateType)
6567 return;
6568
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006569 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6570 for (unsigned Right = FirstPromotedIntegralType;
6571 Right < LastPromotedIntegralType; ++Right) {
6572 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006573 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006574
6575 // Add this built-in operator as a candidate (VQ is empty).
6576 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006577 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006578 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6579 if (VisibleTypeConversionsQuals.hasVolatile()) {
6580 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00006581 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006582 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6583 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6584 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6585 CandidateSet);
6586 }
6587 }
6588 }
6589 }
6590
6591 // C++ [over.operator]p23:
6592 //
6593 // There also exist candidate operator functions of the form
6594 //
6595 // bool operator!(bool);
6596 // bool operator&&(bool, bool);
6597 // bool operator||(bool, bool);
6598 void addExclaimOverload() {
6599 QualType ParamTy = S.Context.BoolTy;
6600 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6601 /*IsAssignmentOperator=*/false,
6602 /*NumContextualBoolArguments=*/1);
6603 }
6604 void addAmpAmpOrPipePipeOverload() {
6605 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6606 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6607 /*IsAssignmentOperator=*/false,
6608 /*NumContextualBoolArguments=*/2);
6609 }
6610
6611 // C++ [over.built]p13:
6612 //
6613 // For every cv-qualified or cv-unqualified object type T there
6614 // exist candidate operator functions of the form
6615 //
6616 // T* operator+(T*, ptrdiff_t); [ABOVE]
6617 // T& operator[](T*, ptrdiff_t);
6618 // T* operator-(T*, ptrdiff_t); [ABOVE]
6619 // T* operator+(ptrdiff_t, T*); [ABOVE]
6620 // T& operator[](ptrdiff_t, T*);
6621 void addSubscriptOverloads() {
6622 for (BuiltinCandidateTypeSet::iterator
6623 Ptr = CandidateTypes[0].pointer_begin(),
6624 PtrEnd = CandidateTypes[0].pointer_end();
6625 Ptr != PtrEnd; ++Ptr) {
6626 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6627 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006628 if (!PointeeType->isObjectType())
6629 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006630
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006631 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6632
6633 // T& operator[](T*, ptrdiff_t)
6634 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6635 }
6636
6637 for (BuiltinCandidateTypeSet::iterator
6638 Ptr = CandidateTypes[1].pointer_begin(),
6639 PtrEnd = CandidateTypes[1].pointer_end();
6640 Ptr != PtrEnd; ++Ptr) {
6641 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6642 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006643 if (!PointeeType->isObjectType())
6644 continue;
6645
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006646 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6647
6648 // T& operator[](ptrdiff_t, T*)
6649 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6650 }
6651 }
6652
6653 // C++ [over.built]p11:
6654 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6655 // C1 is the same type as C2 or is a derived class of C2, T is an object
6656 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6657 // there exist candidate operator functions of the form
6658 //
6659 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6660 //
6661 // where CV12 is the union of CV1 and CV2.
6662 void addArrowStarOverloads() {
6663 for (BuiltinCandidateTypeSet::iterator
6664 Ptr = CandidateTypes[0].pointer_begin(),
6665 PtrEnd = CandidateTypes[0].pointer_end();
6666 Ptr != PtrEnd; ++Ptr) {
6667 QualType C1Ty = (*Ptr);
6668 QualType C1;
6669 QualifierCollector Q1;
6670 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6671 if (!isa<RecordType>(C1))
6672 continue;
6673 // heuristic to reduce number of builtin candidates in the set.
6674 // Add volatile/restrict version only if there are conversions to a
6675 // volatile/restrict type.
6676 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6677 continue;
6678 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6679 continue;
6680 for (BuiltinCandidateTypeSet::iterator
6681 MemPtr = CandidateTypes[1].member_pointer_begin(),
6682 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6683 MemPtr != MemPtrEnd; ++MemPtr) {
6684 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6685 QualType C2 = QualType(mptr->getClass(), 0);
6686 C2 = C2.getUnqualifiedType();
6687 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6688 break;
6689 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6690 // build CV12 T&
6691 QualType T = mptr->getPointeeType();
6692 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6693 T.isVolatileQualified())
6694 continue;
6695 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6696 T.isRestrictQualified())
6697 continue;
6698 T = Q1.apply(S.Context, T);
6699 QualType ResultTy = S.Context.getLValueReferenceType(T);
6700 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6701 }
6702 }
6703 }
6704
6705 // Note that we don't consider the first argument, since it has been
6706 // contextually converted to bool long ago. The candidates below are
6707 // therefore added as binary.
6708 //
6709 // C++ [over.built]p25:
6710 // For every type T, where T is a pointer, pointer-to-member, or scoped
6711 // enumeration type, there exist candidate operator functions of the form
6712 //
6713 // T operator?(bool, T, T);
6714 //
6715 void addConditionalOperatorOverloads() {
6716 /// Set of (canonical) types that we've already handled.
6717 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6718
6719 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6720 for (BuiltinCandidateTypeSet::iterator
6721 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6722 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6723 Ptr != PtrEnd; ++Ptr) {
6724 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6725 continue;
6726
6727 QualType ParamTypes[2] = { *Ptr, *Ptr };
6728 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6729 }
6730
6731 for (BuiltinCandidateTypeSet::iterator
6732 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6733 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6734 MemPtr != MemPtrEnd; ++MemPtr) {
6735 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6736 continue;
6737
6738 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6739 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6740 }
6741
6742 if (S.getLangOptions().CPlusPlus0x) {
6743 for (BuiltinCandidateTypeSet::iterator
6744 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6745 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6746 Enum != EnumEnd; ++Enum) {
6747 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6748 continue;
6749
6750 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6751 continue;
6752
6753 QualType ParamTypes[2] = { *Enum, *Enum };
6754 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6755 }
6756 }
6757 }
6758 }
6759};
6760
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006761} // end anonymous namespace
6762
6763/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6764/// operator overloads to the candidate set (C++ [over.built]), based
6765/// on the operator @p Op and the arguments given. For example, if the
6766/// operator is a binary '+', this routine might add "int
6767/// operator+(int, int)" to cover integer addition.
6768void
6769Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6770 SourceLocation OpLoc,
6771 Expr **Args, unsigned NumArgs,
6772 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006773 // Find all of the types that the arguments can convert to, but only
6774 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00006775 // that make use of these types. Also record whether we encounter non-record
6776 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006777 Qualifiers VisibleTypeConversionsQuals;
6778 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00006779 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6780 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00006781
6782 bool HasNonRecordCandidateType = false;
6783 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006784 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00006785 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6786 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6787 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6788 OpLoc,
6789 true,
6790 (Op == OO_Exclaim ||
6791 Op == OO_AmpAmp ||
6792 Op == OO_PipePipe),
6793 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00006794 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6795 CandidateTypes[ArgIdx].hasNonRecordTypes();
6796 HasArithmeticOrEnumeralCandidateType =
6797 HasArithmeticOrEnumeralCandidateType ||
6798 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00006799 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006800
Chandler Carruth6a577462010-12-13 01:44:01 +00006801 // Exit early when no non-record types have been added to the candidate set
6802 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00006803 //
6804 // We can't exit early for !, ||, or &&, since there we have always have
6805 // 'bool' overloads.
6806 if (!HasNonRecordCandidateType &&
6807 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00006808 return;
6809
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006810 // Setup an object to manage the common state for building overloads.
6811 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6812 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006813 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006814 CandidateTypes, CandidateSet);
6815
6816 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006817 switch (Op) {
6818 case OO_None:
6819 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00006820 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006821
Chandler Carruthabb71842010-12-12 08:51:33 +00006822 case OO_New:
6823 case OO_Delete:
6824 case OO_Array_New:
6825 case OO_Array_Delete:
6826 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00006827 llvm_unreachable(
6828 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00006829
6830 case OO_Comma:
6831 case OO_Arrow:
6832 // C++ [over.match.oper]p3:
6833 // -- For the operator ',', the unary operator '&', or the
6834 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00006835 break;
6836
6837 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006838 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006839 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006840 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00006841
6842 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00006843 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006844 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006845 } else {
6846 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6847 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6848 }
Douglas Gregor74253732008-11-19 15:42:04 +00006849 break;
6850
Chandler Carruthabb71842010-12-12 08:51:33 +00006851 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00006852 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00006853 OpBuilder.addUnaryStarPointerOverloads();
6854 else
6855 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6856 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006857
Chandler Carruthabb71842010-12-12 08:51:33 +00006858 case OO_Slash:
6859 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00006860 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006861
6862 case OO_PlusPlus:
6863 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006864 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6865 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00006866 break;
6867
Douglas Gregor19b7b152009-08-24 13:43:27 +00006868 case OO_EqualEqual:
6869 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006870 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006871 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00006872
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006873 case OO_Less:
6874 case OO_Greater:
6875 case OO_LessEqual:
6876 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006877 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006878 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6879 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006880
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006881 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006882 case OO_Caret:
6883 case OO_Pipe:
6884 case OO_LessLess:
6885 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006886 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006887 break;
6888
Chandler Carruthabb71842010-12-12 08:51:33 +00006889 case OO_Amp: // '&' is either unary or binary
6890 if (NumArgs == 1)
6891 // C++ [over.match.oper]p3:
6892 // -- For the operator ',', the unary operator '&', or the
6893 // operator '->', the built-in candidates set is empty.
6894 break;
6895
6896 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6897 break;
6898
6899 case OO_Tilde:
6900 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6901 break;
6902
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006903 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006904 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00006905 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006906
6907 case OO_PlusEqual:
6908 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006909 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006910 // Fall through.
6911
6912 case OO_StarEqual:
6913 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006914 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006915 break;
6916
6917 case OO_PercentEqual:
6918 case OO_LessLessEqual:
6919 case OO_GreaterGreaterEqual:
6920 case OO_AmpEqual:
6921 case OO_CaretEqual:
6922 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006923 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006924 break;
6925
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006926 case OO_Exclaim:
6927 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00006928 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006929
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006930 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006931 case OO_PipePipe:
6932 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006933 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006934
6935 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006936 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006937 break;
6938
6939 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006940 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006941 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006942
6943 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006944 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006945 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6946 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006947 }
6948}
6949
Douglas Gregorfa047642009-02-04 00:32:51 +00006950/// \brief Add function candidates found via argument-dependent lookup
6951/// to the set of overloading candidates.
6952///
6953/// This routine performs argument-dependent name lookup based on the
6954/// given function name (which may also be an operator name) and adds
6955/// all of the overload candidates found by ADL to the overload
6956/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00006957void
Douglas Gregorfa047642009-02-04 00:32:51 +00006958Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00006959 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00006960 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00006961 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006962 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00006963 bool PartialOverloading,
6964 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00006965 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00006966
John McCalla113e722010-01-26 06:04:06 +00006967 // FIXME: This approach for uniquing ADL results (and removing
6968 // redundant candidates from the set) relies on pointer-equality,
6969 // which means we need to key off the canonical decl. However,
6970 // always going back to the canonical decl might not get us the
6971 // right set of default arguments. What default arguments are
6972 // we supposed to consider on ADL candidates, anyway?
6973
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006974 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00006975 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6976 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00006977
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006978 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006979 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6980 CandEnd = CandidateSet.end();
6981 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00006982 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00006983 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00006984 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00006985 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00006986 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006987
6988 // For each of the ADL candidates we found, add it to the overload
6989 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00006990 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00006991 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00006992 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00006993 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006994 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006995
John McCall9aa472c2010-03-19 07:35:19 +00006996 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006997 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006998 } else
John McCall6e266892010-01-26 03:27:55 +00006999 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007000 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00007001 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007002 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007003}
7004
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007005/// isBetterOverloadCandidate - Determines whether the first overload
7006/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007007bool
John McCall120d63c2010-08-24 20:38:10 +00007008isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007009 const OverloadCandidate &Cand1,
7010 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007011 SourceLocation Loc,
7012 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007013 // Define viable functions to be better candidates than non-viable
7014 // functions.
7015 if (!Cand2.Viable)
7016 return Cand1.Viable;
7017 else if (!Cand1.Viable)
7018 return false;
7019
Douglas Gregor88a35142008-12-22 05:46:06 +00007020 // C++ [over.match.best]p1:
7021 //
7022 // -- if F is a static member function, ICS1(F) is defined such
7023 // that ICS1(F) is neither better nor worse than ICS1(G) for
7024 // any function G, and, symmetrically, ICS1(G) is neither
7025 // better nor worse than ICS1(F).
7026 unsigned StartArg = 0;
7027 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7028 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007029
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007030 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007031 // A viable function F1 is defined to be a better function than another
7032 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007033 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007034 unsigned NumArgs = Cand1.Conversions.size();
7035 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
7036 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007037 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007038 switch (CompareImplicitConversionSequences(S,
7039 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007040 Cand2.Conversions[ArgIdx])) {
7041 case ImplicitConversionSequence::Better:
7042 // Cand1 has a better conversion sequence.
7043 HasBetterConversion = true;
7044 break;
7045
7046 case ImplicitConversionSequence::Worse:
7047 // Cand1 can't be better than Cand2.
7048 return false;
7049
7050 case ImplicitConversionSequence::Indistinguishable:
7051 // Do nothing.
7052 break;
7053 }
7054 }
7055
Mike Stump1eb44332009-09-09 15:08:12 +00007056 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007057 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007058 if (HasBetterConversion)
7059 return true;
7060
Mike Stump1eb44332009-09-09 15:08:12 +00007061 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007062 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007063 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007064 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7065 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007066
7067 // -- F1 and F2 are function template specializations, and the function
7068 // template for F1 is more specialized than the template for F2
7069 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007070 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007071 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007072 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007073 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007074 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7075 Cand2.Function->getPrimaryTemplate(),
7076 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007077 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007078 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007079 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007080 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007081 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007082
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007083 // -- the context is an initialization by user-defined conversion
7084 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7085 // from the return type of F1 to the destination type (i.e.,
7086 // the type of the entity being initialized) is a better
7087 // conversion sequence than the standard conversion sequence
7088 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007089 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007090 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007091 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00007092 switch (CompareStandardConversionSequences(S,
7093 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007094 Cand2.FinalConversion)) {
7095 case ImplicitConversionSequence::Better:
7096 // Cand1 has a better conversion sequence.
7097 return true;
7098
7099 case ImplicitConversionSequence::Worse:
7100 // Cand1 can't be better than Cand2.
7101 return false;
7102
7103 case ImplicitConversionSequence::Indistinguishable:
7104 // Do nothing
7105 break;
7106 }
7107 }
7108
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007109 return false;
7110}
7111
Mike Stump1eb44332009-09-09 15:08:12 +00007112/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007113/// within an overload candidate set.
7114///
7115/// \param CandidateSet the set of candidate functions.
7116///
7117/// \param Loc the location of the function name (or operator symbol) for
7118/// which overload resolution occurs.
7119///
Mike Stump1eb44332009-09-09 15:08:12 +00007120/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007121/// function, Best points to the candidate function found.
7122///
7123/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007124OverloadingResult
7125OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007126 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007127 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007128 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007129 Best = end();
7130 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7131 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007132 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007133 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007134 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007135 }
7136
7137 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007138 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007139 return OR_No_Viable_Function;
7140
7141 // Make sure that this function is better than every other viable
7142 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007143 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007144 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007145 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007146 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007147 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007148 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007149 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007150 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007151 }
Mike Stump1eb44332009-09-09 15:08:12 +00007152
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007153 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007154 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007155 (Best->Function->isDeleted() ||
7156 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007157 return OR_Deleted;
7158
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007159 return OR_Success;
7160}
7161
John McCall3c80f572010-01-12 02:15:36 +00007162namespace {
7163
7164enum OverloadCandidateKind {
7165 oc_function,
7166 oc_method,
7167 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007168 oc_function_template,
7169 oc_method_template,
7170 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007171 oc_implicit_default_constructor,
7172 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007173 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007174 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007175 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007176 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007177};
7178
John McCall220ccbf2010-01-13 00:25:19 +00007179OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7180 FunctionDecl *Fn,
7181 std::string &Description) {
7182 bool isTemplate = false;
7183
7184 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7185 isTemplate = true;
7186 Description = S.getTemplateArgumentBindingsText(
7187 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7188 }
John McCallb1622a12010-01-06 09:43:14 +00007189
7190 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007191 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007192 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007193
Sebastian Redlf677ea32011-02-05 19:23:19 +00007194 if (Ctor->getInheritedConstructor())
7195 return oc_implicit_inherited_constructor;
7196
Sean Hunt82713172011-05-25 23:16:36 +00007197 if (Ctor->isDefaultConstructor())
7198 return oc_implicit_default_constructor;
7199
7200 if (Ctor->isMoveConstructor())
7201 return oc_implicit_move_constructor;
7202
7203 assert(Ctor->isCopyConstructor() &&
7204 "unexpected sort of implicit constructor");
7205 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007206 }
7207
7208 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7209 // This actually gets spelled 'candidate function' for now, but
7210 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007211 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007212 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007213
Sean Hunt82713172011-05-25 23:16:36 +00007214 if (Meth->isMoveAssignmentOperator())
7215 return oc_implicit_move_assignment;
7216
Douglas Gregor3e9438b2010-09-27 22:37:28 +00007217 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00007218 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00007219 return oc_implicit_copy_assignment;
7220 }
7221
John McCall220ccbf2010-01-13 00:25:19 +00007222 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007223}
7224
Sebastian Redlf677ea32011-02-05 19:23:19 +00007225void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7226 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7227 if (!Ctor) return;
7228
7229 Ctor = Ctor->getInheritedConstructor();
7230 if (!Ctor) return;
7231
7232 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7233}
7234
John McCall3c80f572010-01-12 02:15:36 +00007235} // end anonymous namespace
7236
7237// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007238void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007239 std::string FnDesc;
7240 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007241 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7242 << (unsigned) K << FnDesc;
7243 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7244 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007245 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007246}
7247
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007248//Notes the location of all overload candidates designated through
7249// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007250void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007251 assert(OverloadedExpr->getType() == Context.OverloadTy);
7252
7253 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7254 OverloadExpr *OvlExpr = Ovl.Expression;
7255
7256 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7257 IEnd = OvlExpr->decls_end();
7258 I != IEnd; ++I) {
7259 if (FunctionTemplateDecl *FunTmpl =
7260 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007261 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007262 } else if (FunctionDecl *Fun
7263 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007264 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007265 }
7266 }
7267}
7268
John McCall1d318332010-01-12 00:44:57 +00007269/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7270/// "lead" diagnostic; it will be given two arguments, the source and
7271/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007272void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7273 Sema &S,
7274 SourceLocation CaretLoc,
7275 const PartialDiagnostic &PDiag) const {
7276 S.Diag(CaretLoc, PDiag)
7277 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007278 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007279 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7280 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007281 }
John McCall81201622010-01-08 04:41:39 +00007282}
7283
John McCall1d318332010-01-12 00:44:57 +00007284namespace {
7285
John McCalladbb8f82010-01-13 09:16:55 +00007286void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7287 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7288 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007289 assert(Cand->Function && "for now, candidate must be a function");
7290 FunctionDecl *Fn = Cand->Function;
7291
7292 // There's a conversion slot for the object argument if this is a
7293 // non-constructor method. Note that 'I' corresponds the
7294 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007295 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007296 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007297 if (I == 0)
7298 isObjectArgument = true;
7299 else
7300 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007301 }
7302
John McCall220ccbf2010-01-13 00:25:19 +00007303 std::string FnDesc;
7304 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7305
John McCalladbb8f82010-01-13 09:16:55 +00007306 Expr *FromExpr = Conv.Bad.FromExpr;
7307 QualType FromTy = Conv.Bad.getFromType();
7308 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007309
John McCall5920dbb2010-02-02 02:42:52 +00007310 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007311 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007312 Expr *E = FromExpr->IgnoreParens();
7313 if (isa<UnaryOperator>(E))
7314 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007315 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007316
7317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7318 << (unsigned) FnKind << FnDesc
7319 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7320 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007321 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007322 return;
7323 }
7324
John McCall258b2032010-01-23 08:10:49 +00007325 // Do some hand-waving analysis to see if the non-viability is due
7326 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007327 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7328 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7329 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7330 CToTy = RT->getPointeeType();
7331 else {
7332 // TODO: detect and diagnose the full richness of const mismatches.
7333 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7334 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7335 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7336 }
7337
7338 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7339 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7340 // It is dumb that we have to do this here.
7341 while (isa<ArrayType>(CFromTy))
7342 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7343 while (isa<ArrayType>(CToTy))
7344 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7345
7346 Qualifiers FromQs = CFromTy.getQualifiers();
7347 Qualifiers ToQs = CToTy.getQualifiers();
7348
7349 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7351 << (unsigned) FnKind << FnDesc
7352 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7353 << FromTy
7354 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7355 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007356 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007357 return;
7358 }
7359
John McCallf85e1932011-06-15 23:02:42 +00007360 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007361 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007362 << (unsigned) FnKind << FnDesc
7363 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7364 << FromTy
7365 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7366 << (unsigned) isObjectArgument << I+1;
7367 MaybeEmitInheritedConstructorNote(S, Fn);
7368 return;
7369 }
7370
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007371 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7372 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7373 << (unsigned) FnKind << FnDesc
7374 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7375 << FromTy
7376 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7377 << (unsigned) isObjectArgument << I+1;
7378 MaybeEmitInheritedConstructorNote(S, Fn);
7379 return;
7380 }
7381
John McCall651f3ee2010-01-14 03:28:57 +00007382 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7383 assert(CVR && "unexpected qualifiers mismatch");
7384
7385 if (isObjectArgument) {
7386 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7387 << (unsigned) FnKind << FnDesc
7388 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7389 << FromTy << (CVR - 1);
7390 } else {
7391 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7392 << (unsigned) FnKind << FnDesc
7393 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7394 << FromTy << (CVR - 1) << I+1;
7395 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007396 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007397 return;
7398 }
7399
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007400 // Special diagnostic for failure to convert an initializer list, since
7401 // telling the user that it has type void is not useful.
7402 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7403 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7404 << (unsigned) FnKind << FnDesc
7405 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7406 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7407 MaybeEmitInheritedConstructorNote(S, Fn);
7408 return;
7409 }
7410
John McCall258b2032010-01-23 08:10:49 +00007411 // Diagnose references or pointers to incomplete types differently,
7412 // since it's far from impossible that the incompleteness triggered
7413 // the failure.
7414 QualType TempFromTy = FromTy.getNonReferenceType();
7415 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7416 TempFromTy = PTy->getPointeeType();
7417 if (TempFromTy->isIncompleteType()) {
7418 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7419 << (unsigned) FnKind << FnDesc
7420 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7421 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007422 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00007423 return;
7424 }
7425
Douglas Gregor85789812010-06-30 23:01:39 +00007426 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007427 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00007428 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7429 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7430 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7431 FromPtrTy->getPointeeType()) &&
7432 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7433 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007434 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00007435 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007436 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00007437 }
7438 } else if (const ObjCObjectPointerType *FromPtrTy
7439 = FromTy->getAs<ObjCObjectPointerType>()) {
7440 if (const ObjCObjectPointerType *ToPtrTy
7441 = ToTy->getAs<ObjCObjectPointerType>())
7442 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7443 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7444 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7445 FromPtrTy->getPointeeType()) &&
7446 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007447 BaseToDerivedConversion = 2;
7448 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7449 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7450 !FromTy->isIncompleteType() &&
7451 !ToRefTy->getPointeeType()->isIncompleteType() &&
7452 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7453 BaseToDerivedConversion = 3;
7454 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007455
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007456 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007457 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007458 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00007459 << (unsigned) FnKind << FnDesc
7460 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007461 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007462 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007463 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00007464 return;
7465 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007466
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00007467 if (isa<ObjCObjectPointerType>(CFromTy) &&
7468 isa<PointerType>(CToTy)) {
7469 Qualifiers FromQs = CFromTy.getQualifiers();
7470 Qualifiers ToQs = CToTy.getQualifiers();
7471 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7473 << (unsigned) FnKind << FnDesc
7474 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7475 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7476 MaybeEmitInheritedConstructorNote(S, Fn);
7477 return;
7478 }
7479 }
7480
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007481 // Emit the generic diagnostic and, optionally, add the hints to it.
7482 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7483 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00007484 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007485 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7486 << (unsigned) (Cand->Fix.Kind);
7487
7488 // If we can fix the conversion, suggest the FixIts.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007489 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007490 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7491 HI != HE; ++HI)
7492 FDiag << *HI;
7493 S.Diag(Fn->getLocation(), FDiag);
7494
Sebastian Redlf677ea32011-02-05 19:23:19 +00007495 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00007496}
7497
7498void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7499 unsigned NumFormalArgs) {
7500 // TODO: treat calls to a missing default constructor as a special case
7501
7502 FunctionDecl *Fn = Cand->Function;
7503 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7504
7505 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007506
Douglas Gregor439d3c32011-05-05 00:13:13 +00007507 // With invalid overloaded operators, it's possible that we think we
7508 // have an arity mismatch when it fact it looks like we have the
7509 // right number of arguments, because only overloaded operators have
7510 // the weird behavior of overloading member and non-member functions.
7511 // Just don't report anything.
7512 if (Fn->isInvalidDecl() &&
7513 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7514 return;
7515
John McCalladbb8f82010-01-13 09:16:55 +00007516 // at least / at most / exactly
7517 unsigned mode, modeCount;
7518 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00007519 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7520 (Cand->FailureKind == ovl_fail_bad_deduction &&
7521 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007522 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00007523 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00007524 mode = 0; // "at least"
7525 else
7526 mode = 2; // "exactly"
7527 modeCount = MinParams;
7528 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00007529 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7530 (Cand->FailureKind == ovl_fail_bad_deduction &&
7531 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00007532 if (MinParams != FnTy->getNumArgs())
7533 mode = 1; // "at most"
7534 else
7535 mode = 2; // "exactly"
7536 modeCount = FnTy->getNumArgs();
7537 }
7538
7539 std::string Description;
7540 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7541
7542 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007543 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00007544 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007545 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007546}
7547
John McCall342fec42010-02-01 18:53:26 +00007548/// Diagnose a failed template-argument deduction.
7549void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7550 Expr **Args, unsigned NumArgs) {
7551 FunctionDecl *Fn = Cand->Function; // pattern
7552
Douglas Gregora9333192010-05-08 17:41:32 +00007553 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00007554 NamedDecl *ParamD;
7555 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7556 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7557 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00007558 switch (Cand->DeductionFailure.Result) {
7559 case Sema::TDK_Success:
7560 llvm_unreachable("TDK_success while diagnosing bad deduction");
7561
7562 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00007563 assert(ParamD && "no parameter found for incomplete deduction result");
7564 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7565 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007566 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007567 return;
7568 }
7569
John McCall57e97782010-08-05 09:05:08 +00007570 case Sema::TDK_Underqualified: {
7571 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7572 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7573
7574 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7575
7576 // Param will have been canonicalized, but it should just be a
7577 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00007578 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00007579 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00007580 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00007581 assert(S.Context.hasSameType(Param, NonCanonParam));
7582
7583 // Arg has also been canonicalized, but there's nothing we can do
7584 // about that. It also doesn't matter as much, because it won't
7585 // have any template parameters in it (because deduction isn't
7586 // done on dependent types).
7587 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7588
7589 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7590 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007591 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00007592 return;
7593 }
7594
7595 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00007596 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00007597 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007598 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007599 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007600 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007601 which = 1;
7602 else {
Douglas Gregora9333192010-05-08 17:41:32 +00007603 which = 2;
7604 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007605
Douglas Gregora9333192010-05-08 17:41:32 +00007606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007607 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00007608 << *Cand->DeductionFailure.getFirstArg()
7609 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007610 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00007611 return;
7612 }
Douglas Gregora18592e2010-05-08 18:13:28 +00007613
Douglas Gregorf1a84452010-05-08 19:15:54 +00007614 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007615 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00007616 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007617 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007618 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7619 << ParamD->getDeclName();
7620 else {
7621 int index = 0;
7622 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7623 index = TTP->getIndex();
7624 else if (NonTypeTemplateParmDecl *NTTP
7625 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7626 index = NTTP->getIndex();
7627 else
7628 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007629 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007630 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7631 << (index + 1);
7632 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007633 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00007634 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007635
Douglas Gregora18592e2010-05-08 18:13:28 +00007636 case Sema::TDK_TooManyArguments:
7637 case Sema::TDK_TooFewArguments:
7638 DiagnoseArityMismatch(S, Cand, NumArgs);
7639 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00007640
7641 case Sema::TDK_InstantiationDepth:
7642 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007643 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007644 return;
7645
7646 case Sema::TDK_SubstitutionFailure: {
7647 std::string ArgString;
7648 if (TemplateArgumentList *Args
7649 = Cand->DeductionFailure.getTemplateArgumentList())
7650 ArgString = S.getTemplateArgumentBindingsText(
7651 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7652 *Args);
7653 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7654 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007655 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007656 return;
7657 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007658
John McCall342fec42010-02-01 18:53:26 +00007659 // TODO: diagnose these individually, then kill off
7660 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00007661 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00007662 case Sema::TDK_FailedOverloadResolution:
7663 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007664 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007665 return;
7666 }
7667}
7668
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007669/// CUDA: diagnose an invalid call across targets.
7670void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7671 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7672 FunctionDecl *Callee = Cand->Function;
7673
7674 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7675 CalleeTarget = S.IdentifyCUDATarget(Callee);
7676
7677 std::string FnDesc;
7678 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7679
7680 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7681 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7682}
7683
John McCall342fec42010-02-01 18:53:26 +00007684/// Generates a 'note' diagnostic for an overload candidate. We've
7685/// already generated a primary error at the call site.
7686///
7687/// It really does need to be a single diagnostic with its caret
7688/// pointed at the candidate declaration. Yes, this creates some
7689/// major challenges of technical writing. Yes, this makes pointing
7690/// out problems with specific arguments quite awkward. It's still
7691/// better than generating twenty screens of text for every failed
7692/// overload.
7693///
7694/// It would be great to be able to express per-candidate problems
7695/// more richly for those diagnostic clients that cared, but we'd
7696/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00007697void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7698 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00007699 FunctionDecl *Fn = Cand->Function;
7700
John McCall81201622010-01-08 04:41:39 +00007701 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007702 if (Cand->Viable && (Fn->isDeleted() ||
7703 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00007704 std::string FnDesc;
7705 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00007706
7707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00007708 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007709 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00007710 return;
John McCall81201622010-01-08 04:41:39 +00007711 }
7712
John McCall220ccbf2010-01-13 00:25:19 +00007713 // We don't really have anything else to say about viable candidates.
7714 if (Cand->Viable) {
7715 S.NoteOverloadCandidate(Fn);
7716 return;
7717 }
John McCall1d318332010-01-12 00:44:57 +00007718
John McCalladbb8f82010-01-13 09:16:55 +00007719 switch (Cand->FailureKind) {
7720 case ovl_fail_too_many_arguments:
7721 case ovl_fail_too_few_arguments:
7722 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00007723
John McCalladbb8f82010-01-13 09:16:55 +00007724 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00007725 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7726
John McCall717e8912010-01-23 05:17:32 +00007727 case ovl_fail_trivial_conversion:
7728 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00007729 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00007730 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007731
John McCallb1bdc622010-02-25 01:37:24 +00007732 case ovl_fail_bad_conversion: {
7733 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7734 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00007735 if (Cand->Conversions[I].isBad())
7736 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007737
John McCalladbb8f82010-01-13 09:16:55 +00007738 // FIXME: this currently happens when we're called from SemaInit
7739 // when user-conversion overload fails. Figure out how to handle
7740 // those conditions and diagnose them well.
7741 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007742 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007743
7744 case ovl_fail_bad_target:
7745 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00007746 }
John McCalla1d7d622010-01-08 00:58:21 +00007747}
7748
7749void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7750 // Desugar the type of the surrogate down to a function type,
7751 // retaining as many typedefs as possible while still showing
7752 // the function type (and, therefore, its parameter types).
7753 QualType FnType = Cand->Surrogate->getConversionType();
7754 bool isLValueReference = false;
7755 bool isRValueReference = false;
7756 bool isPointer = false;
7757 if (const LValueReferenceType *FnTypeRef =
7758 FnType->getAs<LValueReferenceType>()) {
7759 FnType = FnTypeRef->getPointeeType();
7760 isLValueReference = true;
7761 } else if (const RValueReferenceType *FnTypeRef =
7762 FnType->getAs<RValueReferenceType>()) {
7763 FnType = FnTypeRef->getPointeeType();
7764 isRValueReference = true;
7765 }
7766 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7767 FnType = FnTypePtr->getPointeeType();
7768 isPointer = true;
7769 }
7770 // Desugar down to a function type.
7771 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7772 // Reconstruct the pointer/reference as appropriate.
7773 if (isPointer) FnType = S.Context.getPointerType(FnType);
7774 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7775 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7776
7777 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7778 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007779 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00007780}
7781
7782void NoteBuiltinOperatorCandidate(Sema &S,
7783 const char *Opc,
7784 SourceLocation OpLoc,
7785 OverloadCandidate *Cand) {
7786 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7787 std::string TypeStr("operator");
7788 TypeStr += Opc;
7789 TypeStr += "(";
7790 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7791 if (Cand->Conversions.size() == 1) {
7792 TypeStr += ")";
7793 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7794 } else {
7795 TypeStr += ", ";
7796 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7797 TypeStr += ")";
7798 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7799 }
7800}
7801
7802void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7803 OverloadCandidate *Cand) {
7804 unsigned NoOperands = Cand->Conversions.size();
7805 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7806 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00007807 if (ICS.isBad()) break; // all meaningless after first invalid
7808 if (!ICS.isAmbiguous()) continue;
7809
John McCall120d63c2010-08-24 20:38:10 +00007810 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007811 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00007812 }
7813}
7814
John McCall1b77e732010-01-15 23:32:50 +00007815SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7816 if (Cand->Function)
7817 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00007818 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00007819 return Cand->Surrogate->getLocation();
7820 return SourceLocation();
7821}
7822
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007823static unsigned
7824RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00007825 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007826 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00007827 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007828
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007829 case Sema::TDK_Incomplete:
7830 return 1;
7831
7832 case Sema::TDK_Underqualified:
7833 case Sema::TDK_Inconsistent:
7834 return 2;
7835
7836 case Sema::TDK_SubstitutionFailure:
7837 case Sema::TDK_NonDeducedMismatch:
7838 return 3;
7839
7840 case Sema::TDK_InstantiationDepth:
7841 case Sema::TDK_FailedOverloadResolution:
7842 return 4;
7843
7844 case Sema::TDK_InvalidExplicitArguments:
7845 return 5;
7846
7847 case Sema::TDK_TooManyArguments:
7848 case Sema::TDK_TooFewArguments:
7849 return 6;
7850 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007851 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007852}
7853
John McCallbf65c0b2010-01-12 00:48:53 +00007854struct CompareOverloadCandidatesForDisplay {
7855 Sema &S;
7856 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00007857
7858 bool operator()(const OverloadCandidate *L,
7859 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00007860 // Fast-path this check.
7861 if (L == R) return false;
7862
John McCall81201622010-01-08 04:41:39 +00007863 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00007864 if (L->Viable) {
7865 if (!R->Viable) return true;
7866
7867 // TODO: introduce a tri-valued comparison for overload
7868 // candidates. Would be more worthwhile if we had a sort
7869 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00007870 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7871 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00007872 } else if (R->Viable)
7873 return false;
John McCall81201622010-01-08 04:41:39 +00007874
John McCall1b77e732010-01-15 23:32:50 +00007875 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00007876
John McCall1b77e732010-01-15 23:32:50 +00007877 // Criteria by which we can sort non-viable candidates:
7878 if (!L->Viable) {
7879 // 1. Arity mismatches come after other candidates.
7880 if (L->FailureKind == ovl_fail_too_many_arguments ||
7881 L->FailureKind == ovl_fail_too_few_arguments)
7882 return false;
7883 if (R->FailureKind == ovl_fail_too_many_arguments ||
7884 R->FailureKind == ovl_fail_too_few_arguments)
7885 return true;
John McCall81201622010-01-08 04:41:39 +00007886
John McCall717e8912010-01-23 05:17:32 +00007887 // 2. Bad conversions come first and are ordered by the number
7888 // of bad conversions and quality of good conversions.
7889 if (L->FailureKind == ovl_fail_bad_conversion) {
7890 if (R->FailureKind != ovl_fail_bad_conversion)
7891 return true;
7892
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007893 // The conversion that can be fixed with a smaller number of changes,
7894 // comes first.
7895 unsigned numLFixes = L->Fix.NumConversionsFixed;
7896 unsigned numRFixes = R->Fix.NumConversionsFixed;
7897 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7898 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007899 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007900 if (numLFixes < numRFixes)
7901 return true;
7902 else
7903 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007904 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007905
John McCall717e8912010-01-23 05:17:32 +00007906 // If there's any ordering between the defined conversions...
7907 // FIXME: this might not be transitive.
7908 assert(L->Conversions.size() == R->Conversions.size());
7909
7910 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00007911 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7912 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00007913 switch (CompareImplicitConversionSequences(S,
7914 L->Conversions[I],
7915 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00007916 case ImplicitConversionSequence::Better:
7917 leftBetter++;
7918 break;
7919
7920 case ImplicitConversionSequence::Worse:
7921 leftBetter--;
7922 break;
7923
7924 case ImplicitConversionSequence::Indistinguishable:
7925 break;
7926 }
7927 }
7928 if (leftBetter > 0) return true;
7929 if (leftBetter < 0) return false;
7930
7931 } else if (R->FailureKind == ovl_fail_bad_conversion)
7932 return false;
7933
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007934 if (L->FailureKind == ovl_fail_bad_deduction) {
7935 if (R->FailureKind != ovl_fail_bad_deduction)
7936 return true;
7937
7938 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7939 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00007940 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00007941 } else if (R->FailureKind == ovl_fail_bad_deduction)
7942 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007943
John McCall1b77e732010-01-15 23:32:50 +00007944 // TODO: others?
7945 }
7946
7947 // Sort everything else by location.
7948 SourceLocation LLoc = GetLocationForCandidate(L);
7949 SourceLocation RLoc = GetLocationForCandidate(R);
7950
7951 // Put candidates without locations (e.g. builtins) at the end.
7952 if (LLoc.isInvalid()) return false;
7953 if (RLoc.isInvalid()) return true;
7954
7955 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00007956 }
7957};
7958
John McCall717e8912010-01-23 05:17:32 +00007959/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007960/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00007961void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7962 Expr **Args, unsigned NumArgs) {
7963 assert(!Cand->Viable);
7964
7965 // Don't do anything on failures other than bad conversion.
7966 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7967
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007968 // We only want the FixIts if all the arguments can be corrected.
7969 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00007970 // Use a implicit copy initialization to check conversion fixes.
7971 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007972
John McCall717e8912010-01-23 05:17:32 +00007973 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00007974 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00007975 unsigned ConvCount = Cand->Conversions.size();
7976 while (true) {
7977 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7978 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007979 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00007980 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00007981 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007982 }
John McCall717e8912010-01-23 05:17:32 +00007983 }
7984
7985 if (ConvIdx == ConvCount)
7986 return;
7987
John McCallb1bdc622010-02-25 01:37:24 +00007988 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7989 "remaining conversion is initialized?");
7990
Douglas Gregor23ef6c02010-04-16 17:45:54 +00007991 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00007992 // operation somehow.
7993 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00007994
7995 const FunctionProtoType* Proto;
7996 unsigned ArgIdx = ConvIdx;
7997
7998 if (Cand->IsSurrogate) {
7999 QualType ConvType
8000 = Cand->Surrogate->getConversionType().getNonReferenceType();
8001 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8002 ConvType = ConvPtrType->getPointeeType();
8003 Proto = ConvType->getAs<FunctionProtoType>();
8004 ArgIdx--;
8005 } else if (Cand->Function) {
8006 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8007 if (isa<CXXMethodDecl>(Cand->Function) &&
8008 !isa<CXXConstructorDecl>(Cand->Function))
8009 ArgIdx--;
8010 } else {
8011 // Builtin binary operator with a bad first conversion.
8012 assert(ConvCount <= 3);
8013 for (; ConvIdx != ConvCount; ++ConvIdx)
8014 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008015 = TryCopyInitialization(S, Args[ConvIdx],
8016 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008017 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008018 /*InOverloadResolution*/ true,
8019 /*AllowObjCWritebackConversion=*/
8020 S.getLangOptions().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008021 return;
8022 }
8023
8024 // Fill in the rest of the conversions.
8025 unsigned NumArgsInProto = Proto->getNumArgs();
8026 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008027 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008028 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008029 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008030 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008031 /*InOverloadResolution=*/true,
8032 /*AllowObjCWritebackConversion=*/
8033 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008034 // Store the FixIt in the candidate if it exists.
8035 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008036 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008037 }
John McCall717e8912010-01-23 05:17:32 +00008038 else
8039 Cand->Conversions[ConvIdx].setEllipsis();
8040 }
8041}
8042
John McCalla1d7d622010-01-08 00:58:21 +00008043} // end anonymous namespace
8044
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008045/// PrintOverloadCandidates - When overload resolution fails, prints
8046/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008047/// set.
John McCall120d63c2010-08-24 20:38:10 +00008048void OverloadCandidateSet::NoteCandidates(Sema &S,
8049 OverloadCandidateDisplayKind OCD,
8050 Expr **Args, unsigned NumArgs,
8051 const char *Opc,
8052 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008053 // Sort the candidates by viability and position. Sorting directly would
8054 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008055 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008056 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8057 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008058 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008059 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008060 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00008061 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008062 if (Cand->Function || Cand->IsSurrogate)
8063 Cands.push_back(Cand);
8064 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8065 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008066 }
8067 }
8068
John McCallbf65c0b2010-01-12 00:48:53 +00008069 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008070 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008071
John McCall1d318332010-01-12 00:44:57 +00008072 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008073
Chris Lattner5f9e2722011-07-23 10:55:15 +00008074 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008075 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8076 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008077 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008078 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8079 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008080
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008081 // Set an arbitrary limit on the number of candidate functions we'll spam
8082 // the user with. FIXME: This limit should depend on details of the
8083 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008084 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008085 break;
8086 }
8087 ++CandsShown;
8088
John McCalla1d7d622010-01-08 00:58:21 +00008089 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00008090 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00008091 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008092 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008093 else {
8094 assert(Cand->Viable &&
8095 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008096 // Generally we only see ambiguities including viable builtin
8097 // operators if overload resolution got screwed up by an
8098 // ambiguous user-defined conversion.
8099 //
8100 // FIXME: It's quite possible for different conversions to see
8101 // different ambiguities, though.
8102 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008103 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008104 ReportedAmbiguousConversions = true;
8105 }
John McCalla1d7d622010-01-08 00:58:21 +00008106
John McCall1d318332010-01-12 00:44:57 +00008107 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008108 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008109 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008110 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008111
8112 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008113 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008114}
8115
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008116// [PossiblyAFunctionType] --> [Return]
8117// NonFunctionType --> NonFunctionType
8118// R (A) --> R(A)
8119// R (*)(A) --> R (A)
8120// R (&)(A) --> R (A)
8121// R (S::*)(A) --> R (A)
8122QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8123 QualType Ret = PossiblyAFunctionType;
8124 if (const PointerType *ToTypePtr =
8125 PossiblyAFunctionType->getAs<PointerType>())
8126 Ret = ToTypePtr->getPointeeType();
8127 else if (const ReferenceType *ToTypeRef =
8128 PossiblyAFunctionType->getAs<ReferenceType>())
8129 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008130 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008131 PossiblyAFunctionType->getAs<MemberPointerType>())
8132 Ret = MemTypePtr->getPointeeType();
8133 Ret =
8134 Context.getCanonicalType(Ret).getUnqualifiedType();
8135 return Ret;
8136}
Douglas Gregor904eed32008-11-10 20:40:00 +00008137
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008138// A helper class to help with address of function resolution
8139// - allows us to avoid passing around all those ugly parameters
8140class AddressOfFunctionResolver
8141{
8142 Sema& S;
8143 Expr* SourceExpr;
8144 const QualType& TargetType;
8145 QualType TargetFunctionType; // Extracted function type from target type
8146
8147 bool Complain;
8148 //DeclAccessPair& ResultFunctionAccessPair;
8149 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008150
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008151 bool TargetTypeIsNonStaticMemberFunction;
8152 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008153
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008154 OverloadExpr::FindResult OvlExprInfo;
8155 OverloadExpr *OvlExpr;
8156 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008157 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008158
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008159public:
8160 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8161 const QualType& TargetType, bool Complain)
8162 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8163 Complain(Complain), Context(S.getASTContext()),
8164 TargetTypeIsNonStaticMemberFunction(
8165 !!TargetType->getAs<MemberPointerType>()),
8166 FoundNonTemplateFunction(false),
8167 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8168 OvlExpr(OvlExprInfo.Expression)
8169 {
8170 ExtractUnqualifiedFunctionTypeFromTargetType();
8171
8172 if (!TargetFunctionType->isFunctionType()) {
8173 if (OvlExpr->hasExplicitTemplateArgs()) {
8174 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008175 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008176 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008177
8178 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8179 if (!Method->isStatic()) {
8180 // If the target type is a non-function type and the function
8181 // found is a non-static member function, pretend as if that was
8182 // the target, it's the only possible type to end up with.
8183 TargetTypeIsNonStaticMemberFunction = true;
8184
8185 // And skip adding the function if its not in the proper form.
8186 // We'll diagnose this due to an empty set of functions.
8187 if (!OvlExprInfo.HasFormOfMemberPointer)
8188 return;
8189 }
8190 }
8191
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008192 Matches.push_back(std::make_pair(dap,Fn));
8193 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008194 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008195 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008196 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008197
8198 if (OvlExpr->hasExplicitTemplateArgs())
8199 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008200
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008201 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8202 // C++ [over.over]p4:
8203 // If more than one function is selected, [...]
8204 if (Matches.size() > 1) {
8205 if (FoundNonTemplateFunction)
8206 EliminateAllTemplateMatches();
8207 else
8208 EliminateAllExceptMostSpecializedTemplate();
8209 }
8210 }
8211 }
8212
8213private:
8214 bool isTargetTypeAFunction() const {
8215 return TargetFunctionType->isFunctionType();
8216 }
8217
8218 // [ToType] [Return]
8219
8220 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8221 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8222 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8223 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8224 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8225 }
8226
8227 // return true if any matching specializations were found
8228 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8229 const DeclAccessPair& CurAccessFunPair) {
8230 if (CXXMethodDecl *Method
8231 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8232 // Skip non-static function templates when converting to pointer, and
8233 // static when converting to member pointer.
8234 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8235 return false;
8236 }
8237 else if (TargetTypeIsNonStaticMemberFunction)
8238 return false;
8239
8240 // C++ [over.over]p2:
8241 // If the name is a function template, template argument deduction is
8242 // done (14.8.2.2), and if the argument deduction succeeds, the
8243 // resulting template argument list is used to generate a single
8244 // function template specialization, which is added to the set of
8245 // overloaded functions considered.
8246 FunctionDecl *Specialization = 0;
8247 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8248 if (Sema::TemplateDeductionResult Result
8249 = S.DeduceTemplateArguments(FunctionTemplate,
8250 &OvlExplicitTemplateArgs,
8251 TargetFunctionType, Specialization,
8252 Info)) {
8253 // FIXME: make a note of the failed deduction for diagnostics.
8254 (void)Result;
8255 return false;
8256 }
8257
8258 // Template argument deduction ensures that we have an exact match.
8259 // This function template specicalization works.
8260 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8261 assert(TargetFunctionType
8262 == Context.getCanonicalType(Specialization->getType()));
8263 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8264 return true;
8265 }
8266
8267 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8268 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008269 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008270 // Skip non-static functions when converting to pointer, and static
8271 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008272 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8273 return false;
8274 }
8275 else if (TargetTypeIsNonStaticMemberFunction)
8276 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008277
Chandler Carruthbd647292009-12-29 06:17:27 +00008278 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008279 if (S.getLangOptions().CUDA)
8280 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8281 if (S.CheckCUDATarget(Caller, FunDecl))
8282 return false;
8283
Douglas Gregor43c79c22009-12-09 00:47:37 +00008284 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008285 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8286 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008287 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8288 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008289 Matches.push_back(std::make_pair(CurAccessFunPair,
8290 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008291 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008292 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008293 }
Mike Stump1eb44332009-09-09 15:08:12 +00008294 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008295
8296 return false;
8297 }
8298
8299 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8300 bool Ret = false;
8301
8302 // If the overload expression doesn't have the form of a pointer to
8303 // member, don't try to convert it to a pointer-to-member type.
8304 if (IsInvalidFormOfPointerToMemberFunction())
8305 return false;
8306
8307 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8308 E = OvlExpr->decls_end();
8309 I != E; ++I) {
8310 // Look through any using declarations to find the underlying function.
8311 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8312
8313 // C++ [over.over]p3:
8314 // Non-member functions and static member functions match
8315 // targets of type "pointer-to-function" or "reference-to-function."
8316 // Nonstatic member functions match targets of
8317 // type "pointer-to-member-function."
8318 // Note that according to DR 247, the containing class does not matter.
8319 if (FunctionTemplateDecl *FunctionTemplate
8320 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8321 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8322 Ret = true;
8323 }
8324 // If we have explicit template arguments supplied, skip non-templates.
8325 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8326 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8327 Ret = true;
8328 }
8329 assert(Ret || Matches.empty());
8330 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008331 }
8332
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008333 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008334 // [...] and any given function template specialization F1 is
8335 // eliminated if the set contains a second function template
8336 // specialization whose function template is more specialized
8337 // than the function template of F1 according to the partial
8338 // ordering rules of 14.5.5.2.
8339
8340 // The algorithm specified above is quadratic. We instead use a
8341 // two-pass algorithm (similar to the one used to identify the
8342 // best viable function in an overload set) that identifies the
8343 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008344
8345 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8346 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8347 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008348
John McCallc373d482010-01-27 01:50:18 +00008349 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008350 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8351 TPOC_Other, 0, SourceExpr->getLocStart(),
8352 S.PDiag(),
8353 S.PDiag(diag::err_addr_ovl_ambiguous)
8354 << Matches[0].second->getDeclName(),
8355 S.PDiag(diag::note_ovl_candidate)
8356 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00008357 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008358
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008359 if (Result != MatchesCopy.end()) {
8360 // Make it the first and only element
8361 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8362 Matches[0].second = cast<FunctionDecl>(*Result);
8363 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008364 }
8365 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008366
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008367 void EliminateAllTemplateMatches() {
8368 // [...] any function template specializations in the set are
8369 // eliminated if the set also contains a non-template function, [...]
8370 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8371 if (Matches[I].second->getPrimaryTemplate() == 0)
8372 ++I;
8373 else {
8374 Matches[I] = Matches[--N];
8375 Matches.set_size(N);
8376 }
8377 }
8378 }
8379
8380public:
8381 void ComplainNoMatchesFound() const {
8382 assert(Matches.empty());
8383 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8384 << OvlExpr->getName() << TargetFunctionType
8385 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008386 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008387 }
8388
8389 bool IsInvalidFormOfPointerToMemberFunction() const {
8390 return TargetTypeIsNonStaticMemberFunction &&
8391 !OvlExprInfo.HasFormOfMemberPointer;
8392 }
8393
8394 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8395 // TODO: Should we condition this on whether any functions might
8396 // have matched, or is it more appropriate to do that in callers?
8397 // TODO: a fixit wouldn't hurt.
8398 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8399 << TargetType << OvlExpr->getSourceRange();
8400 }
8401
8402 void ComplainOfInvalidConversion() const {
8403 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8404 << OvlExpr->getName() << TargetType;
8405 }
8406
8407 void ComplainMultipleMatchesFound() const {
8408 assert(Matches.size() > 1);
8409 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8410 << OvlExpr->getName()
8411 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008412 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008413 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008414
8415 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8416
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008417 int getNumMatches() const { return Matches.size(); }
8418
8419 FunctionDecl* getMatchingFunctionDecl() const {
8420 if (Matches.size() != 1) return 0;
8421 return Matches[0].second;
8422 }
8423
8424 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8425 if (Matches.size() != 1) return 0;
8426 return &Matches[0].first;
8427 }
8428};
8429
8430/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8431/// an overloaded function (C++ [over.over]), where @p From is an
8432/// expression with overloaded function type and @p ToType is the type
8433/// we're trying to resolve to. For example:
8434///
8435/// @code
8436/// int f(double);
8437/// int f(int);
8438///
8439/// int (*pfd)(double) = f; // selects f(double)
8440/// @endcode
8441///
8442/// This routine returns the resulting FunctionDecl if it could be
8443/// resolved, and NULL otherwise. When @p Complain is true, this
8444/// routine will emit diagnostics if there is an error.
8445FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008446Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8447 QualType TargetType,
8448 bool Complain,
8449 DeclAccessPair &FoundResult,
8450 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008451 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008452
8453 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8454 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008455 int NumMatches = Resolver.getNumMatches();
8456 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008457 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008458 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8459 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8460 else
8461 Resolver.ComplainNoMatchesFound();
8462 }
8463 else if (NumMatches > 1 && Complain)
8464 Resolver.ComplainMultipleMatchesFound();
8465 else if (NumMatches == 1) {
8466 Fn = Resolver.getMatchingFunctionDecl();
8467 assert(Fn);
8468 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8469 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00008470 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008471 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00008472 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008473
8474 if (pHadMultipleCandidates)
8475 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008476 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00008477}
8478
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008479/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00008480/// resolve that overloaded function expression down to a single function.
8481///
8482/// This routine can only resolve template-ids that refer to a single function
8483/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008484/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00008485/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00008486FunctionDecl *
8487Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8488 bool Complain,
8489 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008490 // C++ [over.over]p1:
8491 // [...] [Note: any redundant set of parentheses surrounding the
8492 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00008493 // C++ [over.over]p1:
8494 // [...] The overloaded function name can be preceded by the &
8495 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008496
Douglas Gregor4b52e252009-12-21 23:17:24 +00008497 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00008498 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00008499 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00008500
8501 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00008502 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008503
Douglas Gregor4b52e252009-12-21 23:17:24 +00008504 // Look through all of the overloaded functions, searching for one
8505 // whose type matches exactly.
8506 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00008507 for (UnresolvedSetIterator I = ovl->decls_begin(),
8508 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008509 // C++0x [temp.arg.explicit]p3:
8510 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008511 // where deduction is not done, if a template argument list is
8512 // specified and it, along with any default template arguments,
8513 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00008514 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00008515 FunctionTemplateDecl *FunctionTemplate
8516 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008517
Douglas Gregor4b52e252009-12-21 23:17:24 +00008518 // C++ [over.over]p2:
8519 // If the name is a function template, template argument deduction is
8520 // done (14.8.2.2), and if the argument deduction succeeds, the
8521 // resulting template argument list is used to generate a single
8522 // function template specialization, which is added to the set of
8523 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00008524 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00008525 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00008526 if (TemplateDeductionResult Result
8527 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8528 Specialization, Info)) {
8529 // FIXME: make a note of the failed deduction for diagnostics.
8530 (void)Result;
8531 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008532 }
8533
John McCall864c0412011-04-26 20:42:42 +00008534 assert(Specialization && "no specialization and no error?");
8535
Douglas Gregor4b52e252009-12-21 23:17:24 +00008536 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008537 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008538 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00008539 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8540 << ovl->getName();
8541 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008542 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00008543 return 0;
John McCall864c0412011-04-26 20:42:42 +00008544 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008545
John McCall864c0412011-04-26 20:42:42 +00008546 Matched = Specialization;
8547 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00008548 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008549
Douglas Gregor4b52e252009-12-21 23:17:24 +00008550 return Matched;
8551}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008552
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008553
8554
8555
John McCall6dbba4f2011-10-11 23:14:30 +00008556// Resolve and fix an overloaded expression that can be resolved
8557// because it identifies a single function template specialization.
8558//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008559// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00008560//
8561// Return true if it was logically possible to so resolve the
8562// expression, regardless of whether or not it succeeded. Always
8563// returns true if 'complain' is set.
8564bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8565 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8566 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008567 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00008568 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00008569 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008570
John McCall6dbba4f2011-10-11 23:14:30 +00008571 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008572
John McCall864c0412011-04-26 20:42:42 +00008573 DeclAccessPair found;
8574 ExprResult SingleFunctionExpression;
8575 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8576 ovl.Expression, /*complain*/ false, &found)) {
John McCall6dbba4f2011-10-11 23:14:30 +00008577 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8578 SrcExpr = ExprError();
8579 return true;
8580 }
John McCall864c0412011-04-26 20:42:42 +00008581
8582 // It is only correct to resolve to an instance method if we're
8583 // resolving a form that's permitted to be a pointer to member.
8584 // Otherwise we'll end up making a bound member expression, which
8585 // is illegal in all the contexts we resolve like this.
8586 if (!ovl.HasFormOfMemberPointer &&
8587 isa<CXXMethodDecl>(fn) &&
8588 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00008589 if (!complain) return false;
8590
8591 Diag(ovl.Expression->getExprLoc(),
8592 diag::err_bound_member_function)
8593 << 0 << ovl.Expression->getSourceRange();
8594
8595 // TODO: I believe we only end up here if there's a mix of
8596 // static and non-static candidates (otherwise the expression
8597 // would have 'bound member' type, not 'overload' type).
8598 // Ideally we would note which candidate was chosen and why
8599 // the static candidates were rejected.
8600 SrcExpr = ExprError();
8601 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008602 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00008603
John McCall864c0412011-04-26 20:42:42 +00008604 // Fix the expresion to refer to 'fn'.
8605 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00008606 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00008607
8608 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00008609 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00008610 SingleFunctionExpression =
8611 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00008612 if (SingleFunctionExpression.isInvalid()) {
8613 SrcExpr = ExprError();
8614 return true;
8615 }
8616 }
John McCall864c0412011-04-26 20:42:42 +00008617 }
8618
8619 if (!SingleFunctionExpression.isUsable()) {
8620 if (complain) {
8621 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8622 << ovl.Expression->getName()
8623 << DestTypeForComplaining
8624 << OpRangeForComplaining
8625 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00008626 NoteAllOverloadCandidates(SrcExpr.get());
8627
8628 SrcExpr = ExprError();
8629 return true;
8630 }
8631
8632 return false;
John McCall864c0412011-04-26 20:42:42 +00008633 }
8634
John McCall6dbba4f2011-10-11 23:14:30 +00008635 SrcExpr = SingleFunctionExpression;
8636 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008637}
8638
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008639/// \brief Add a single candidate to the overload set.
8640static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00008641 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00008642 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008643 Expr **Args, unsigned NumArgs,
8644 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008645 bool PartialOverloading,
8646 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00008647 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00008648 if (isa<UsingShadowDecl>(Callee))
8649 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8650
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008651 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00008652 if (ExplicitTemplateArgs) {
8653 assert(!KnownValid && "Explicit template arguments?");
8654 return;
8655 }
John McCall9aa472c2010-03-19 07:35:19 +00008656 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00008657 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008658 return;
John McCallba135432009-11-21 08:51:07 +00008659 }
8660
8661 if (FunctionTemplateDecl *FuncTemplate
8662 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00008663 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8664 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00008665 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00008666 return;
8667 }
8668
Richard Smith2ced0442011-06-26 22:19:54 +00008669 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008670}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008671
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008672/// \brief Add the overload candidates named by callee and/or found by argument
8673/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00008674void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008675 Expr **Args, unsigned NumArgs,
8676 OverloadCandidateSet &CandidateSet,
8677 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00008678
8679#ifndef NDEBUG
8680 // Verify that ArgumentDependentLookup is consistent with the rules
8681 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008682 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008683 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8684 // and let Y be the lookup set produced by argument dependent
8685 // lookup (defined as follows). If X contains
8686 //
8687 // -- a declaration of a class member, or
8688 //
8689 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00008690 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008691 //
8692 // -- a declaration that is neither a function or a function
8693 // template
8694 //
8695 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00008696
John McCall3b4294e2009-12-16 12:17:52 +00008697 if (ULE->requiresADL()) {
8698 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8699 E = ULE->decls_end(); I != E; ++I) {
8700 assert(!(*I)->getDeclContext()->isRecord());
8701 assert(isa<UsingShadowDecl>(*I) ||
8702 !(*I)->getDeclContext()->isFunctionOrMethod());
8703 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00008704 }
8705 }
8706#endif
8707
John McCall3b4294e2009-12-16 12:17:52 +00008708 // It would be nice to avoid this copy.
8709 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00008710 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008711 if (ULE->hasExplicitTemplateArgs()) {
8712 ULE->copyTemplateArgumentsInto(TABuffer);
8713 ExplicitTemplateArgs = &TABuffer;
8714 }
8715
8716 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8717 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00008718 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008719 Args, NumArgs, CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008720 PartialOverloading, /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00008721
John McCall3b4294e2009-12-16 12:17:52 +00008722 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00008723 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8724 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008725 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008726 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00008727 PartialOverloading,
8728 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008729}
John McCall578b69b2009-12-16 08:11:27 +00008730
Richard Smithf50e88a2011-06-05 22:42:48 +00008731/// Attempt to recover from an ill-formed use of a non-dependent name in a
8732/// template, where the non-dependent name was declared after the template
8733/// was defined. This is common in code written for a compilers which do not
8734/// correctly implement two-stage name lookup.
8735///
8736/// Returns true if a viable candidate was found and a diagnostic was issued.
8737static bool
8738DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8739 const CXXScopeSpec &SS, LookupResult &R,
8740 TemplateArgumentListInfo *ExplicitTemplateArgs,
8741 Expr **Args, unsigned NumArgs) {
8742 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8743 return false;
8744
8745 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8746 SemaRef.LookupQualifiedName(R, DC);
8747
8748 if (!R.empty()) {
8749 R.suppressDiagnostics();
8750
8751 if (isa<CXXRecordDecl>(DC)) {
8752 // Don't diagnose names we find in classes; we get much better
8753 // diagnostics for these from DiagnoseEmptyLookup.
8754 R.clear();
8755 return false;
8756 }
8757
8758 OverloadCandidateSet Candidates(FnLoc);
8759 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8760 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8761 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith2ced0442011-06-26 22:19:54 +00008762 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00008763
8764 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00008765 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008766 // No viable functions. Don't bother the user with notes for functions
8767 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00008768 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00008769 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00008770 }
Richard Smithf50e88a2011-06-05 22:42:48 +00008771
8772 // Find the namespaces where ADL would have looked, and suggest
8773 // declaring the function there instead.
8774 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8775 Sema::AssociatedClassSet AssociatedClasses;
8776 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8777 AssociatedNamespaces,
8778 AssociatedClasses);
8779 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00008780 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008781 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008782 for (Sema::AssociatedNamespaceSet::iterator
8783 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00008784 end = AssociatedNamespaces.end(); it != end; ++it) {
8785 if (!Std->Encloses(*it))
8786 SuggestedNamespaces.insert(*it);
8787 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00008788 } else {
8789 // Lacking the 'std::' namespace, use all of the associated namespaces.
8790 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008791 }
8792
8793 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8794 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00008795 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008796 SemaRef.Diag(Best->Function->getLocation(),
8797 diag::note_not_found_by_two_phase_lookup)
8798 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00008799 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008800 SemaRef.Diag(Best->Function->getLocation(),
8801 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00008802 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00008803 } else {
8804 // FIXME: It would be useful to list the associated namespaces here,
8805 // but the diagnostics infrastructure doesn't provide a way to produce
8806 // a localized representation of a list of items.
8807 SemaRef.Diag(Best->Function->getLocation(),
8808 diag::note_not_found_by_two_phase_lookup)
8809 << R.getLookupName() << 2;
8810 }
8811
8812 // Try to recover by calling this function.
8813 return true;
8814 }
8815
8816 R.clear();
8817 }
8818
8819 return false;
8820}
8821
8822/// Attempt to recover from ill-formed use of a non-dependent operator in a
8823/// template, where the non-dependent operator was declared after the template
8824/// was defined.
8825///
8826/// Returns true if a viable candidate was found and a diagnostic was issued.
8827static bool
8828DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8829 SourceLocation OpLoc,
8830 Expr **Args, unsigned NumArgs) {
8831 DeclarationName OpName =
8832 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8833 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8834 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8835 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8836}
8837
John McCall578b69b2009-12-16 08:11:27 +00008838/// Attempts to recover from a call where no functions were found.
8839///
8840/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00008841static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008842BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00008843 UnresolvedLookupExpr *ULE,
8844 SourceLocation LParenLoc,
8845 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008846 SourceLocation RParenLoc,
8847 bool EmptyLookup) {
John McCall578b69b2009-12-16 08:11:27 +00008848
8849 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00008850 SS.Adopt(ULE->getQualifierLoc());
John McCall578b69b2009-12-16 08:11:27 +00008851
John McCall3b4294e2009-12-16 12:17:52 +00008852 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00008853 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008854 if (ULE->hasExplicitTemplateArgs()) {
8855 ULE->copyTemplateArgumentsInto(TABuffer);
8856 ExplicitTemplateArgs = &TABuffer;
8857 }
8858
John McCall578b69b2009-12-16 08:11:27 +00008859 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8860 Sema::LookupOrdinaryName);
Richard Smithf50e88a2011-06-05 22:42:48 +00008861 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8862 ExplicitTemplateArgs, Args, NumArgs) &&
8863 (!EmptyLookup ||
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00008864 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00008865 ExplicitTemplateArgs, Args, NumArgs)))
John McCallf312b1e2010-08-26 23:41:50 +00008866 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00008867
John McCall3b4294e2009-12-16 12:17:52 +00008868 assert(!R.empty() && "lookup results empty despite recovery");
8869
8870 // Build an implicit member call if appropriate. Just drop the
8871 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00008872 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008873 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00008874 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8875 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00008876 else if (ExplicitTemplateArgs)
8877 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8878 else
8879 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8880
8881 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008882 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008883
8884 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00008885 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00008886 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00008887 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00008888 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00008889}
Douglas Gregord7a95972010-06-08 17:35:15 +00008890
Douglas Gregorf6b89692008-11-26 05:54:23 +00008891/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00008892/// (which eventually refers to the declaration Func) and the call
8893/// arguments Args/NumArgs, attempt to resolve the function call down
8894/// to a specific function. If overload resolution succeeds, returns
8895/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00008896/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00008897/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00008898ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008899Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00008900 SourceLocation LParenLoc,
8901 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00008902 SourceLocation RParenLoc,
8903 Expr *ExecConfig) {
John McCall3b4294e2009-12-16 12:17:52 +00008904#ifndef NDEBUG
8905 if (ULE->requiresADL()) {
8906 // To do ADL, we must have found an unqualified name.
8907 assert(!ULE->getQualifier() && "qualified name with ADL");
8908
8909 // We don't perform ADL for implicit declarations of builtins.
8910 // Verify that this was correctly set up.
8911 FunctionDecl *F;
8912 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8913 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8914 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00008915 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008916
John McCall3b4294e2009-12-16 12:17:52 +00008917 // We don't perform ADL in C.
8918 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00008919 } else
8920 assert(!ULE->isStdAssociatedNamespace() &&
8921 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00008922#endif
8923
John McCall5acb0c92011-10-17 18:40:02 +00008924 UnbridgedCastsSet UnbridgedCasts;
8925 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8926 return ExprError();
8927
John McCall5769d612010-02-08 23:07:23 +00008928 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00008929
John McCall3b4294e2009-12-16 12:17:52 +00008930 // Add the functions denoted by the callee to the set of candidate
8931 // functions, including those from argument-dependent lookup.
8932 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00008933
8934 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00008935 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8936 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008937 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00008938 // In Microsoft mode, if we are inside a template class member function then
8939 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008940 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00008941 // classes.
Francois Pichetef04ecf2011-11-11 00:12:11 +00008942 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00008943 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00008944 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8945 Context.DependentTy, VK_RValue,
8946 RParenLoc);
8947 CE->setTypeDependent(true);
8948 return Owned(CE);
8949 }
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008950 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008951 RParenLoc, /*EmptyLookup=*/true);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008952 }
John McCall578b69b2009-12-16 08:11:27 +00008953
John McCall5acb0c92011-10-17 18:40:02 +00008954 UnbridgedCasts.restore();
8955
Douglas Gregorf6b89692008-11-26 05:54:23 +00008956 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008957 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00008958 case OR_Success: {
8959 FunctionDecl *FDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00008960 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00008961 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00008962 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00008963 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00008964 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8965 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00008966 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008967
Richard Smithf50e88a2011-06-05 22:42:48 +00008968 case OR_No_Viable_Function: {
8969 // Try to recover by looking for viable functions which the user might
8970 // have meant to call.
8971 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8972 Args, NumArgs, RParenLoc,
8973 /*EmptyLookup=*/false);
8974 if (!Recovery.isInvalid())
8975 return Recovery;
8976
Chris Lattner4330d652009-02-17 07:29:20 +00008977 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00008978 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00008979 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008980 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008981 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00008982 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008983
8984 case OR_Ambiguous:
8985 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00008986 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008987 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008988 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008989
8990 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008991 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008992 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8993 << Best->Function->isDeleted()
8994 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008995 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008996 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008997 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00008998
8999 // We emitted an error for the unvailable/deleted function call but keep
9000 // the call in the AST.
9001 FunctionDecl *FDecl = Best->Function;
9002 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9003 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9004 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009005 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009006 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00009007 }
9008
Douglas Gregorff331c12010-07-25 18:17:45 +00009009 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009010 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009011}
9012
John McCall6e266892010-01-26 03:27:55 +00009013static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009014 return Functions.size() > 1 ||
9015 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9016}
9017
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009018/// \brief Create a unary operation that may resolve to an overloaded
9019/// operator.
9020///
9021/// \param OpLoc The location of the operator itself (e.g., '*').
9022///
9023/// \param OpcIn The UnaryOperator::Opcode that describes this
9024/// operator.
9025///
9026/// \param Functions The set of non-member functions that will be
9027/// considered by overload resolution. The caller needs to build this
9028/// set based on the context using, e.g.,
9029/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9030/// set should not contain any member functions; those will be added
9031/// by CreateOverloadedUnaryOp().
9032///
9033/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009034ExprResult
John McCall6e266892010-01-26 03:27:55 +00009035Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9036 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009037 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009038 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009039
9040 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9041 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9042 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009043 // TODO: provide better source location info.
9044 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009045
John McCall5acb0c92011-10-17 18:40:02 +00009046 if (checkPlaceholderForOverload(*this, Input))
9047 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009048
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009049 Expr *Args[2] = { Input, 0 };
9050 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009051
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009052 // For post-increment and post-decrement, add the implicit '0' as
9053 // the second argument, so that we know this is a post-increment or
9054 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009055 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009056 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009057 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9058 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009059 NumArgs = 2;
9060 }
9061
9062 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009063 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009064 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009065 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009066 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009067 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009068 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009069
John McCallc373d482010-01-27 01:50:18 +00009070 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009071 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009072 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009073 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009074 /*ADL*/ true, IsOverloaded(Fns),
9075 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009076 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009077 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009078 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009079 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009080 OpLoc));
9081 }
9082
9083 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009084 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009085
9086 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009087 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009088
9089 // Add operator candidates that are member functions.
9090 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9091
John McCall6e266892010-01-26 03:27:55 +00009092 // Add candidates from ADL.
9093 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00009094 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00009095 /*ExplicitTemplateArgs*/ 0,
9096 CandidateSet);
9097
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009098 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009099 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009100
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009101 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9102
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009103 // Perform overload resolution.
9104 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009105 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009106 case OR_Success: {
9107 // We found a built-in operator or an overloaded operator.
9108 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009109
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009110 if (FnDecl) {
9111 // We matched an overloaded operator. Build a call to that
9112 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009113
Chandler Carruth25ca4212011-02-25 19:41:05 +00009114 MarkDeclarationReferenced(OpLoc, FnDecl);
9115
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009116 // Convert the arguments.
9117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009118 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009119
John Wiegley429bb272011-04-08 18:41:53 +00009120 ExprResult InputRes =
9121 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9122 Best->FoundDecl, Method);
9123 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009124 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009125 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009126 } else {
9127 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009128 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009129 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009130 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009131 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009132 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009133 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009134 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009135 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009136 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009137 }
9138
John McCallb697e082010-05-06 18:15:07 +00009139 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9140
John McCallf89e55a2010-11-18 06:31:45 +00009141 // Determine the result type.
9142 QualType ResultTy = FnDecl->getResultType();
9143 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9144 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009145
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009146 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009147 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9148 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +00009149 if (FnExpr.isInvalid())
9150 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009151
Eli Friedman4c3b8962009-11-18 03:58:17 +00009152 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009153 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009154 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009155 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009156
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009157 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009158 FnDecl))
9159 return ExprError();
9160
John McCall9ae2f072010-08-23 23:25:46 +00009161 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009162 } else {
9163 // We matched a built-in operator. Convert the arguments, then
9164 // break out so that we will build the appropriate built-in
9165 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009166 ExprResult InputRes =
9167 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9168 Best->Conversions[0], AA_Passing);
9169 if (InputRes.isInvalid())
9170 return ExprError();
9171 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009172 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009173 }
John Wiegley429bb272011-04-08 18:41:53 +00009174 }
9175
9176 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009177 // This is an erroneous use of an operator which can be overloaded by
9178 // a non-member function. Check for non-member operators which were
9179 // defined too late to be candidates.
9180 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9181 // FIXME: Recover by calling the found function.
9182 return ExprError();
9183
John Wiegley429bb272011-04-08 18:41:53 +00009184 // No viable function; fall through to handling this as a
9185 // built-in operator, which will produce an error message for us.
9186 break;
9187
9188 case OR_Ambiguous:
9189 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9190 << UnaryOperator::getOpcodeStr(Opc)
9191 << Input->getType()
9192 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009193 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley429bb272011-04-08 18:41:53 +00009194 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9195 return ExprError();
9196
9197 case OR_Deleted:
9198 Diag(OpLoc, diag::err_ovl_deleted_oper)
9199 << Best->Function->isDeleted()
9200 << UnaryOperator::getOpcodeStr(Opc)
9201 << getDeletedOrUnavailableSuffix(Best->Function)
9202 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009203 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9204 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009205 return ExprError();
9206 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009207
9208 // Either we found no viable overloaded operator or we matched a
9209 // built-in operator. In either case, fall through to trying to
9210 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00009211 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009212}
9213
Douglas Gregor063daf62009-03-13 18:40:31 +00009214/// \brief Create a binary operation that may resolve to an overloaded
9215/// operator.
9216///
9217/// \param OpLoc The location of the operator itself (e.g., '+').
9218///
9219/// \param OpcIn The BinaryOperator::Opcode that describes this
9220/// operator.
9221///
9222/// \param Functions The set of non-member functions that will be
9223/// considered by overload resolution. The caller needs to build this
9224/// set based on the context using, e.g.,
9225/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9226/// set should not contain any member functions; those will be added
9227/// by CreateOverloadedBinOp().
9228///
9229/// \param LHS Left-hand argument.
9230/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009231ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00009232Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00009233 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009234 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009235 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009236 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009237 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009238
9239 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9240 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9241 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9242
9243 // If either side is type-dependent, create an appropriate dependent
9244 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009245 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009246 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009247 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009248 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009249 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009250 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009251 Context.DependentTy,
9252 VK_RValue, OK_Ordinary,
9253 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009254
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009255 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9256 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009257 VK_LValue,
9258 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009259 Context.DependentTy,
9260 Context.DependentTy,
9261 OpLoc));
9262 }
John McCall6e266892010-01-26 03:27:55 +00009263
9264 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009265 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009266 // TODO: provide better source location info in DNLoc component.
9267 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009268 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009269 = UnresolvedLookupExpr::Create(Context, NamingClass,
9270 NestedNameSpecifierLoc(), OpNameInfo,
9271 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009272 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009273 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009274 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009275 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009276 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009277 OpLoc));
9278 }
9279
John McCall5acb0c92011-10-17 18:40:02 +00009280 // Always do placeholder-like conversions on the RHS.
9281 if (checkPlaceholderForOverload(*this, Args[1]))
9282 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009283
John McCall3c3b7f92011-10-25 17:37:35 +00009284 // Do placeholder-like conversion on the LHS; note that we should
9285 // not get here with a PseudoObject LHS.
9286 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009287 if (checkPlaceholderForOverload(*this, Args[0]))
9288 return ExprError();
9289
Sebastian Redl275c2b42009-11-18 23:10:33 +00009290 // If this is the assignment operator, we only perform overload resolution
9291 // if the left-hand side is a class or enumeration type. This is actually
9292 // a hack. The standard requires that we do overload resolution between the
9293 // various built-in candidates, but as DR507 points out, this can lead to
9294 // problems. So we do it this way, which pretty much follows what GCC does.
9295 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009296 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009297 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009298
John McCall0e800c92010-12-04 08:14:53 +00009299 // If this is the .* operator, which is not overloadable, just
9300 // create a built-in binary operator.
9301 if (Opc == BO_PtrMemD)
9302 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9303
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009304 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009305 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009306
9307 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009308 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009309
9310 // Add operator candidates that are member functions.
9311 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9312
John McCall6e266892010-01-26 03:27:55 +00009313 // Add candidates from ADL.
9314 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9315 Args, 2,
9316 /*ExplicitTemplateArgs*/ 0,
9317 CandidateSet);
9318
Douglas Gregor063daf62009-03-13 18:40:31 +00009319 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009320 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009321
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009322 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9323
Douglas Gregor063daf62009-03-13 18:40:31 +00009324 // Perform overload resolution.
9325 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009326 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00009327 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00009328 // We found a built-in operator or an overloaded operator.
9329 FunctionDecl *FnDecl = Best->Function;
9330
9331 if (FnDecl) {
9332 // We matched an overloaded operator. Build a call to that
9333 // operator.
9334
Chandler Carruth25ca4212011-02-25 19:41:05 +00009335 MarkDeclarationReferenced(OpLoc, FnDecl);
9336
Douglas Gregor063daf62009-03-13 18:40:31 +00009337 // Convert the arguments.
9338 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00009339 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00009340 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009341
Chandler Carruth6df868e2010-12-12 08:17:55 +00009342 ExprResult Arg1 =
9343 PerformCopyInitialization(
9344 InitializedEntity::InitializeParameter(Context,
9345 FnDecl->getParamDecl(0)),
9346 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009347 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009348 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009349
John Wiegley429bb272011-04-08 18:41:53 +00009350 ExprResult Arg0 =
9351 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9352 Best->FoundDecl, Method);
9353 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009354 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009355 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009356 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009357 } else {
9358 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00009359 ExprResult Arg0 = PerformCopyInitialization(
9360 InitializedEntity::InitializeParameter(Context,
9361 FnDecl->getParamDecl(0)),
9362 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009363 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009364 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009365
Chandler Carruth6df868e2010-12-12 08:17:55 +00009366 ExprResult Arg1 =
9367 PerformCopyInitialization(
9368 InitializedEntity::InitializeParameter(Context,
9369 FnDecl->getParamDecl(1)),
9370 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009371 if (Arg1.isInvalid())
9372 return ExprError();
9373 Args[0] = LHS = Arg0.takeAs<Expr>();
9374 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009375 }
9376
John McCallb697e082010-05-06 18:15:07 +00009377 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9378
John McCallf89e55a2010-11-18 06:31:45 +00009379 // Determine the result type.
9380 QualType ResultTy = FnDecl->getResultType();
9381 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9382 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00009383
9384 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009385 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9386 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009387 if (FnExpr.isInvalid())
9388 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00009389
John McCall9ae2f072010-08-23 23:25:46 +00009390 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009391 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009392 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009393
9394 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009395 FnDecl))
9396 return ExprError();
9397
John McCall9ae2f072010-08-23 23:25:46 +00009398 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00009399 } else {
9400 // We matched a built-in operator. Convert the arguments, then
9401 // break out so that we will build the appropriate built-in
9402 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009403 ExprResult ArgsRes0 =
9404 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9405 Best->Conversions[0], AA_Passing);
9406 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009407 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009408 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009409
John Wiegley429bb272011-04-08 18:41:53 +00009410 ExprResult ArgsRes1 =
9411 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9412 Best->Conversions[1], AA_Passing);
9413 if (ArgsRes1.isInvalid())
9414 return ExprError();
9415 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009416 break;
9417 }
9418 }
9419
Douglas Gregor33074752009-09-30 21:46:01 +00009420 case OR_No_Viable_Function: {
9421 // C++ [over.match.oper]p9:
9422 // If the operator is the operator , [...] and there are no
9423 // viable functions, then the operator is assumed to be the
9424 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00009425 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00009426 break;
9427
Chandler Carruth6df868e2010-12-12 08:17:55 +00009428 // For class as left operand for assignment or compound assigment
9429 // operator do not fall through to handling in built-in, but report that
9430 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00009431 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009432 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00009433 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00009434 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9435 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009436 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00009437 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +00009438 // This is an erroneous use of an operator which can be overloaded by
9439 // a non-member function. Check for non-member operators which were
9440 // defined too late to be candidates.
9441 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9442 // FIXME: Recover by calling the found function.
9443 return ExprError();
9444
Douglas Gregor33074752009-09-30 21:46:01 +00009445 // No viable function; try to create a built-in operation, which will
9446 // produce an error. Then, show the non-viable candidates.
9447 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00009448 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009449 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00009450 "C++ binary operator overloading is missing candidates!");
9451 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00009452 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9453 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00009454 return move(Result);
9455 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009456
9457 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009458 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00009459 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00009460 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009461 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009462 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9463 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009464 return ExprError();
9465
9466 case OR_Deleted:
9467 Diag(OpLoc, diag::err_ovl_deleted_oper)
9468 << Best->Function->isDeleted()
9469 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009470 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009471 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009472 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9473 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009474 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00009475 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009476
Douglas Gregor33074752009-09-30 21:46:01 +00009477 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009478 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009479}
9480
John McCall60d7b3a2010-08-24 06:29:42 +00009481ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00009482Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9483 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009484 Expr *Base, Expr *Idx) {
9485 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00009486 DeclarationName OpName =
9487 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9488
9489 // If either side is type-dependent, create an appropriate dependent
9490 // expression.
9491 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9492
John McCallc373d482010-01-27 01:50:18 +00009493 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009494 // CHECKME: no 'operator' keyword?
9495 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9496 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00009497 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009498 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009499 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009500 /*ADL*/ true, /*Overloaded*/ false,
9501 UnresolvedSetIterator(),
9502 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00009503 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00009504
Sebastian Redlf322ed62009-10-29 20:17:01 +00009505 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9506 Args, 2,
9507 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009508 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00009509 RLoc));
9510 }
9511
John McCall5acb0c92011-10-17 18:40:02 +00009512 // Handle placeholders on both operands.
9513 if (checkPlaceholderForOverload(*this, Args[0]))
9514 return ExprError();
9515 if (checkPlaceholderForOverload(*this, Args[1]))
9516 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009517
Sebastian Redlf322ed62009-10-29 20:17:01 +00009518 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009519 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009520
9521 // Subscript can only be overloaded as a member function.
9522
9523 // Add operator candidates that are member functions.
9524 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9525
9526 // Add builtin operator candidates.
9527 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9528
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009529 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9530
Sebastian Redlf322ed62009-10-29 20:17:01 +00009531 // Perform overload resolution.
9532 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009533 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00009534 case OR_Success: {
9535 // We found a built-in operator or an overloaded operator.
9536 FunctionDecl *FnDecl = Best->Function;
9537
9538 if (FnDecl) {
9539 // We matched an overloaded operator. Build a call to that
9540 // operator.
9541
Chandler Carruth25ca4212011-02-25 19:41:05 +00009542 MarkDeclarationReferenced(LLoc, FnDecl);
9543
John McCall9aa472c2010-03-19 07:35:19 +00009544 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009545 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00009546
Sebastian Redlf322ed62009-10-29 20:17:01 +00009547 // Convert the arguments.
9548 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +00009549 ExprResult Arg0 =
9550 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9551 Best->FoundDecl, Method);
9552 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00009553 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009554 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009555
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009556 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009557 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009558 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009559 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009560 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009561 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009562 Owned(Args[1]));
9563 if (InputInit.isInvalid())
9564 return ExprError();
9565
9566 Args[1] = InputInit.takeAs<Expr>();
9567
Sebastian Redlf322ed62009-10-29 20:17:01 +00009568 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00009569 QualType ResultTy = FnDecl->getResultType();
9570 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9571 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009572
9573 // Build the actual expression node.
Douglas Gregor5b8968c2011-07-15 16:25:15 +00009574 DeclarationNameLoc LocInfo;
9575 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9576 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009577 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9578 HadMultipleCandidates,
9579 LLoc, LocInfo);
John Wiegley429bb272011-04-08 18:41:53 +00009580 if (FnExpr.isInvalid())
9581 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009582
John McCall9ae2f072010-08-23 23:25:46 +00009583 CXXOperatorCallExpr *TheCall =
9584 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +00009585 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00009586 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009587
John McCall9ae2f072010-08-23 23:25:46 +00009588 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00009589 FnDecl))
9590 return ExprError();
9591
John McCall9ae2f072010-08-23 23:25:46 +00009592 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009593 } else {
9594 // We matched a built-in operator. Convert the arguments, then
9595 // break out so that we will build the appropriate built-in
9596 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009597 ExprResult ArgsRes0 =
9598 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9599 Best->Conversions[0], AA_Passing);
9600 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00009601 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009602 Args[0] = ArgsRes0.take();
9603
9604 ExprResult ArgsRes1 =
9605 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9606 Best->Conversions[1], AA_Passing);
9607 if (ArgsRes1.isInvalid())
9608 return ExprError();
9609 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009610
9611 break;
9612 }
9613 }
9614
9615 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00009616 if (CandidateSet.empty())
9617 Diag(LLoc, diag::err_ovl_no_oper)
9618 << Args[0]->getType() << /*subscript*/ 0
9619 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9620 else
9621 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9622 << Args[0]->getType()
9623 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009624 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9625 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00009626 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009627 }
9628
9629 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009630 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009631 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +00009632 << Args[0]->getType() << Args[1]->getType()
9633 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009634 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9635 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009636 return ExprError();
9637
9638 case OR_Deleted:
9639 Diag(LLoc, diag::err_ovl_deleted_oper)
9640 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009641 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +00009642 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009643 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9644 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009645 return ExprError();
9646 }
9647
9648 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00009649 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009650}
9651
Douglas Gregor88a35142008-12-22 05:46:06 +00009652/// BuildCallToMemberFunction - Build a call to a member
9653/// function. MemExpr is the expression that refers to the member
9654/// function (and includes the object parameter), Args/NumArgs are the
9655/// arguments to the function call (not including the object
9656/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +00009657/// expression refers to a non-static member function or an overloaded
9658/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +00009659ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00009660Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9661 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00009662 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +00009663 assert(MemExprE->getType() == Context.BoundMemberTy ||
9664 MemExprE->getType() == Context.OverloadTy);
9665
Douglas Gregor88a35142008-12-22 05:46:06 +00009666 // Dig out the member expression. This holds both the object
9667 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00009668 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009669
John McCall864c0412011-04-26 20:42:42 +00009670 // Determine whether this is a call to a pointer-to-member function.
9671 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9672 assert(op->getType() == Context.BoundMemberTy);
9673 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9674
9675 QualType fnType =
9676 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9677
9678 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9679 QualType resultType = proto->getCallResultType(Context);
9680 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9681
9682 // Check that the object type isn't more qualified than the
9683 // member function we're calling.
9684 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9685
9686 QualType objectType = op->getLHS()->getType();
9687 if (op->getOpcode() == BO_PtrMemI)
9688 objectType = objectType->castAs<PointerType>()->getPointeeType();
9689 Qualifiers objectQuals = objectType.getQualifiers();
9690
9691 Qualifiers difference = objectQuals - funcQuals;
9692 difference.removeObjCGCAttr();
9693 difference.removeAddressSpace();
9694 if (difference) {
9695 std::string qualsString = difference.getAsString();
9696 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9697 << fnType.getUnqualifiedType()
9698 << qualsString
9699 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9700 }
9701
9702 CXXMemberCallExpr *call
9703 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9704 resultType, valueKind, RParenLoc);
9705
9706 if (CheckCallReturnType(proto->getResultType(),
9707 op->getRHS()->getSourceRange().getBegin(),
9708 call, 0))
9709 return ExprError();
9710
9711 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9712 return ExprError();
9713
9714 return MaybeBindToTemporary(call);
9715 }
9716
John McCall5acb0c92011-10-17 18:40:02 +00009717 UnbridgedCastsSet UnbridgedCasts;
9718 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9719 return ExprError();
9720
John McCall129e2df2009-11-30 22:42:35 +00009721 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00009722 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00009723 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009724 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00009725 if (isa<MemberExpr>(NakedMemExpr)) {
9726 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00009727 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00009728 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00009729 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +00009730 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +00009731 } else {
9732 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009733 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009734
John McCall701c89e2009-12-03 04:06:58 +00009735 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009736 Expr::Classification ObjectClassification
9737 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9738 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +00009739
Douglas Gregor88a35142008-12-22 05:46:06 +00009740 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00009741 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00009742
John McCallaa81e162009-12-01 22:10:20 +00009743 // FIXME: avoid copy.
9744 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9745 if (UnresExpr->hasExplicitTemplateArgs()) {
9746 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9747 TemplateArgs = &TemplateArgsBuffer;
9748 }
9749
John McCall129e2df2009-11-30 22:42:35 +00009750 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9751 E = UnresExpr->decls_end(); I != E; ++I) {
9752
John McCall701c89e2009-12-03 04:06:58 +00009753 NamedDecl *Func = *I;
9754 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9755 if (isa<UsingShadowDecl>(Func))
9756 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9757
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009758
Francois Pichetdbee3412011-01-18 05:04:39 +00009759 // Microsoft supports direct constructor calls.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009760 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichetdbee3412011-01-18 05:04:39 +00009761 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9762 CandidateSet);
9763 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009764 // If explicit template arguments were provided, we can't call a
9765 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00009766 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009767 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009768
John McCall9aa472c2010-03-19 07:35:19 +00009769 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009770 ObjectClassification,
9771 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009772 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009773 } else {
John McCall129e2df2009-11-30 22:42:35 +00009774 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00009775 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009776 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009777 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00009778 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009779 }
Douglas Gregordec06662009-08-21 18:42:58 +00009780 }
Mike Stump1eb44332009-09-09 15:08:12 +00009781
John McCall129e2df2009-11-30 22:42:35 +00009782 DeclarationName DeclName = UnresExpr->getMemberName();
9783
John McCall5acb0c92011-10-17 18:40:02 +00009784 UnbridgedCasts.restore();
9785
Douglas Gregor88a35142008-12-22 05:46:06 +00009786 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009787 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00009788 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00009789 case OR_Success:
9790 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009791 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +00009792 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00009793 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009794 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00009795 break;
9796
9797 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00009798 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00009799 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009800 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009801 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009802 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009803 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009804
9805 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00009806 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009807 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009809 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009810 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009811
9812 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00009813 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009814 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009815 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009816 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009817 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009818 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009819 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009820 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009821 }
9822
John McCall6bb80172010-03-30 21:47:33 +00009823 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00009824
John McCallaa81e162009-12-01 22:10:20 +00009825 // If overload resolution picked a static member, build a
9826 // non-member call based on that function.
9827 if (Method->isStatic()) {
9828 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9829 Args, NumArgs, RParenLoc);
9830 }
9831
John McCall129e2df2009-11-30 22:42:35 +00009832 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00009833 }
9834
John McCallf89e55a2010-11-18 06:31:45 +00009835 QualType ResultType = Method->getResultType();
9836 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9837 ResultType = ResultType.getNonLValueExprType(Context);
9838
Douglas Gregor88a35142008-12-22 05:46:06 +00009839 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009840 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +00009841 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00009842 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00009843
Anders Carlssoneed3e692009-10-10 00:06:20 +00009844 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009845 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00009846 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00009847 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009848
Douglas Gregor88a35142008-12-22 05:46:06 +00009849 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00009850 // We only need to do this if there was actually an overload; otherwise
9851 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +00009852 if (!Method->isStatic()) {
9853 ExprResult ObjectArg =
9854 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9855 FoundDecl, Method);
9856 if (ObjectArg.isInvalid())
9857 return ExprError();
9858 MemExpr->setBase(ObjectArg.take());
9859 }
Douglas Gregor88a35142008-12-22 05:46:06 +00009860
9861 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00009862 const FunctionProtoType *Proto =
9863 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00009864 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00009865 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00009866 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009867
John McCall9ae2f072010-08-23 23:25:46 +00009868 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00009869 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00009870
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009871 if ((isa<CXXConstructorDecl>(CurContext) ||
9872 isa<CXXDestructorDecl>(CurContext)) &&
9873 TheCall->getMethodDecl()->isPure()) {
9874 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9875
Chandler Carruthae198062011-06-27 08:31:58 +00009876 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009877 Diag(MemExpr->getLocStart(),
9878 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9879 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9880 << MD->getParent()->getDeclName();
9881
9882 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +00009883 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009884 }
John McCall9ae2f072010-08-23 23:25:46 +00009885 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00009886}
9887
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009888/// BuildCallToObjectOfClassType - Build a call to an object of class
9889/// type (C++ [over.call.object]), which can end up invoking an
9890/// overloaded function call operator (@c operator()) or performing a
9891/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00009892ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00009893Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +00009894 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009895 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009896 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +00009897 if (checkPlaceholderForOverload(*this, Obj))
9898 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009899 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +00009900
9901 UnbridgedCastsSet UnbridgedCasts;
9902 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9903 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009904
John Wiegley429bb272011-04-08 18:41:53 +00009905 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9906 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00009907
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009908 // C++ [over.call.object]p1:
9909 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00009910 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009911 // candidate functions includes at least the function call
9912 // operators of T. The function call operators of T are obtained by
9913 // ordinary lookup of the name operator() in the context of
9914 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00009915 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00009916 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00009917
John Wiegley429bb272011-04-08 18:41:53 +00009918 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009919 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009920 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +00009921 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009922
John McCalla24dc2e2009-11-17 02:14:36 +00009923 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9924 LookupQualifiedName(R, Record->getDecl());
9925 R.suppressDiagnostics();
9926
Douglas Gregor593564b2009-11-15 07:48:03 +00009927 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00009928 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +00009929 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9930 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00009931 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00009932 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009933
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009934 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009935 // In addition, for each (non-explicit in C++0x) conversion function
9936 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009937 //
9938 // operator conversion-type-id () cv-qualifier;
9939 //
9940 // where cv-qualifier is the same cv-qualification as, or a
9941 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00009942 // denotes the type "pointer to function of (P1,...,Pn) returning
9943 // R", or the type "reference to pointer to function of
9944 // (P1,...,Pn) returning R", or the type "reference to function
9945 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009946 // is also considered as a candidate function. Similarly,
9947 // surrogate call functions are added to the set of candidate
9948 // functions for each conversion function declared in an
9949 // accessible base class provided the function is not hidden
9950 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00009951 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00009952 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00009953 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00009954 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00009955 NamedDecl *D = *I;
9956 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9957 if (isa<UsingShadowDecl>(D))
9958 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009959
Douglas Gregor4a27d702009-10-21 06:18:39 +00009960 // Skip over templated conversion functions; they aren't
9961 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00009962 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00009963 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009964
John McCall701c89e2009-12-03 04:06:58 +00009965 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009966 if (!Conv->isExplicit()) {
9967 // Strip the reference type (if any) and then the pointer type (if
9968 // any) to get down to what might be a function type.
9969 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9970 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9971 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +00009972
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009973 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9974 {
9975 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9976 Object.get(), Args, NumArgs, CandidateSet);
9977 }
9978 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009979 }
Mike Stump1eb44332009-09-09 15:08:12 +00009980
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009981 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9982
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009983 // Perform overload resolution.
9984 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +00009985 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +00009986 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009987 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009988 // Overload resolution succeeded; we'll build the appropriate call
9989 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009990 break;
9991
9992 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00009993 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +00009994 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9995 << Object.get()->getType() << /*call*/ 1
9996 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +00009997 else
John Wiegley429bb272011-04-08 18:41:53 +00009998 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +00009999 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010000 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010001 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010002 break;
10003
10004 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +000010005 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010006 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010007 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010008 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010009 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010010
10011 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +000010012 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010013 diag::err_ovl_deleted_object_call)
10014 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010015 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010016 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010017 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010018 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010019 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010020 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010021
Douglas Gregorff331c12010-07-25 18:17:45 +000010022 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010023 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010024
John McCall5acb0c92011-10-17 18:40:02 +000010025 UnbridgedCasts.restore();
10026
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010027 if (Best->Function == 0) {
10028 // Since there is no function declaration, this is one of the
10029 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010030 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010031 = cast<CXXConversionDecl>(
10032 Best->Conversions[0].UserDefined.ConversionFunction);
10033
John Wiegley429bb272011-04-08 18:41:53 +000010034 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010035 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010036
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010037 // We selected one of the surrogate functions that converts the
10038 // object parameter to a function pointer. Perform the conversion
10039 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010040
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010041 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010042 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010043 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10044 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010045 if (Call.isInvalid())
10046 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010047 // Record usage of conversion in an implicit cast.
10048 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10049 CK_UserDefinedConversion,
10050 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010051
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010052 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010053 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010054 }
10055
Chandler Carruth25ca4212011-02-25 19:41:05 +000010056 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010057 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010058 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010059
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010060 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10061 // that calls this method, using Object for the implicit object
10062 // parameter and passing along the remaining arguments.
10063 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010064 const FunctionProtoType *Proto =
10065 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010066
10067 unsigned NumArgsInProto = Proto->getNumArgs();
10068 unsigned NumArgsToCheck = NumArgs;
10069
10070 // Build the full argument list for the method call (the
10071 // implicit object parameter is placed at the beginning of the
10072 // list).
10073 Expr **MethodArgs;
10074 if (NumArgs < NumArgsInProto) {
10075 NumArgsToCheck = NumArgsInProto;
10076 MethodArgs = new Expr*[NumArgsInProto + 1];
10077 } else {
10078 MethodArgs = new Expr*[NumArgs + 1];
10079 }
John Wiegley429bb272011-04-08 18:41:53 +000010080 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010081 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10082 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010083
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010084 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10085 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +000010086 if (NewFn.isInvalid())
10087 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010088
10089 // Once we've built TheCall, all of the expressions are properly
10090 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010091 QualType ResultTy = Method->getResultType();
10092 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10093 ResultTy = ResultTy.getNonLValueExprType(Context);
10094
John McCall9ae2f072010-08-23 23:25:46 +000010095 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010096 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010097 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010098 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010099 delete [] MethodArgs;
10100
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010101 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010102 Method))
10103 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010104
Douglas Gregor518fda12009-01-13 05:10:00 +000010105 // We may have default arguments. If so, we need to allocate more
10106 // slots in the call for them.
10107 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010108 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010109 else if (NumArgs > NumArgsInProto)
10110 NumArgsToCheck = NumArgsInProto;
10111
Chris Lattner312531a2009-04-12 08:11:20 +000010112 bool IsError = false;
10113
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010114 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010115 ExprResult ObjRes =
10116 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10117 Best->FoundDecl, Method);
10118 if (ObjRes.isInvalid())
10119 IsError = true;
10120 else
10121 Object = move(ObjRes);
10122 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010123
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010124 // Check the argument types.
10125 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010126 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010127 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010128 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010129
Douglas Gregor518fda12009-01-13 05:10:00 +000010130 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010131
John McCall60d7b3a2010-08-24 06:29:42 +000010132 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010133 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010134 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010135 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010136 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010137
Anders Carlsson3faa4862010-01-29 18:43:53 +000010138 IsError |= InputInit.isInvalid();
10139 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010140 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010141 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010142 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10143 if (DefArg.isInvalid()) {
10144 IsError = true;
10145 break;
10146 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010147
Douglas Gregord47c47d2009-11-09 19:27:57 +000010148 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010149 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010150
10151 TheCall->setArg(i + 1, Arg);
10152 }
10153
10154 // If this is a variadic call, handle args passed through "...".
10155 if (Proto->isVariadic()) {
10156 // Promote the arguments (C99 6.5.2.2p7).
10157 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000010158 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10159 IsError |= Arg.isInvalid();
10160 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010161 }
10162 }
10163
Chris Lattner312531a2009-04-12 08:11:20 +000010164 if (IsError) return true;
10165
John McCall9ae2f072010-08-23 23:25:46 +000010166 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000010167 return true;
10168
John McCall182f7092010-08-24 06:09:16 +000010169 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010170}
10171
Douglas Gregor8ba10742008-11-20 16:27:02 +000010172/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000010173/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000010174/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000010175ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010176Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000010177 assert(Base->getType()->isRecordType() &&
10178 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000010179
John McCall5acb0c92011-10-17 18:40:02 +000010180 if (checkPlaceholderForOverload(*this, Base))
10181 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010182
John McCall5769d612010-02-08 23:07:23 +000010183 SourceLocation Loc = Base->getExprLoc();
10184
Douglas Gregor8ba10742008-11-20 16:27:02 +000010185 // C++ [over.ref]p1:
10186 //
10187 // [...] An expression x->m is interpreted as (x.operator->())->m
10188 // for a class object x of type T if T::operator->() exists and if
10189 // the operator is selected as the best match function by the
10190 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000010191 DeclarationName OpName =
10192 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000010193 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000010194 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010195
John McCall5769d612010-02-08 23:07:23 +000010196 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +000010197 PDiag(diag::err_typecheck_incomplete_tag)
10198 << Base->getSourceRange()))
10199 return ExprError();
10200
John McCalla24dc2e2009-11-17 02:14:36 +000010201 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10202 LookupQualifiedName(R, BaseRecord->getDecl());
10203 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000010204
10205 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000010206 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010207 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10208 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000010209 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000010210
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010211 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10212
Douglas Gregor8ba10742008-11-20 16:27:02 +000010213 // Perform overload resolution.
10214 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010215 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000010216 case OR_Success:
10217 // Overload resolution succeeded; we'll build the call below.
10218 break;
10219
10220 case OR_No_Viable_Function:
10221 if (CandidateSet.empty())
10222 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010223 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010224 else
10225 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010226 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010227 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010228 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010229
10230 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010231 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10232 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010233 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010234 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010235
10236 case OR_Deleted:
10237 Diag(OpLoc, diag::err_ovl_deleted_oper)
10238 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010239 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010240 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010241 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010242 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010243 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010244 }
10245
Chandler Carruth25ca4212011-02-25 19:41:05 +000010246 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010247 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010248 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010249
Douglas Gregor8ba10742008-11-20 16:27:02 +000010250 // Convert the object parameter.
10251 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010252 ExprResult BaseResult =
10253 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10254 Best->FoundDecl, Method);
10255 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010256 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010257 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010258
Douglas Gregor8ba10742008-11-20 16:27:02 +000010259 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010260 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10261 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +000010262 if (FnExpr.isInvalid())
10263 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010264
John McCallf89e55a2010-11-18 06:31:45 +000010265 QualType ResultTy = Method->getResultType();
10266 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10267 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010268 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010269 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010270 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010271
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010272 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010273 Method))
10274 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010275
10276 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010277}
10278
Douglas Gregor904eed32008-11-10 20:40:00 +000010279/// FixOverloadedFunctionReference - E is an expression that refers to
10280/// a C++ overloaded function (possibly with some parentheses and
10281/// perhaps a '&' around it). We have resolved the overloaded function
10282/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000010283/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000010284Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000010285 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000010286 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010287 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10288 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010289 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010290 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010291
Douglas Gregor699ee522009-11-20 19:42:02 +000010292 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010293 }
10294
Douglas Gregor699ee522009-11-20 19:42:02 +000010295 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010296 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10297 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010298 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000010299 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000010300 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000010301 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000010302 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010303 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010304
10305 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000010306 ICE->getCastKind(),
10307 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000010308 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010309 }
10310
Douglas Gregor699ee522009-11-20 19:42:02 +000010311 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000010312 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000010313 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000010314 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10315 if (Method->isStatic()) {
10316 // Do nothing: static member functions aren't any different
10317 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000010318 } else {
John McCallf7a1a742009-11-24 19:00:30 +000010319 // Fix the sub expression, which really has to be an
10320 // UnresolvedLookupExpr holding an overloaded member function
10321 // or template.
John McCall6bb80172010-03-30 21:47:33 +000010322 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10323 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000010324 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010325 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000010326
John McCallba135432009-11-21 08:51:07 +000010327 assert(isa<DeclRefExpr>(SubExpr)
10328 && "fixed to something other than a decl ref");
10329 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10330 && "fixed to a member ref with no nested name qualifier");
10331
10332 // We have taken the address of a pointer to member
10333 // function. Perform the computation here so that we get the
10334 // appropriate pointer to member type.
10335 QualType ClassType
10336 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10337 QualType MemPtrType
10338 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10339
John McCallf89e55a2010-11-18 06:31:45 +000010340 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10341 VK_RValue, OK_Ordinary,
10342 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000010343 }
10344 }
John McCall6bb80172010-03-30 21:47:33 +000010345 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10346 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010347 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010348 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010349
John McCall2de56d12010-08-25 11:45:40 +000010350 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000010351 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000010352 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000010353 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010354 }
John McCallba135432009-11-21 08:51:07 +000010355
10356 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000010357 // FIXME: avoid copy.
10358 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000010359 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000010360 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10361 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000010362 }
10363
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010364 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10365 ULE->getQualifierLoc(),
10366 Fn,
10367 ULE->getNameLoc(),
10368 Fn->getType(),
10369 VK_LValue,
10370 Found.getDecl(),
10371 TemplateArgs);
10372 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10373 return DRE;
John McCallba135432009-11-21 08:51:07 +000010374 }
10375
John McCall129e2df2009-11-30 22:42:35 +000010376 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000010377 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000010378 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10379 if (MemExpr->hasExplicitTemplateArgs()) {
10380 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10381 TemplateArgs = &TemplateArgsBuffer;
10382 }
John McCalld5532b62009-11-23 01:53:49 +000010383
John McCallaa81e162009-12-01 22:10:20 +000010384 Expr *Base;
10385
John McCallf89e55a2010-11-18 06:31:45 +000010386 // If we're filling in a static method where we used to have an
10387 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000010388 if (MemExpr->isImplicitAccess()) {
10389 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010390 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10391 MemExpr->getQualifierLoc(),
10392 Fn,
10393 MemExpr->getMemberLoc(),
10394 Fn->getType(),
10395 VK_LValue,
10396 Found.getDecl(),
10397 TemplateArgs);
10398 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10399 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000010400 } else {
10401 SourceLocation Loc = MemExpr->getMemberLoc();
10402 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000010403 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregor828a1972010-01-07 23:12:05 +000010404 Base = new (Context) CXXThisExpr(Loc,
10405 MemExpr->getBaseType(),
10406 /*isImplicit=*/true);
10407 }
John McCallaa81e162009-12-01 22:10:20 +000010408 } else
John McCall3fa5cae2010-10-26 07:05:15 +000010409 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000010410
John McCallf5307512011-04-27 00:36:17 +000010411 ExprValueKind valueKind;
10412 QualType type;
10413 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10414 valueKind = VK_LValue;
10415 type = Fn->getType();
10416 } else {
10417 valueKind = VK_RValue;
10418 type = Context.BoundMemberTy;
10419 }
10420
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010421 MemberExpr *ME = MemberExpr::Create(Context, Base,
10422 MemExpr->isArrow(),
10423 MemExpr->getQualifierLoc(),
10424 Fn,
10425 Found,
10426 MemExpr->getMemberNameInfo(),
10427 TemplateArgs,
10428 type, valueKind, OK_Ordinary);
10429 ME->setHadMultipleCandidates(true);
10430 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000010431 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010432
John McCall3fa5cae2010-10-26 07:05:15 +000010433 llvm_unreachable("Invalid reference to overloaded function");
10434 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +000010435}
10436
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010437ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000010438 DeclAccessPair Found,
10439 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000010440 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000010441}
10442
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000010443} // end namespace clang