blob: bd971b793aefec0f6b706bd4d37e1ff89fdef6af [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"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035
John McCall120d63c2010-08-24 20:38:10 +000036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
37 bool InOverloadResolution,
38 StandardConversionSequence &SCS);
39static OverloadingResult
40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
41 UserDefinedConversionSequence& User,
42 OverloadCandidateSet& Conversions,
43 bool AllowExplicit);
44
45
46static ImplicitConversionSequence::CompareKind
47CompareStandardConversionSequences(Sema &S,
48 const StandardConversionSequence& SCS1,
49 const StandardConversionSequence& SCS2);
50
51static ImplicitConversionSequence::CompareKind
52CompareQualificationConversions(Sema &S,
53 const StandardConversionSequence& SCS1,
54 const StandardConversionSequence& SCS2);
55
56static ImplicitConversionSequence::CompareKind
57CompareDerivedToBaseConversions(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61
62
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000063/// GetConversionCategory - Retrieve the implicit conversion
64/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000065ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000066GetConversionCategory(ImplicitConversionKind Kind) {
67 static const ImplicitConversionCategory
68 Category[(int)ICK_Num_Conversion_Kinds] = {
69 ICC_Identity,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
72 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000073 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074 ICC_Qualification_Adjustment,
75 ICC_Promotion,
76 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000077 ICC_Promotion,
78 ICC_Conversion,
79 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
84 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000085 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000086 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000087 ICC_Conversion,
88 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089 ICC_Conversion
90 };
91 return Category[(int)Kind];
92}
93
94/// GetConversionRank - Retrieve the implicit conversion rank
95/// corresponding to the given implicit conversion kind.
96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
97 static const ImplicitConversionRank
98 Rank[(int)ICK_Num_Conversion_Kinds] = {
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
103 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000104 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 ICR_Promotion,
106 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 ICR_Promotion,
108 ICR_Conversion,
109 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
114 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000115 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000116 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000117 ICR_Conversion,
118 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000119 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000120 };
121 return Rank[(int)Kind];
122}
123
124/// GetImplicitConversionName - Return the name of this kind of
125/// implicit conversion.
126const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128 "No conversion",
129 "Lvalue-to-rvalue",
130 "Array-to-pointer",
131 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000132 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 "Qualification",
134 "Integral promotion",
135 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 "Integral conversion",
138 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000139 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000140 "Floating-integral conversion",
141 "Pointer conversion",
142 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000143 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000144 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000145 "Derived-to-base conversion",
146 "Vector conversion",
147 "Vector splat",
148 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000149 };
150 return Name[Kind];
151}
152
Douglas Gregor60d62c22008-10-31 16:23:19 +0000153/// StandardConversionSequence - Set the standard conversion
154/// sequence to the identity conversion.
155void StandardConversionSequence::setAsIdentityConversion() {
156 First = ICK_Identity;
157 Second = ICK_Identity;
158 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000159 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000160 ReferenceBinding = false;
161 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000162 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000163 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000164}
165
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166/// getRank - Retrieve the rank of this standard conversion sequence
167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
168/// implicit conversions.
169ImplicitConversionRank StandardConversionSequence::getRank() const {
170 ImplicitConversionRank Rank = ICR_Exact_Match;
171 if (GetConversionRank(First) > Rank)
172 Rank = GetConversionRank(First);
173 if (GetConversionRank(Second) > Rank)
174 Rank = GetConversionRank(Second);
175 if (GetConversionRank(Third) > Rank)
176 Rank = GetConversionRank(Third);
177 return Rank;
178}
179
180/// isPointerConversionToBool - Determines whether this conversion is
181/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000182/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000184bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 // Note that FromType has not necessarily been transformed by the
186 // array-to-pointer or function-to-pointer implicit conversions, so
187 // check for their presence as well as checking whether FromType is
188 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000189 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000190 (getFromType()->isPointerType() ||
191 getFromType()->isObjCObjectPointerType() ||
192 getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000193 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
194 return true;
195
196 return false;
197}
198
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000199/// isPointerConversionToVoidPointer - Determines whether this
200/// conversion is a conversion of a pointer to a void pointer. This is
201/// used as part of the ranking of standard conversion sequences (C++
202/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000203bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000204StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000205isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000206 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000207 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000208
209 // Note that FromType has not necessarily been transformed by the
210 // array-to-pointer implicit conversion, so check for its presence
211 // and redo the conversion to get a pointer.
212 if (First == ICK_Array_To_Pointer)
213 FromType = Context.getArrayDecayedType(FromType);
214
Douglas Gregor01919692009-12-13 21:37:05 +0000215 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000216 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000217 return ToPtrType->getPointeeType()->isVoidType();
218
219 return false;
220}
221
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000222/// DebugPrint - Print this standard conversion sequence to standard
223/// error. Useful for debugging overloading issues.
224void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000225 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000226 bool PrintedSomething = false;
227 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000228 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229 PrintedSomething = true;
230 }
231
232 if (Second != ICK_Identity) {
233 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000234 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000235 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000236 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000237
238 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000240 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000241 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000242 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000243 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000244 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000245 PrintedSomething = true;
246 }
247
248 if (Third != ICK_Identity) {
249 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000252 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000253 PrintedSomething = true;
254 }
255
256 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000257 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000258 }
259}
260
261/// DebugPrint - Print this user-defined conversion sequence to standard
262/// error. Useful for debugging overloading issues.
263void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 if (Before.First || Before.Second || Before.Third) {
266 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000267 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000268 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000269 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000270 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000271 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000272 After.DebugPrint();
273 }
274}
275
276/// DebugPrint - Print this implicit conversion sequence to standard
277/// error. Useful for debugging overloading issues.
278void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000279 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000280 switch (ConversionKind) {
281 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000282 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000283 Standard.DebugPrint();
284 break;
285 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000286 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287 UserDefined.DebugPrint();
288 break;
289 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000290 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000291 break;
John McCall1d318332010-01-12 00:44:57 +0000292 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000293 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000294 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000295 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000296 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000297 break;
298 }
299
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000300 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000301}
302
John McCall1d318332010-01-12 00:44:57 +0000303void AmbiguousConversionSequence::construct() {
304 new (&conversions()) ConversionSet();
305}
306
307void AmbiguousConversionSequence::destruct() {
308 conversions().~ConversionSet();
309}
310
311void
312AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
313 FromTypePtr = O.FromTypePtr;
314 ToTypePtr = O.ToTypePtr;
315 new (&conversions()) ConversionSet(O.conversions());
316}
317
Douglas Gregora9333192010-05-08 17:41:32 +0000318namespace {
319 // Structure used by OverloadCandidate::DeductionFailureInfo to store
320 // template parameter and template argument information.
321 struct DFIParamWithArguments {
322 TemplateParameter Param;
323 TemplateArgument FirstArg;
324 TemplateArgument SecondArg;
325 };
326}
327
328/// \brief Convert from Sema's representation of template deduction information
329/// to the form used in overload-candidate information.
330OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000331static MakeDeductionFailureInfo(ASTContext &Context,
332 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000333 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000334 OverloadCandidate::DeductionFailureInfo Result;
335 Result.Result = static_cast<unsigned>(TDK);
336 Result.Data = 0;
337 switch (TDK) {
338 case Sema::TDK_Success:
339 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000340 case Sema::TDK_TooManyArguments:
341 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000342 break;
343
344 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000345 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000346 Result.Data = Info.Param.getOpaqueValue();
347 break;
348
Douglas Gregora9333192010-05-08 17:41:32 +0000349 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000350 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000351 // FIXME: Should allocate from normal heap so that we can free this later.
352 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000353 Saved->Param = Info.Param;
354 Saved->FirstArg = Info.FirstArg;
355 Saved->SecondArg = Info.SecondArg;
356 Result.Data = Saved;
357 break;
358 }
359
360 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000361 Result.Data = Info.take();
362 break;
363
Douglas Gregora9333192010-05-08 17:41:32 +0000364 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000365 case Sema::TDK_FailedOverloadResolution:
366 break;
367 }
368
369 return Result;
370}
John McCall1d318332010-01-12 00:44:57 +0000371
Douglas Gregora9333192010-05-08 17:41:32 +0000372void OverloadCandidate::DeductionFailureInfo::Destroy() {
373 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
374 case Sema::TDK_Success:
375 case Sema::TDK_InstantiationDepth:
376 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000377 case Sema::TDK_TooManyArguments:
378 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000380 break;
381
Douglas Gregora9333192010-05-08 17:41:32 +0000382 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000384 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000385 Data = 0;
386 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000387
388 case Sema::TDK_SubstitutionFailure:
389 // FIXME: Destroy the template arugment list?
390 Data = 0;
391 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000392
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000393 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000394 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000395 case Sema::TDK_FailedOverloadResolution:
396 break;
397 }
398}
399
400TemplateParameter
401OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
402 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
403 case Sema::TDK_Success:
404 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000407 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000408 return TemplateParameter();
409
410 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000411 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000412 return TemplateParameter::getFromOpaqueValue(Data);
413
414 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000415 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000416 return static_cast<DFIParamWithArguments*>(Data)->Param;
417
418 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000419 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000420 case Sema::TDK_FailedOverloadResolution:
421 break;
422 }
423
424 return TemplateParameter();
425}
Douglas Gregorec20f462010-05-08 20:07:26 +0000426
427TemplateArgumentList *
428OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
429 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
430 case Sema::TDK_Success:
431 case Sema::TDK_InstantiationDepth:
432 case Sema::TDK_TooManyArguments:
433 case Sema::TDK_TooFewArguments:
434 case Sema::TDK_Incomplete:
435 case Sema::TDK_InvalidExplicitArguments:
436 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000437 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000438 return 0;
439
440 case Sema::TDK_SubstitutionFailure:
441 return static_cast<TemplateArgumentList*>(Data);
442
443 // Unhandled
444 case Sema::TDK_NonDeducedMismatch:
445 case Sema::TDK_FailedOverloadResolution:
446 break;
447 }
448
449 return 0;
450}
451
Douglas Gregora9333192010-05-08 17:41:32 +0000452const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
453 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
454 case Sema::TDK_Success:
455 case Sema::TDK_InstantiationDepth:
456 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000457 case Sema::TDK_TooManyArguments:
458 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000459 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000460 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000461 return 0;
462
Douglas Gregora9333192010-05-08 17:41:32 +0000463 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000464 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000465 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
466
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000467 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000468 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000469 case Sema::TDK_FailedOverloadResolution:
470 break;
471 }
472
473 return 0;
474}
475
476const TemplateArgument *
477OverloadCandidate::DeductionFailureInfo::getSecondArg() {
478 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
479 case Sema::TDK_Success:
480 case Sema::TDK_InstantiationDepth:
481 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000482 case Sema::TDK_TooManyArguments:
483 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000484 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000485 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000486 return 0;
487
Douglas Gregora9333192010-05-08 17:41:32 +0000488 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000489 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000490 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
491
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000492 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000493 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000494 case Sema::TDK_FailedOverloadResolution:
495 break;
496 }
497
498 return 0;
499}
500
501void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000502 inherited::clear();
503 Functions.clear();
504}
505
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000507// overload of the declarations in Old. This routine returns false if
508// New and Old cannot be overloaded, e.g., if New has the same
509// signature as some function in Old (C++ 1.3.10) or if the Old
510// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000511// it does return false, MatchedDecl will point to the decl that New
512// cannot be overloaded with. This decl may be a UsingShadowDecl on
513// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514//
515// Example: Given the following input:
516//
517// void f(int, float); // #1
518// void f(int, int); // #2
519// int f(int, int); // #3
520//
521// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000522// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523//
John McCall51fa86f2009-12-02 08:47:38 +0000524// When we process #2, Old contains only the FunctionDecl for #1. By
525// comparing the parameter types, we see that #1 and #2 are overloaded
526// (since they have different signatures), so this routine returns
527// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000528//
John McCall51fa86f2009-12-02 08:47:38 +0000529// When we process #3, Old is an overload set containing #1 and #2. We
530// compare the signatures of #3 to #1 (they're overloaded, so we do
531// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
532// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533// signature), IsOverload returns false and MatchedDecl will be set to
534// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000535//
536// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
537// into a class by a using declaration. The rules for whether to hide
538// shadow declarations ignore some properties which otherwise figure
539// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000540Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000541Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
542 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000543 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000544 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000545 NamedDecl *OldD = *I;
546
547 bool OldIsUsingDecl = false;
548 if (isa<UsingShadowDecl>(OldD)) {
549 OldIsUsingDecl = true;
550
551 // We can always introduce two using declarations into the same
552 // context, even if they have identical signatures.
553 if (NewIsUsingDecl) continue;
554
555 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
556 }
557
558 // If either declaration was introduced by a using declaration,
559 // we'll need to use slightly different rules for matching.
560 // Essentially, these rules are the normal rules, except that
561 // function templates hide function templates with different
562 // return types or template parameter lists.
563 bool UseMemberUsingDeclRules =
564 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
565
John McCall51fa86f2009-12-02 08:47:38 +0000566 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000567 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
568 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
569 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
570 continue;
571 }
572
John McCall871b2e72009-12-09 03:35:25 +0000573 Match = *I;
574 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000575 }
John McCall51fa86f2009-12-02 08:47:38 +0000576 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000577 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
578 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
579 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
580 continue;
581 }
582
John McCall871b2e72009-12-09 03:35:25 +0000583 Match = *I;
584 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000585 }
John McCall9f54ad42009-12-10 09:41:52 +0000586 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
587 // We can overload with these, which can show up when doing
588 // redeclaration checks for UsingDecls.
589 assert(Old.getLookupKind() == LookupUsingDeclName);
590 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
591 // Optimistically assume that an unresolved using decl will
592 // overload; if it doesn't, we'll have to diagnose during
593 // template instantiation.
594 } else {
John McCall68263142009-11-18 22:49:29 +0000595 // (C++ 13p1):
596 // Only function declarations can be overloaded; object and type
597 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000598 Match = *I;
599 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000600 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000601 }
John McCall68263142009-11-18 22:49:29 +0000602
John McCall871b2e72009-12-09 03:35:25 +0000603 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000604}
605
John McCallad00b772010-06-16 08:42:20 +0000606bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
607 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000608 // If both of the functions are extern "C", then they are not
609 // overloads.
610 if (Old->isExternC() && New->isExternC())
611 return false;
612
John McCall68263142009-11-18 22:49:29 +0000613 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
614 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
615
616 // C++ [temp.fct]p2:
617 // A function template can be overloaded with other function templates
618 // and with normal (non-template) functions.
619 if ((OldTemplate == 0) != (NewTemplate == 0))
620 return true;
621
622 // Is the function New an overload of the function Old?
623 QualType OldQType = Context.getCanonicalType(Old->getType());
624 QualType NewQType = Context.getCanonicalType(New->getType());
625
626 // Compare the signatures (C++ 1.3.10) of the two functions to
627 // determine whether they are overloads. If we find any mismatch
628 // in the signature, they are overloads.
629
630 // If either of these functions is a K&R-style function (no
631 // prototype), then we consider them to have matching signatures.
632 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
633 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
634 return false;
635
636 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
637 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
638
639 // The signature of a function includes the types of its
640 // parameters (C++ 1.3.10), which includes the presence or absence
641 // of the ellipsis; see C++ DR 357).
642 if (OldQType != NewQType &&
643 (OldType->getNumArgs() != NewType->getNumArgs() ||
644 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000645 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000646 return true;
647
648 // C++ [temp.over.link]p4:
649 // The signature of a function template consists of its function
650 // signature, its return type and its template parameter list. The names
651 // of the template parameters are significant only for establishing the
652 // relationship between the template parameters and the rest of the
653 // signature.
654 //
655 // We check the return type and template parameter lists for function
656 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000657 //
658 // However, we don't consider either of these when deciding whether
659 // a member introduced by a shadow declaration is hidden.
660 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000661 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
662 OldTemplate->getTemplateParameters(),
663 false, TPL_TemplateMatch) ||
664 OldType->getResultType() != NewType->getResultType()))
665 return true;
666
667 // If the function is a class member, its signature includes the
668 // cv-qualifiers (if any) on the function itself.
669 //
670 // As part of this, also check whether one of the member functions
671 // is static, in which case they are not overloads (C++
672 // 13.1p2). While not part of the definition of the signature,
673 // this check is important to determine whether these functions
674 // can be overloaded.
675 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
676 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
677 if (OldMethod && NewMethod &&
678 !OldMethod->isStatic() && !NewMethod->isStatic() &&
679 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
680 return true;
681
682 // The signatures match; this is not an overload.
683 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000684}
685
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000686/// TryImplicitConversion - Attempt to perform an implicit conversion
687/// from the given expression (Expr) to the given type (ToType). This
688/// function returns an implicit conversion sequence that can be used
689/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000690///
691/// void f(float f);
692/// void g(int i) { f(i); }
693///
694/// this routine would produce an implicit conversion sequence to
695/// describe the initialization of f from i, which will be a standard
696/// conversion sequence containing an lvalue-to-rvalue conversion (C++
697/// 4.1) followed by a floating-integral conversion (C++ 4.9).
698//
699/// Note that this routine only determines how the conversion can be
700/// performed; it does not actually perform the conversion. As such,
701/// it will not produce any diagnostics if no conversion is available,
702/// but will instead return an implicit conversion sequence of kind
703/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000704///
705/// If @p SuppressUserConversions, then user-defined conversions are
706/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000707/// If @p AllowExplicit, then explicit user-defined conversions are
708/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000709static ImplicitConversionSequence
710TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
711 bool SuppressUserConversions,
712 bool AllowExplicit,
713 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000714 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000715 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
716 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000717 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000718 return ICS;
719 }
720
John McCall120d63c2010-08-24 20:38:10 +0000721 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000722 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000723 return ICS;
724 }
725
Douglas Gregor604eb652010-08-11 02:15:33 +0000726 // C++ [over.ics.user]p4:
727 // A conversion of an expression of class type to the same class
728 // type is given Exact Match rank, and a conversion of an
729 // expression of class type to a base class of that type is
730 // given Conversion rank, in spite of the fact that a copy/move
731 // constructor (i.e., a user-defined conversion function) is
732 // called for those cases.
733 QualType FromType = From->getType();
734 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000735 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
736 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000737 ICS.setStandard();
738 ICS.Standard.setAsIdentityConversion();
739 ICS.Standard.setFromType(FromType);
740 ICS.Standard.setAllToTypes(ToType);
741
742 // We don't actually check at this point whether there is a valid
743 // copy/move constructor, since overloading just assumes that it
744 // exists. When we actually perform initialization, we'll find the
745 // appropriate constructor to copy the returned object, if needed.
746 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000747
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000748 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000749 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000750 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000751
752 return ICS;
753 }
754
755 if (SuppressUserConversions) {
756 // We're not in the case above, so there is no conversion that
757 // we can perform.
758 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000759 return ICS;
760 }
761
762 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000763 OverloadCandidateSet Conversions(From->getExprLoc());
764 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000765 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000766 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000767
768 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000769 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000770 // C++ [over.ics.user]p4:
771 // A conversion of an expression of class type to the same class
772 // type is given Exact Match rank, and a conversion of an
773 // expression of class type to a base class of that type is
774 // given Conversion rank, in spite of the fact that a copy
775 // constructor (i.e., a user-defined conversion function) is
776 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000777 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000778 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000779 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000780 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
781 QualType ToCanon
782 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000783 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000784 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000785 // Turn this into a "standard" conversion sequence, so that it
786 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000787 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000788 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000789 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000790 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000791 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000792 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000793 ICS.Standard.Second = ICK_Derived_To_Base;
794 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000795 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000796
797 // C++ [over.best.ics]p4:
798 // However, when considering the argument of a user-defined
799 // conversion function that is a candidate by 13.3.1.3 when
800 // invoked for the copying of the temporary in the second step
801 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
802 // 13.3.1.6 in all cases, only standard conversion sequences and
803 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000804 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000805 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000806 }
John McCallcefd3ad2010-01-13 22:30:33 +0000807 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000808 ICS.setAmbiguous();
809 ICS.Ambiguous.setFromType(From->getType());
810 ICS.Ambiguous.setToType(ToType);
811 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
812 Cand != Conversions.end(); ++Cand)
813 if (Cand->Viable)
814 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000815 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000816 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000817 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000818
819 return ICS;
820}
821
John McCall120d63c2010-08-24 20:38:10 +0000822bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
823 const InitializedEntity &Entity,
824 Expr *Initializer,
825 bool SuppressUserConversions,
826 bool AllowExplicitConversions,
827 bool InOverloadResolution) {
828 ImplicitConversionSequence ICS
829 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
830 SuppressUserConversions,
831 AllowExplicitConversions,
832 InOverloadResolution);
833 if (ICS.isBad()) return true;
834
835 // Perform the actual conversion.
836 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
837 return false;
838}
839
Douglas Gregor575c63a2010-04-16 22:27:05 +0000840/// PerformImplicitConversion - Perform an implicit conversion of the
841/// expression From to the type ToType. Returns true if there was an
842/// error, false otherwise. The expression From is replaced with the
843/// converted expression. Flavor is the kind of conversion we're
844/// performing, used in the error message. If @p AllowExplicit,
845/// explicit user-defined conversions are permitted.
846bool
847Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
848 AssignmentAction Action, bool AllowExplicit) {
849 ImplicitConversionSequence ICS;
850 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
851}
852
853bool
854Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
855 AssignmentAction Action, bool AllowExplicit,
856 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000857 ICS = clang::TryImplicitConversion(*this, From, ToType,
858 /*SuppressUserConversions=*/false,
859 AllowExplicit,
860 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000861 return PerformImplicitConversion(From, ToType, ICS, Action);
862}
863
Douglas Gregor43c79c22009-12-09 00:47:37 +0000864/// \brief Determine whether the conversion from FromType to ToType is a valid
865/// conversion that strips "noreturn" off the nested function type.
866static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
867 QualType ToType, QualType &ResultTy) {
868 if (Context.hasSameUnqualifiedType(FromType, ToType))
869 return false;
870
871 // Strip the noreturn off the type we're converting from; noreturn can
872 // safely be removed.
873 FromType = Context.getNoReturnType(FromType, false);
874 if (!Context.hasSameUnqualifiedType(FromType, ToType))
875 return false;
876
877 ResultTy = FromType;
878 return true;
879}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000880
881/// \brief Determine whether the conversion from FromType to ToType is a valid
882/// vector conversion.
883///
884/// \param ICK Will be set to the vector conversion kind, if this is a vector
885/// conversion.
886static bool IsVectorConversion(ASTContext &Context, QualType FromType,
887 QualType ToType, ImplicitConversionKind &ICK) {
888 // We need at least one of these types to be a vector type to have a vector
889 // conversion.
890 if (!ToType->isVectorType() && !FromType->isVectorType())
891 return false;
892
893 // Identical types require no conversions.
894 if (Context.hasSameUnqualifiedType(FromType, ToType))
895 return false;
896
897 // There are no conversions between extended vector types, only identity.
898 if (ToType->isExtVectorType()) {
899 // There are no conversions between extended vector types other than the
900 // identity conversion.
901 if (FromType->isExtVectorType())
902 return false;
903
904 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000905 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000906 ICK = ICK_Vector_Splat;
907 return true;
908 }
909 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000910
911 // We can perform the conversion between vector types in the following cases:
912 // 1)vector types are equivalent AltiVec and GCC vector types
913 // 2)lax vector conversions are permitted and the vector types are of the
914 // same size
915 if (ToType->isVectorType() && FromType->isVectorType()) {
916 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000917 (Context.getLangOptions().LaxVectorConversions &&
918 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000919 ICK = ICK_Vector_Conversion;
920 return true;
921 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000922 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000923
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000924 return false;
925}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000926
Douglas Gregor60d62c22008-10-31 16:23:19 +0000927/// IsStandardConversion - Determines whether there is a standard
928/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
929/// expression From to the type ToType. Standard conversion sequences
930/// only consider non-class types; for conversions that involve class
931/// types, use TryImplicitConversion. If a conversion exists, SCS will
932/// contain the standard conversion sequence required to perform this
933/// conversion and this routine will return true. Otherwise, this
934/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000935static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
936 bool InOverloadResolution,
937 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000938 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000939
Douglas Gregor60d62c22008-10-31 16:23:19 +0000940 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000941 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000942 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000943 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000944 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000945 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000946
Douglas Gregorf9201e02009-02-11 23:02:49 +0000947 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000948 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000949 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000950 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000951 return false;
952
Mike Stump1eb44332009-09-09 15:08:12 +0000953 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000954 }
955
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000956 // The first conversion can be an lvalue-to-rvalue conversion,
957 // array-to-pointer conversion, or function-to-pointer conversion
958 // (C++ 4p1).
959
John McCall120d63c2010-08-24 20:38:10 +0000960 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000961 DeclAccessPair AccessPair;
962 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +0000963 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
964 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000965 // We were able to resolve the address of the overloaded function,
966 // so we can convert to the type of that function.
967 FromType = Fn->getType();
968 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
969 if (!Method->isStatic()) {
970 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +0000971 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
972 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000973 }
974 }
975
976 // If the "from" expression takes the address of the overloaded
977 // function, update the type of the resulting expression accordingly.
978 if (FromType->getAs<FunctionType>())
979 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +0000980 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +0000981 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000982
983 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +0000984 assert(S.Context.hasSameType(FromType,
985 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000986 } else {
987 return false;
988 }
989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000991 // An lvalue (3.10) of a non-function, non-array type T can be
992 // converted to an rvalue.
John McCall120d63c2010-08-24 20:38:10 +0000993 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000994 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000995 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +0000996 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000997 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000998
999 // If T is a non-class type, the type of the rvalue is the
1000 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001001 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1002 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001003 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001004 } else if (FromType->isArrayType()) {
1005 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001006 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001007
1008 // An lvalue or rvalue of type "array of N T" or "array of unknown
1009 // bound of T" can be converted to an rvalue of type "pointer to
1010 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001011 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001012
John McCall120d63c2010-08-24 20:38:10 +00001013 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001014 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001015 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001016
1017 // For the purpose of ranking in overload resolution
1018 // (13.3.3.1.1), this conversion is considered an
1019 // array-to-pointer conversion followed by a qualification
1020 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001021 SCS.Second = ICK_Identity;
1022 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001023 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001024 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001025 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001026 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1027 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001028 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001029
1030 // An lvalue of function type T can be converted to an rvalue of
1031 // type "pointer to T." The result is a pointer to the
1032 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001033 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001034 } else {
1035 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001036 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001037 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001038 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001039
1040 // The second conversion can be an integral promotion, floating
1041 // point promotion, integral conversion, floating point conversion,
1042 // floating-integral conversion, pointer conversion,
1043 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001044 // For overloading in C, this can also be a "compatible-type"
1045 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001046 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001047 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001048 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001049 // The unqualified versions of the types are the same: there's no
1050 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001051 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001052 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001053 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001054 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001055 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001056 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001057 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001058 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001059 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001060 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001061 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001062 SCS.Second = ICK_Complex_Promotion;
1063 FromType = ToType.getUnqualifiedType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001064 } else if (FromType->isIntegralOrEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001065 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001066 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001067 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001068 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001069 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1070 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001071 SCS.Second = ICK_Complex_Conversion;
1072 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001073 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1074 (ToType->isComplexType() && FromType->isArithmeticType())) {
1075 // Complex-real conversions (C99 6.3.1.7)
1076 SCS.Second = ICK_Complex_Real;
1077 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001078 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001079 // Floating point conversions (C++ 4.8).
1080 SCS.Second = ICK_Floating_Conversion;
1081 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001082 } else if ((FromType->isRealFloatingType() &&
John McCall120d63c2010-08-24 20:38:10 +00001083 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001084 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001085 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001086 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001087 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001088 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001089 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1090 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001091 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001092 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001093 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001094 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1095 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001096 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001097 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001098 } else if (ToType->isBooleanType() &&
1099 (FromType->isArithmeticType() ||
1100 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001101 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001102 FromType->isBlockPointerType() ||
1103 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001104 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001105 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001106 SCS.Second = ICK_Boolean_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001107 FromType = S.Context.BoolTy;
1108 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001109 SCS.Second = SecondICK;
1110 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001111 } else if (!S.getLangOptions().CPlusPlus &&
1112 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001113 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001114 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001115 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001116 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001117 // Treat a conversion that strips "noreturn" as an identity conversion.
1118 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001119 } else {
1120 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001121 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001122 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001123 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001124
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001125 QualType CanonFrom;
1126 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001127 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001128 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001129 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001130 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001131 CanonFrom = S.Context.getCanonicalType(FromType);
1132 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001133 } else {
1134 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001135 SCS.Third = ICK_Identity;
1136
Mike Stump1eb44332009-09-09 15:08:12 +00001137 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001138 // [...] Any difference in top-level cv-qualification is
1139 // subsumed by the initialization itself and does not constitute
1140 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001141 CanonFrom = S.Context.getCanonicalType(FromType);
1142 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001143 if (CanonFrom.getLocalUnqualifiedType()
1144 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001145 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1146 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001147 FromType = ToType;
1148 CanonFrom = CanonTo;
1149 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001150 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001151 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152
1153 // If we have not converted the argument type to the parameter type,
1154 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001155 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001156 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001157
Douglas Gregor60d62c22008-10-31 16:23:19 +00001158 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001159}
1160
1161/// IsIntegralPromotion - Determines whether the conversion from the
1162/// expression From (whose potentially-adjusted type is FromType) to
1163/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1164/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001165bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001166 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001167 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001168 if (!To) {
1169 return false;
1170 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171
1172 // An rvalue of type char, signed char, unsigned char, short int, or
1173 // unsigned short int can be converted to an rvalue of type int if
1174 // int can represent all the values of the source type; otherwise,
1175 // the source rvalue can be converted to an rvalue of type unsigned
1176 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001177 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1178 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001179 if (// We can promote any signed, promotable integer type to an int
1180 (FromType->isSignedIntegerType() ||
1181 // We can promote any unsigned integer type whose size is
1182 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001183 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001184 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001185 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001186 }
1187
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001188 return To->getKind() == BuiltinType::UInt;
1189 }
1190
1191 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1192 // can be converted to an rvalue of the first of the following types
1193 // that can represent all the values of its underlying type: int,
1194 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001195
1196 // We pre-calculate the promotion type for enum types.
1197 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
Douglas Gregor5dde1602010-09-12 03:38:25 +00001198 if (ToType->isIntegerType() &&
1199 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001200 return Context.hasSameUnqualifiedType(ToType,
1201 FromEnumType->getDecl()->getPromotionType());
1202
1203 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001204 // Determine whether the type we're converting from is signed or
1205 // unsigned.
1206 bool FromIsSigned;
1207 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001208
1209 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1210 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001211
1212 // The types we'll try to promote to, in the appropriate
1213 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001214 QualType PromoteTypes[6] = {
1215 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001216 Context.LongTy, Context.UnsignedLongTy ,
1217 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001218 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001219 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001220 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1221 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001222 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001223 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1224 // We found the type that we can promote to. If this is the
1225 // type we wanted, we have a promotion. Otherwise, no
1226 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001227 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001228 }
1229 }
1230 }
1231
1232 // An rvalue for an integral bit-field (9.6) can be converted to an
1233 // rvalue of type int if int can represent all the values of the
1234 // bit-field; otherwise, it can be converted to unsigned int if
1235 // unsigned int can represent all the values of the bit-field. If
1236 // the bit-field is larger yet, no integral promotion applies to
1237 // it. If the bit-field has an enumerated type, it is treated as any
1238 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001239 // FIXME: We should delay checking of bit-fields until we actually perform the
1240 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001241 using llvm::APSInt;
1242 if (From)
1243 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001244 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001245 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001246 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1247 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1248 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001249
Douglas Gregor86f19402008-12-20 23:49:58 +00001250 // Are we promoting to an int from a bitfield that fits in an int?
1251 if (BitWidth < ToSize ||
1252 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1253 return To->getKind() == BuiltinType::Int;
1254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Douglas Gregor86f19402008-12-20 23:49:58 +00001256 // Are we promoting to an unsigned int from an unsigned bitfield
1257 // that fits into an unsigned int?
1258 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1259 return To->getKind() == BuiltinType::UInt;
1260 }
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Douglas Gregor86f19402008-12-20 23:49:58 +00001262 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001263 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001264 }
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001266 // An rvalue of type bool can be converted to an rvalue of type int,
1267 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001268 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001269 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001270 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001271
1272 return false;
1273}
1274
1275/// IsFloatingPointPromotion - Determines whether the conversion from
1276/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1277/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001278bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001279 /// An rvalue of type float can be converted to an rvalue of type
1280 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001281 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1282 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001283 if (FromBuiltin->getKind() == BuiltinType::Float &&
1284 ToBuiltin->getKind() == BuiltinType::Double)
1285 return true;
1286
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001287 // C99 6.3.1.5p1:
1288 // When a float is promoted to double or long double, or a
1289 // double is promoted to long double [...].
1290 if (!getLangOptions().CPlusPlus &&
1291 (FromBuiltin->getKind() == BuiltinType::Float ||
1292 FromBuiltin->getKind() == BuiltinType::Double) &&
1293 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1294 return true;
1295 }
1296
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001297 return false;
1298}
1299
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001300/// \brief Determine if a conversion is a complex promotion.
1301///
1302/// A complex promotion is defined as a complex -> complex conversion
1303/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001304/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001305bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001306 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001307 if (!FromComplex)
1308 return false;
1309
John McCall183700f2009-09-21 23:43:11 +00001310 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001311 if (!ToComplex)
1312 return false;
1313
1314 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001315 ToComplex->getElementType()) ||
1316 IsIntegralPromotion(0, FromComplex->getElementType(),
1317 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001318}
1319
Douglas Gregorcb7de522008-11-26 23:31:11 +00001320/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1321/// the pointer type FromPtr to a pointer to type ToPointee, with the
1322/// same type qualifiers as FromPtr has on its pointee type. ToType,
1323/// if non-empty, will be a pointer to ToType that may or may not have
1324/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001325static QualType
1326BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001327 QualType ToPointee, QualType ToType,
1328 ASTContext &Context) {
1329 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1330 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001331 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001332
1333 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001334 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001335 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001336 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001337 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001338
1339 // Build a pointer to ToPointee. It has the right qualifiers
1340 // already.
1341 return Context.getPointerType(ToPointee);
1342 }
1343
1344 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001345 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001346 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1347 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001348}
1349
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001350/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1351/// the FromType, which is an objective-c pointer, to ToType, which may or may
1352/// not have the right set of qualifiers.
1353static QualType
1354BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1355 QualType ToType,
1356 ASTContext &Context) {
1357 QualType CanonFromType = Context.getCanonicalType(FromType);
1358 QualType CanonToType = Context.getCanonicalType(ToType);
1359 Qualifiers Quals = CanonFromType.getQualifiers();
1360
1361 // Exact qualifier match -> return the pointer type we're converting to.
1362 if (CanonToType.getLocalQualifiers() == Quals)
1363 return ToType;
1364
1365 // Just build a canonical type that has the right qualifiers.
1366 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1367}
1368
Mike Stump1eb44332009-09-09 15:08:12 +00001369static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001370 bool InOverloadResolution,
1371 ASTContext &Context) {
1372 // Handle value-dependent integral null pointer constants correctly.
1373 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1374 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001375 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001376 return !InOverloadResolution;
1377
Douglas Gregorce940492009-09-25 04:25:58 +00001378 return Expr->isNullPointerConstant(Context,
1379 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1380 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001381}
Mike Stump1eb44332009-09-09 15:08:12 +00001382
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001383/// IsPointerConversion - Determines whether the conversion of the
1384/// expression From, which has the (possibly adjusted) type FromType,
1385/// can be converted to the type ToType via a pointer conversion (C++
1386/// 4.10). If so, returns true and places the converted type (that
1387/// might differ from ToType in its cv-qualifiers at some level) into
1388/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001389///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001390/// This routine also supports conversions to and from block pointers
1391/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1392/// pointers to interfaces. FIXME: Once we've determined the
1393/// appropriate overloading rules for Objective-C, we may want to
1394/// split the Objective-C checks into a different routine; however,
1395/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001396/// conversions, so for now they live here. IncompatibleObjC will be
1397/// set if the conversion is an allowed Objective-C conversion that
1398/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001399bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001400 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001401 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001402 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001403 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001404 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1405 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001406
Mike Stump1eb44332009-09-09 15:08:12 +00001407 // Conversion from a null pointer constant to any Objective-C pointer type.
1408 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001409 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001410 ConvertedType = ToType;
1411 return true;
1412 }
1413
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001414 // Blocks: Block pointers can be converted to void*.
1415 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001416 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001417 ConvertedType = ToType;
1418 return true;
1419 }
1420 // Blocks: A null pointer constant can be converted to a block
1421 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001422 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001423 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001424 ConvertedType = ToType;
1425 return true;
1426 }
1427
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001428 // If the left-hand-side is nullptr_t, the right side can be a null
1429 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001430 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001431 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001432 ConvertedType = ToType;
1433 return true;
1434 }
1435
Ted Kremenek6217b802009-07-29 21:53:49 +00001436 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001437 if (!ToTypePtr)
1438 return false;
1439
1440 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001441 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001442 ConvertedType = ToType;
1443 return true;
1444 }
Sebastian Redl07779722008-10-31 14:43:28 +00001445
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001446 // Beyond this point, both types need to be pointers
1447 // , including objective-c pointers.
1448 QualType ToPointeeType = ToTypePtr->getPointeeType();
1449 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1450 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1451 ToType, Context);
1452 return true;
1453
1454 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001455 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001456 if (!FromTypePtr)
1457 return false;
1458
1459 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001460
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001461 // If the unqualified pointee types are the same, this can't be a
1462 // pointer conversion, so don't do all of the work below.
1463 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1464 return false;
1465
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001466 // An rvalue of type "pointer to cv T," where T is an object type,
1467 // can be converted to an rvalue of type "pointer to cv void" (C++
1468 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001469 if (FromPointeeType->isIncompleteOrObjectType() &&
1470 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001471 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001472 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001473 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001474 return true;
1475 }
1476
Douglas Gregorf9201e02009-02-11 23:02:49 +00001477 // When we're overloading in C, we allow a special kind of pointer
1478 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001479 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001480 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001481 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001482 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001483 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001484 return true;
1485 }
1486
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001487 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001488 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001489 // An rvalue of type "pointer to cv D," where D is a class type,
1490 // can be converted to an rvalue of type "pointer to cv B," where
1491 // B is a base class (clause 10) of D. If B is an inaccessible
1492 // (clause 11) or ambiguous (10.2) base class of D, a program that
1493 // necessitates this conversion is ill-formed. The result of the
1494 // conversion is a pointer to the base class sub-object of the
1495 // derived class object. The null pointer value is converted to
1496 // the null pointer value of the destination type.
1497 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001498 // Note that we do not check for ambiguity or inaccessibility
1499 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001500 if (getLangOptions().CPlusPlus &&
1501 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001502 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001503 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001504 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001505 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001506 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001507 ToType, Context);
1508 return true;
1509 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001510
Douglas Gregorc7887512008-12-19 19:13:09 +00001511 return false;
1512}
1513
1514/// isObjCPointerConversion - Determines whether this is an
1515/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1516/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001517bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001518 QualType& ConvertedType,
1519 bool &IncompatibleObjC) {
1520 if (!getLangOptions().ObjC1)
1521 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001522
Steve Naroff14108da2009-07-10 23:34:53 +00001523 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001524 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001525 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001526 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001527
Steve Naroff14108da2009-07-10 23:34:53 +00001528 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001529 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001530 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001531 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001532 ConvertedType = ToType;
1533 return true;
1534 }
1535 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001536 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001537 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001538 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001539 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001540 ConvertedType = ToType;
1541 return true;
1542 }
1543 // Objective C++: We're able to convert from a pointer to an
1544 // interface to a pointer to a different interface.
1545 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001546 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1547 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1548 if (getLangOptions().CPlusPlus && LHS && RHS &&
1549 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1550 FromObjCPtr->getPointeeType()))
1551 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001552 ConvertedType = ToType;
1553 return true;
1554 }
1555
1556 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1557 // Okay: this is some kind of implicit downcast of Objective-C
1558 // interfaces, which is permitted. However, we're going to
1559 // complain about it.
1560 IncompatibleObjC = true;
1561 ConvertedType = FromType;
1562 return true;
1563 }
Mike Stump1eb44332009-09-09 15:08:12 +00001564 }
Steve Naroff14108da2009-07-10 23:34:53 +00001565 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001566 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001567 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001568 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001569 else if (const BlockPointerType *ToBlockPtr =
1570 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001571 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001572 // to a block pointer type.
1573 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1574 ConvertedType = ToType;
1575 return true;
1576 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001577 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001578 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001579 else if (FromType->getAs<BlockPointerType>() &&
1580 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1581 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001582 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001583 ConvertedType = ToType;
1584 return true;
1585 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001586 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001587 return false;
1588
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001589 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001590 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001591 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001592 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001593 FromPointeeType = FromBlockPtr->getPointeeType();
1594 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001595 return false;
1596
Douglas Gregorc7887512008-12-19 19:13:09 +00001597 // If we have pointers to pointers, recursively check whether this
1598 // is an Objective-C conversion.
1599 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1600 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1601 IncompatibleObjC)) {
1602 // We always complain about this conversion.
1603 IncompatibleObjC = true;
1604 ConvertedType = ToType;
1605 return true;
1606 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001607 // Allow conversion of pointee being objective-c pointer to another one;
1608 // as in I* to id.
1609 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1610 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1611 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1612 IncompatibleObjC)) {
1613 ConvertedType = ToType;
1614 return true;
1615 }
1616
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001617 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001618 // differences in the argument and result types are in Objective-C
1619 // pointer conversions. If so, we permit the conversion (but
1620 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001621 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001622 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001623 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001624 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001625 if (FromFunctionType && ToFunctionType) {
1626 // If the function types are exactly the same, this isn't an
1627 // Objective-C pointer conversion.
1628 if (Context.getCanonicalType(FromPointeeType)
1629 == Context.getCanonicalType(ToPointeeType))
1630 return false;
1631
1632 // Perform the quick checks that will tell us whether these
1633 // function types are obviously different.
1634 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1635 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1636 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1637 return false;
1638
1639 bool HasObjCConversion = false;
1640 if (Context.getCanonicalType(FromFunctionType->getResultType())
1641 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1642 // Okay, the types match exactly. Nothing to do.
1643 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1644 ToFunctionType->getResultType(),
1645 ConvertedType, IncompatibleObjC)) {
1646 // Okay, we have an Objective-C pointer conversion.
1647 HasObjCConversion = true;
1648 } else {
1649 // Function types are too different. Abort.
1650 return false;
1651 }
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Douglas Gregorc7887512008-12-19 19:13:09 +00001653 // Check argument types.
1654 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1655 ArgIdx != NumArgs; ++ArgIdx) {
1656 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1657 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1658 if (Context.getCanonicalType(FromArgType)
1659 == Context.getCanonicalType(ToArgType)) {
1660 // Okay, the types match exactly. Nothing to do.
1661 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1662 ConvertedType, IncompatibleObjC)) {
1663 // Okay, we have an Objective-C pointer conversion.
1664 HasObjCConversion = true;
1665 } else {
1666 // Argument types are too different. Abort.
1667 return false;
1668 }
1669 }
1670
1671 if (HasObjCConversion) {
1672 // We had an Objective-C conversion. Allow this pointer
1673 // conversion, but complain about it.
1674 ConvertedType = ToType;
1675 IncompatibleObjC = true;
1676 return true;
1677 }
1678 }
1679
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001680 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001681}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001682
1683/// FunctionArgTypesAreEqual - This routine checks two function proto types
1684/// for equlity of their argument types. Caller has already checked that
1685/// they have same number of arguments. This routine assumes that Objective-C
1686/// pointer types which only differ in their protocol qualifiers are equal.
1687bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1688 FunctionProtoType* NewType){
1689 if (!getLangOptions().ObjC1)
1690 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1691 NewType->arg_type_begin());
1692
1693 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1694 N = NewType->arg_type_begin(),
1695 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1696 QualType ToType = (*O);
1697 QualType FromType = (*N);
1698 if (ToType != FromType) {
1699 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1700 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001701 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1702 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1703 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1704 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001705 continue;
1706 }
John McCallc12c5bb2010-05-15 11:32:37 +00001707 else if (const ObjCObjectPointerType *PTTo =
1708 ToType->getAs<ObjCObjectPointerType>()) {
1709 if (const ObjCObjectPointerType *PTFr =
1710 FromType->getAs<ObjCObjectPointerType>())
1711 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1712 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001713 }
1714 return false;
1715 }
1716 }
1717 return true;
1718}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001719
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001720/// CheckPointerConversion - Check the pointer conversion from the
1721/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001722/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001723/// conversions for which IsPointerConversion has already returned
1724/// true. It returns true and produces a diagnostic if there was an
1725/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001726bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001727 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001728 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001729 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001730 QualType FromType = From->getType();
1731
Douglas Gregord7a95972010-06-08 17:35:15 +00001732 if (CXXBoolLiteralExpr* LitBool
1733 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1734 if (LitBool->getValue() == false)
1735 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1736 << ToType;
1737
Ted Kremenek6217b802009-07-29 21:53:49 +00001738 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1739 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001740 QualType FromPointeeType = FromPtrType->getPointeeType(),
1741 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001742
Douglas Gregor5fccd362010-03-03 23:55:11 +00001743 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1744 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001745 // We must have a derived-to-base conversion. Check an
1746 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001747 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1748 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001749 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001750 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001751 return true;
1752
1753 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001754 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001755 }
1756 }
Mike Stump1eb44332009-09-09 15:08:12 +00001757 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001758 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001759 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001760 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001761 // Objective-C++ conversions are always okay.
1762 // FIXME: We should have a different class of conversions for the
1763 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001764 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001765 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001766
Steve Naroff14108da2009-07-10 23:34:53 +00001767 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001768 return false;
1769}
1770
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001771/// IsMemberPointerConversion - Determines whether the conversion of the
1772/// expression From, which has the (possibly adjusted) type FromType, can be
1773/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1774/// If so, returns true and places the converted type (that might differ from
1775/// ToType in its cv-qualifiers at some level) into ConvertedType.
1776bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001777 QualType ToType,
1778 bool InOverloadResolution,
1779 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001780 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001781 if (!ToTypePtr)
1782 return false;
1783
1784 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001785 if (From->isNullPointerConstant(Context,
1786 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1787 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001788 ConvertedType = ToType;
1789 return true;
1790 }
1791
1792 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001793 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001794 if (!FromTypePtr)
1795 return false;
1796
1797 // A pointer to member of B can be converted to a pointer to member of D,
1798 // where D is derived from B (C++ 4.11p2).
1799 QualType FromClass(FromTypePtr->getClass(), 0);
1800 QualType ToClass(ToTypePtr->getClass(), 0);
1801 // FIXME: What happens when these are dependent? Is this function even called?
1802
1803 if (IsDerivedFrom(ToClass, FromClass)) {
1804 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1805 ToClass.getTypePtr());
1806 return true;
1807 }
1808
1809 return false;
1810}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001811
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001812/// CheckMemberPointerConversion - Check the member pointer conversion from the
1813/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001814/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001815/// for which IsMemberPointerConversion has already returned true. It returns
1816/// true and produces a diagnostic if there was an error, or returns false
1817/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001818bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001819 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001820 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001821 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001822 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001823 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001824 if (!FromPtrType) {
1825 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001826 assert(From->isNullPointerConstant(Context,
1827 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001828 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001829 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001830 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001831 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001832
Ted Kremenek6217b802009-07-29 21:53:49 +00001833 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001834 assert(ToPtrType && "No member pointer cast has a target type "
1835 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001836
Sebastian Redl21593ac2009-01-28 18:33:18 +00001837 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1838 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001839
Sebastian Redl21593ac2009-01-28 18:33:18 +00001840 // FIXME: What about dependent types?
1841 assert(FromClass->isRecordType() && "Pointer into non-class.");
1842 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001843
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001844 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001845 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001846 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1847 assert(DerivationOkay &&
1848 "Should not have been called if derivation isn't OK.");
1849 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001850
Sebastian Redl21593ac2009-01-28 18:33:18 +00001851 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1852 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001853 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1854 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1855 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1856 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001857 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001858
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001859 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001860 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1861 << FromClass << ToClass << QualType(VBase, 0)
1862 << From->getSourceRange();
1863 return true;
1864 }
1865
John McCall6b2accb2010-02-10 09:31:12 +00001866 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001867 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1868 Paths.front(),
1869 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001870
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001871 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001872 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001873 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001874 return false;
1875}
1876
Douglas Gregor98cd5992008-10-21 23:43:52 +00001877/// IsQualificationConversion - Determines whether the conversion from
1878/// an rvalue of type FromType to ToType is a qualification conversion
1879/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001880bool
1881Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001882 FromType = Context.getCanonicalType(FromType);
1883 ToType = Context.getCanonicalType(ToType);
1884
1885 // If FromType and ToType are the same type, this is not a
1886 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001887 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001888 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001889
Douglas Gregor98cd5992008-10-21 23:43:52 +00001890 // (C++ 4.4p4):
1891 // A conversion can add cv-qualifiers at levels other than the first
1892 // in multi-level pointers, subject to the following rules: [...]
1893 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001894 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001895 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001896 // Within each iteration of the loop, we check the qualifiers to
1897 // determine if this still looks like a qualification
1898 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001899 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001900 // until there are no more pointers or pointers-to-members left to
1901 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001902 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001903
1904 // -- for every j > 0, if const is in cv 1,j then const is in cv
1905 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001906 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001907 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Douglas Gregor98cd5992008-10-21 23:43:52 +00001909 // -- if the cv 1,j and cv 2,j are different, then const is in
1910 // every cv for 0 < k < j.
1911 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001912 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001913 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001914
Douglas Gregor98cd5992008-10-21 23:43:52 +00001915 // Keep track of whether all prior cv-qualifiers in the "to" type
1916 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001917 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001918 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001919 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001920
1921 // We are left with FromType and ToType being the pointee types
1922 // after unwrapping the original FromType and ToType the same number
1923 // of types. If we unwrapped any pointers, and if FromType and
1924 // ToType have the same unqualified type (since we checked
1925 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001926 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001927}
1928
Douglas Gregor734d9862009-01-30 23:27:23 +00001929/// Determines whether there is a user-defined conversion sequence
1930/// (C++ [over.ics.user]) that converts expression From to the type
1931/// ToType. If such a conversion exists, User will contain the
1932/// user-defined conversion sequence that performs such a conversion
1933/// and this routine will return true. Otherwise, this routine returns
1934/// false and User is unspecified.
1935///
Douglas Gregor734d9862009-01-30 23:27:23 +00001936/// \param AllowExplicit true if the conversion should consider C++0x
1937/// "explicit" conversion functions as well as non-explicit conversion
1938/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00001939static OverloadingResult
1940IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1941 UserDefinedConversionSequence& User,
1942 OverloadCandidateSet& CandidateSet,
1943 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001944 // Whether we will only visit constructors.
1945 bool ConstructorsOnly = false;
1946
1947 // If the type we are conversion to is a class type, enumerate its
1948 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001949 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001950 // C++ [over.match.ctor]p1:
1951 // When objects of class type are direct-initialized (8.5), or
1952 // copy-initialized from an expression of the same or a
1953 // derived class type (8.5), overload resolution selects the
1954 // constructor. [...] For copy-initialization, the candidate
1955 // functions are all the converting constructors (12.3.1) of
1956 // that class. The argument list is the expression-list within
1957 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00001958 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001959 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001960 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001961 ConstructorsOnly = true;
1962
John McCall120d63c2010-08-24 20:38:10 +00001963 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001964 // We're not going to find any constructors.
1965 } else if (CXXRecordDecl *ToRecordDecl
1966 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001967 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00001968 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001969 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001970 NamedDecl *D = *Con;
1971 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1972
Douglas Gregordec06662009-08-21 18:42:58 +00001973 // Find the constructor (which may be a template).
1974 CXXConstructorDecl *Constructor = 0;
1975 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001976 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001977 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001978 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001979 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1980 else
John McCall9aa472c2010-03-19 07:35:19 +00001981 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001982
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001983 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001984 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001985 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00001986 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
1987 /*ExplicitArgs*/ 0,
1988 &From, 1, CandidateSet,
1989 /*SuppressUserConversions=*/
1990 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001991 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001992 // Allow one user-defined conversion when user specifies a
1993 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00001994 S.AddOverloadCandidate(Constructor, FoundDecl,
1995 &From, 1, CandidateSet,
1996 /*SuppressUserConversions=*/
1997 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001998 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001999 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002000 }
2001 }
2002
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002003 // Enumerate conversion functions, if we're allowed to.
2004 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002005 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2006 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002007 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002008 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002009 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002010 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002011 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2012 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002013 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002014 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002015 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002016 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002017 DeclAccessPair FoundDecl = I.getPair();
2018 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002019 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2020 if (isa<UsingShadowDecl>(D))
2021 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2022
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002023 CXXConversionDecl *Conv;
2024 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002025 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2026 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002027 else
John McCall32daa422010-03-31 01:36:47 +00002028 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002029
2030 if (AllowExplicit || !Conv->isExplicit()) {
2031 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002032 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2033 ActingContext, From, ToType,
2034 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002035 else
John McCall120d63c2010-08-24 20:38:10 +00002036 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2037 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002038 }
2039 }
2040 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002041 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002042
2043 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002044 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002045 case OR_Success:
2046 // Record the standard conversion we used and the conversion function.
2047 if (CXXConstructorDecl *Constructor
2048 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2049 // C++ [over.ics.user]p1:
2050 // If the user-defined conversion is specified by a
2051 // constructor (12.3.1), the initial standard conversion
2052 // sequence converts the source type to the type required by
2053 // the argument of the constructor.
2054 //
2055 QualType ThisType = Constructor->getThisType(S.Context);
2056 if (Best->Conversions[0].isEllipsis())
2057 User.EllipsisConversion = true;
2058 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002059 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002060 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002061 }
John McCall120d63c2010-08-24 20:38:10 +00002062 User.ConversionFunction = Constructor;
2063 User.After.setAsIdentityConversion();
2064 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2065 User.After.setAllToTypes(ToType);
2066 return OR_Success;
2067 } else if (CXXConversionDecl *Conversion
2068 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2069 // C++ [over.ics.user]p1:
2070 //
2071 // [...] If the user-defined conversion is specified by a
2072 // conversion function (12.3.2), the initial standard
2073 // conversion sequence converts the source type to the
2074 // implicit object parameter of the conversion function.
2075 User.Before = Best->Conversions[0].Standard;
2076 User.ConversionFunction = Conversion;
2077 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002078
John McCall120d63c2010-08-24 20:38:10 +00002079 // C++ [over.ics.user]p2:
2080 // The second standard conversion sequence converts the
2081 // result of the user-defined conversion to the target type
2082 // for the sequence. Since an implicit conversion sequence
2083 // is an initialization, the special rules for
2084 // initialization by user-defined conversion apply when
2085 // selecting the best user-defined conversion for a
2086 // user-defined conversion sequence (see 13.3.3 and
2087 // 13.3.3.1).
2088 User.After = Best->FinalConversion;
2089 return OR_Success;
2090 } else {
2091 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002092 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002093 }
2094
John McCall120d63c2010-08-24 20:38:10 +00002095 case OR_No_Viable_Function:
2096 return OR_No_Viable_Function;
2097 case OR_Deleted:
2098 // No conversion here! We're done.
2099 return OR_Deleted;
2100
2101 case OR_Ambiguous:
2102 return OR_Ambiguous;
2103 }
2104
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002105 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002106}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002107
2108bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002109Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002110 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002111 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002112 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002113 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002114 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002115 if (OvResult == OR_Ambiguous)
2116 Diag(From->getSourceRange().getBegin(),
2117 diag::err_typecheck_ambiguous_condition)
2118 << From->getType() << ToType << From->getSourceRange();
2119 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2120 Diag(From->getSourceRange().getBegin(),
2121 diag::err_typecheck_nonviable_condition)
2122 << From->getType() << ToType << From->getSourceRange();
2123 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002124 return false;
John McCall120d63c2010-08-24 20:38:10 +00002125 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002126 return true;
2127}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002128
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002129/// CompareImplicitConversionSequences - Compare two implicit
2130/// conversion sequences to determine whether one is better than the
2131/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002132static ImplicitConversionSequence::CompareKind
2133CompareImplicitConversionSequences(Sema &S,
2134 const ImplicitConversionSequence& ICS1,
2135 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002136{
2137 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2138 // conversion sequences (as defined in 13.3.3.1)
2139 // -- a standard conversion sequence (13.3.3.1.1) is a better
2140 // conversion sequence than a user-defined conversion sequence or
2141 // an ellipsis conversion sequence, and
2142 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2143 // conversion sequence than an ellipsis conversion sequence
2144 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002145 //
John McCall1d318332010-01-12 00:44:57 +00002146 // C++0x [over.best.ics]p10:
2147 // For the purpose of ranking implicit conversion sequences as
2148 // described in 13.3.3.2, the ambiguous conversion sequence is
2149 // treated as a user-defined sequence that is indistinguishable
2150 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002151 if (ICS1.getKindRank() < ICS2.getKindRank())
2152 return ImplicitConversionSequence::Better;
2153 else if (ICS2.getKindRank() < ICS1.getKindRank())
2154 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002155
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002156 // The following checks require both conversion sequences to be of
2157 // the same kind.
2158 if (ICS1.getKind() != ICS2.getKind())
2159 return ImplicitConversionSequence::Indistinguishable;
2160
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002161 // Two implicit conversion sequences of the same form are
2162 // indistinguishable conversion sequences unless one of the
2163 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002164 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002165 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002166 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002167 // User-defined conversion sequence U1 is a better conversion
2168 // sequence than another user-defined conversion sequence U2 if
2169 // they contain the same user-defined conversion function or
2170 // constructor and if the second standard conversion sequence of
2171 // U1 is better than the second standard conversion sequence of
2172 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002173 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002174 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002175 return CompareStandardConversionSequences(S,
2176 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002177 ICS2.UserDefined.After);
2178 }
2179
2180 return ImplicitConversionSequence::Indistinguishable;
2181}
2182
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002183static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2184 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2185 Qualifiers Quals;
2186 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2187 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2188 }
2189
2190 return Context.hasSameUnqualifiedType(T1, T2);
2191}
2192
Douglas Gregorad323a82010-01-27 03:51:04 +00002193// Per 13.3.3.2p3, compare the given standard conversion sequences to
2194// determine if one is a proper subset of the other.
2195static ImplicitConversionSequence::CompareKind
2196compareStandardConversionSubsets(ASTContext &Context,
2197 const StandardConversionSequence& SCS1,
2198 const StandardConversionSequence& SCS2) {
2199 ImplicitConversionSequence::CompareKind Result
2200 = ImplicitConversionSequence::Indistinguishable;
2201
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002202 // the identity conversion sequence is considered to be a subsequence of
2203 // any non-identity conversion sequence
2204 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2205 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2206 return ImplicitConversionSequence::Better;
2207 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2208 return ImplicitConversionSequence::Worse;
2209 }
2210
Douglas Gregorad323a82010-01-27 03:51:04 +00002211 if (SCS1.Second != SCS2.Second) {
2212 if (SCS1.Second == ICK_Identity)
2213 Result = ImplicitConversionSequence::Better;
2214 else if (SCS2.Second == ICK_Identity)
2215 Result = ImplicitConversionSequence::Worse;
2216 else
2217 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002218 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002219 return ImplicitConversionSequence::Indistinguishable;
2220
2221 if (SCS1.Third == SCS2.Third) {
2222 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2223 : ImplicitConversionSequence::Indistinguishable;
2224 }
2225
2226 if (SCS1.Third == ICK_Identity)
2227 return Result == ImplicitConversionSequence::Worse
2228 ? ImplicitConversionSequence::Indistinguishable
2229 : ImplicitConversionSequence::Better;
2230
2231 if (SCS2.Third == ICK_Identity)
2232 return Result == ImplicitConversionSequence::Better
2233 ? ImplicitConversionSequence::Indistinguishable
2234 : ImplicitConversionSequence::Worse;
2235
2236 return ImplicitConversionSequence::Indistinguishable;
2237}
2238
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002239/// CompareStandardConversionSequences - Compare two standard
2240/// conversion sequences to determine whether one is better than the
2241/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002242static ImplicitConversionSequence::CompareKind
2243CompareStandardConversionSequences(Sema &S,
2244 const StandardConversionSequence& SCS1,
2245 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002246{
2247 // Standard conversion sequence S1 is a better conversion sequence
2248 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2249
2250 // -- S1 is a proper subsequence of S2 (comparing the conversion
2251 // sequences in the canonical form defined by 13.3.3.1.1,
2252 // excluding any Lvalue Transformation; the identity conversion
2253 // sequence is considered to be a subsequence of any
2254 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002255 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002256 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002257 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002258
2259 // -- the rank of S1 is better than the rank of S2 (by the rules
2260 // defined below), or, if not that,
2261 ImplicitConversionRank Rank1 = SCS1.getRank();
2262 ImplicitConversionRank Rank2 = SCS2.getRank();
2263 if (Rank1 < Rank2)
2264 return ImplicitConversionSequence::Better;
2265 else if (Rank2 < Rank1)
2266 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002267
Douglas Gregor57373262008-10-22 14:17:15 +00002268 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2269 // are indistinguishable unless one of the following rules
2270 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Douglas Gregor57373262008-10-22 14:17:15 +00002272 // A conversion that is not a conversion of a pointer, or
2273 // pointer to member, to bool is better than another conversion
2274 // that is such a conversion.
2275 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2276 return SCS2.isPointerConversionToBool()
2277 ? ImplicitConversionSequence::Better
2278 : ImplicitConversionSequence::Worse;
2279
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002280 // C++ [over.ics.rank]p4b2:
2281 //
2282 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002283 // conversion of B* to A* is better than conversion of B* to
2284 // void*, and conversion of A* to void* is better than conversion
2285 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002286 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002287 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002288 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002289 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002290 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2291 // Exactly one of the conversion sequences is a conversion to
2292 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002293 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2294 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002295 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2296 // Neither conversion sequence converts to a void pointer; compare
2297 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002298 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002299 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002300 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002301 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2302 // Both conversion sequences are conversions to void
2303 // pointers. Compare the source types to determine if there's an
2304 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002305 QualType FromType1 = SCS1.getFromType();
2306 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002307
2308 // Adjust the types we're converting from via the array-to-pointer
2309 // conversion, if we need to.
2310 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002311 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002312 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002313 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002314
Douglas Gregor01919692009-12-13 21:37:05 +00002315 QualType FromPointee1
2316 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2317 QualType FromPointee2
2318 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002319
John McCall120d63c2010-08-24 20:38:10 +00002320 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002321 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002322 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002323 return ImplicitConversionSequence::Worse;
2324
2325 // Objective-C++: If one interface is more specific than the
2326 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002327 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2328 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002329 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002330 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002331 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002332 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002333 return ImplicitConversionSequence::Worse;
2334 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002335 }
Douglas Gregor57373262008-10-22 14:17:15 +00002336
2337 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2338 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002339 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002340 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002341 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002342
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002343 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002344 // C++0x [over.ics.rank]p3b4:
2345 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2346 // implicit object parameter of a non-static member function declared
2347 // without a ref-qualifier, and S1 binds an rvalue reference to an
2348 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002349 // FIXME: We don't know if we're dealing with the implicit object parameter,
2350 // or if the member function in this case has a ref qualifier.
2351 // (Of course, we don't have ref qualifiers yet.)
2352 if (SCS1.RRefBinding != SCS2.RRefBinding)
2353 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2354 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002355
2356 // C++ [over.ics.rank]p3b4:
2357 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2358 // which the references refer are the same type except for
2359 // top-level cv-qualifiers, and the type to which the reference
2360 // initialized by S2 refers is more cv-qualified than the type
2361 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002362 QualType T1 = SCS1.getToType(2);
2363 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002364 T1 = S.Context.getCanonicalType(T1);
2365 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002366 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002367 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2368 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002369 if (UnqualT1 == UnqualT2) {
2370 // If the type is an array type, promote the element qualifiers to the type
2371 // for comparison.
2372 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002373 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002374 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002375 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002376 if (T2.isMoreQualifiedThan(T1))
2377 return ImplicitConversionSequence::Better;
2378 else if (T1.isMoreQualifiedThan(T2))
2379 return ImplicitConversionSequence::Worse;
2380 }
2381 }
Douglas Gregor57373262008-10-22 14:17:15 +00002382
2383 return ImplicitConversionSequence::Indistinguishable;
2384}
2385
2386/// CompareQualificationConversions - Compares two standard conversion
2387/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002388/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2389ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002390CompareQualificationConversions(Sema &S,
2391 const StandardConversionSequence& SCS1,
2392 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002393 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002394 // -- S1 and S2 differ only in their qualification conversion and
2395 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2396 // cv-qualification signature of type T1 is a proper subset of
2397 // the cv-qualification signature of type T2, and S1 is not the
2398 // deprecated string literal array-to-pointer conversion (4.2).
2399 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2400 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2401 return ImplicitConversionSequence::Indistinguishable;
2402
2403 // FIXME: the example in the standard doesn't use a qualification
2404 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002405 QualType T1 = SCS1.getToType(2);
2406 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002407 T1 = S.Context.getCanonicalType(T1);
2408 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002409 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002410 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2411 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002412
2413 // If the types are the same, we won't learn anything by unwrapped
2414 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002415 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002416 return ImplicitConversionSequence::Indistinguishable;
2417
Chandler Carruth28e318c2009-12-29 07:16:59 +00002418 // If the type is an array type, promote the element qualifiers to the type
2419 // for comparison.
2420 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002421 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002422 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002423 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002424
Mike Stump1eb44332009-09-09 15:08:12 +00002425 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002426 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002427 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002428 // Within each iteration of the loop, we check the qualifiers to
2429 // determine if this still looks like a qualification
2430 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002431 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002432 // until there are no more pointers or pointers-to-members left
2433 // to unwrap. This essentially mimics what
2434 // IsQualificationConversion does, but here we're checking for a
2435 // strict subset of qualifiers.
2436 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2437 // The qualifiers are the same, so this doesn't tell us anything
2438 // about how the sequences rank.
2439 ;
2440 else if (T2.isMoreQualifiedThan(T1)) {
2441 // T1 has fewer qualifiers, so it could be the better sequence.
2442 if (Result == ImplicitConversionSequence::Worse)
2443 // Neither has qualifiers that are a subset of the other's
2444 // qualifiers.
2445 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor57373262008-10-22 14:17:15 +00002447 Result = ImplicitConversionSequence::Better;
2448 } else if (T1.isMoreQualifiedThan(T2)) {
2449 // T2 has fewer qualifiers, so it could be the better sequence.
2450 if (Result == ImplicitConversionSequence::Better)
2451 // Neither has qualifiers that are a subset of the other's
2452 // qualifiers.
2453 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002454
Douglas Gregor57373262008-10-22 14:17:15 +00002455 Result = ImplicitConversionSequence::Worse;
2456 } else {
2457 // Qualifiers are disjoint.
2458 return ImplicitConversionSequence::Indistinguishable;
2459 }
2460
2461 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002462 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002463 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002464 }
2465
Douglas Gregor57373262008-10-22 14:17:15 +00002466 // Check that the winning standard conversion sequence isn't using
2467 // the deprecated string literal array to pointer conversion.
2468 switch (Result) {
2469 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002470 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002471 Result = ImplicitConversionSequence::Indistinguishable;
2472 break;
2473
2474 case ImplicitConversionSequence::Indistinguishable:
2475 break;
2476
2477 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002478 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002479 Result = ImplicitConversionSequence::Indistinguishable;
2480 break;
2481 }
2482
2483 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002484}
2485
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002486/// CompareDerivedToBaseConversions - Compares two standard conversion
2487/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002488/// various kinds of derived-to-base conversions (C++
2489/// [over.ics.rank]p4b3). As part of these checks, we also look at
2490/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002491ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002492CompareDerivedToBaseConversions(Sema &S,
2493 const StandardConversionSequence& SCS1,
2494 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002495 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002496 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002497 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002498 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002499
2500 // Adjust the types we're converting from via the array-to-pointer
2501 // conversion, if we need to.
2502 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002503 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002504 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002505 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002506
2507 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002508 FromType1 = S.Context.getCanonicalType(FromType1);
2509 ToType1 = S.Context.getCanonicalType(ToType1);
2510 FromType2 = S.Context.getCanonicalType(FromType2);
2511 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002512
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002513 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002514 //
2515 // If class B is derived directly or indirectly from class A and
2516 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002517 //
2518 // For Objective-C, we let A, B, and C also be Objective-C
2519 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002520
2521 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002522 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002523 SCS2.Second == ICK_Pointer_Conversion &&
2524 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2525 FromType1->isPointerType() && FromType2->isPointerType() &&
2526 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002527 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002528 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002529 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002530 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002531 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002532 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002533 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002534 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002535
John McCallc12c5bb2010-05-15 11:32:37 +00002536 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2537 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2538 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2539 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002540
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002541 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002542 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002543 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002544 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002545 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002546 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002547
2548 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002549 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002550 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002551 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002552 return ImplicitConversionSequence::Worse;
2553 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002554 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002555
2556 // -- conversion of B* to A* is better than conversion of C* to A*,
2557 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002558 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002559 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002560 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002561 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002562
Douglas Gregorcb7de522008-11-26 23:31:11 +00002563 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002564 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002565 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002566 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002567 return ImplicitConversionSequence::Worse;
2568 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002569 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002570 }
2571
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002572 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002573 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2574 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2575 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2576 const MemberPointerType * FromMemPointer1 =
2577 FromType1->getAs<MemberPointerType>();
2578 const MemberPointerType * ToMemPointer1 =
2579 ToType1->getAs<MemberPointerType>();
2580 const MemberPointerType * FromMemPointer2 =
2581 FromType2->getAs<MemberPointerType>();
2582 const MemberPointerType * ToMemPointer2 =
2583 ToType2->getAs<MemberPointerType>();
2584 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2585 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2586 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2587 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2588 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2589 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2590 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2591 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002592 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002593 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002594 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002595 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002596 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002597 return ImplicitConversionSequence::Better;
2598 }
2599 // conversion of B::* to C::* is better than conversion of A::* to C::*
2600 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002601 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002602 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002603 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002604 return ImplicitConversionSequence::Worse;
2605 }
2606 }
2607
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002608 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002609 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002610 // -- binding of an expression of type C to a reference of type
2611 // B& is better than binding an expression of type C to a
2612 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002613 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2614 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2615 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002616 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002617 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002618 return ImplicitConversionSequence::Worse;
2619 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002620
Douglas Gregor225c41e2008-11-03 19:09:14 +00002621 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002622 // -- binding of an expression of type B to a reference of type
2623 // A& is better than binding an expression of type C to a
2624 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002625 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2626 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2627 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002628 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002629 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002630 return ImplicitConversionSequence::Worse;
2631 }
2632 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002633
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002634 return ImplicitConversionSequence::Indistinguishable;
2635}
2636
Douglas Gregorabe183d2010-04-13 16:31:36 +00002637/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2638/// determine whether they are reference-related,
2639/// reference-compatible, reference-compatible with added
2640/// qualification, or incompatible, for use in C++ initialization by
2641/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2642/// type, and the first type (T1) is the pointee type of the reference
2643/// type being initialized.
2644Sema::ReferenceCompareResult
2645Sema::CompareReferenceRelationship(SourceLocation Loc,
2646 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002647 bool &DerivedToBase,
2648 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002649 assert(!OrigT1->isReferenceType() &&
2650 "T1 must be the pointee type of the reference type");
2651 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2652
2653 QualType T1 = Context.getCanonicalType(OrigT1);
2654 QualType T2 = Context.getCanonicalType(OrigT2);
2655 Qualifiers T1Quals, T2Quals;
2656 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2657 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2658
2659 // C++ [dcl.init.ref]p4:
2660 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2661 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2662 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002663 DerivedToBase = false;
2664 ObjCConversion = false;
2665 if (UnqualT1 == UnqualT2) {
2666 // Nothing to do.
2667 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002668 IsDerivedFrom(UnqualT2, UnqualT1))
2669 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002670 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2671 UnqualT2->isObjCObjectOrInterfaceType() &&
2672 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2673 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002674 else
2675 return Ref_Incompatible;
2676
2677 // At this point, we know that T1 and T2 are reference-related (at
2678 // least).
2679
2680 // If the type is an array type, promote the element qualifiers to the type
2681 // for comparison.
2682 if (isa<ArrayType>(T1) && T1Quals)
2683 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2684 if (isa<ArrayType>(T2) && T2Quals)
2685 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2686
2687 // C++ [dcl.init.ref]p4:
2688 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2689 // reference-related to T2 and cv1 is the same cv-qualification
2690 // as, or greater cv-qualification than, cv2. For purposes of
2691 // overload resolution, cases for which cv1 is greater
2692 // cv-qualification than cv2 are identified as
2693 // reference-compatible with added qualification (see 13.3.3.2).
2694 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2695 return Ref_Compatible;
2696 else if (T1.isMoreQualifiedThan(T2))
2697 return Ref_Compatible_With_Added_Qualification;
2698 else
2699 return Ref_Related;
2700}
2701
Douglas Gregor604eb652010-08-11 02:15:33 +00002702/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002703/// with DeclType. Return true if something definite is found.
2704static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002705FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2706 QualType DeclType, SourceLocation DeclLoc,
2707 Expr *Init, QualType T2, bool AllowRvalues,
2708 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002709 assert(T2->isRecordType() && "Can only find conversions of record types.");
2710 CXXRecordDecl *T2RecordDecl
2711 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2712
Douglas Gregor604eb652010-08-11 02:15:33 +00002713 QualType ToType
2714 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2715 : DeclType;
2716
Sebastian Redl4680bf22010-06-30 18:13:39 +00002717 OverloadCandidateSet CandidateSet(DeclLoc);
2718 const UnresolvedSetImpl *Conversions
2719 = T2RecordDecl->getVisibleConversionFunctions();
2720 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2721 E = Conversions->end(); I != E; ++I) {
2722 NamedDecl *D = *I;
2723 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2724 if (isa<UsingShadowDecl>(D))
2725 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2726
2727 FunctionTemplateDecl *ConvTemplate
2728 = dyn_cast<FunctionTemplateDecl>(D);
2729 CXXConversionDecl *Conv;
2730 if (ConvTemplate)
2731 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2732 else
2733 Conv = cast<CXXConversionDecl>(D);
2734
Douglas Gregor604eb652010-08-11 02:15:33 +00002735 // If this is an explicit conversion, and we're not allowed to consider
2736 // explicit conversions, skip it.
2737 if (!AllowExplicit && Conv->isExplicit())
2738 continue;
2739
2740 if (AllowRvalues) {
2741 bool DerivedToBase = false;
2742 bool ObjCConversion = false;
2743 if (!ConvTemplate &&
2744 S.CompareReferenceRelationship(DeclLoc,
2745 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2746 DeclType.getNonReferenceType().getUnqualifiedType(),
2747 DerivedToBase, ObjCConversion)
2748 == Sema::Ref_Incompatible)
2749 continue;
2750 } else {
2751 // If the conversion function doesn't return a reference type,
2752 // it can't be considered for this conversion. An rvalue reference
2753 // is only acceptable if its referencee is a function type.
2754
2755 const ReferenceType *RefType =
2756 Conv->getConversionType()->getAs<ReferenceType>();
2757 if (!RefType ||
2758 (!RefType->isLValueReferenceType() &&
2759 !RefType->getPointeeType()->isFunctionType()))
2760 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002761 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002762
2763 if (ConvTemplate)
2764 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2765 Init, ToType, CandidateSet);
2766 else
2767 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2768 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002769 }
2770
2771 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002772 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002773 case OR_Success:
2774 // C++ [over.ics.ref]p1:
2775 //
2776 // [...] If the parameter binds directly to the result of
2777 // applying a conversion function to the argument
2778 // expression, the implicit conversion sequence is a
2779 // user-defined conversion sequence (13.3.3.1.2), with the
2780 // second standard conversion sequence either an identity
2781 // conversion or, if the conversion function returns an
2782 // entity of a type that is a derived class of the parameter
2783 // type, a derived-to-base Conversion.
2784 if (!Best->FinalConversion.DirectBinding)
2785 return false;
2786
2787 ICS.setUserDefined();
2788 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2789 ICS.UserDefined.After = Best->FinalConversion;
2790 ICS.UserDefined.ConversionFunction = Best->Function;
2791 ICS.UserDefined.EllipsisConversion = false;
2792 assert(ICS.UserDefined.After.ReferenceBinding &&
2793 ICS.UserDefined.After.DirectBinding &&
2794 "Expected a direct reference binding!");
2795 return true;
2796
2797 case OR_Ambiguous:
2798 ICS.setAmbiguous();
2799 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2800 Cand != CandidateSet.end(); ++Cand)
2801 if (Cand->Viable)
2802 ICS.Ambiguous.addConversion(Cand->Function);
2803 return true;
2804
2805 case OR_No_Viable_Function:
2806 case OR_Deleted:
2807 // There was no suitable conversion, or we found a deleted
2808 // conversion; continue with other checks.
2809 return false;
2810 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002811
2812 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002813}
2814
Douglas Gregorabe183d2010-04-13 16:31:36 +00002815/// \brief Compute an implicit conversion sequence for reference
2816/// initialization.
2817static ImplicitConversionSequence
2818TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2819 SourceLocation DeclLoc,
2820 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002821 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002822 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2823
2824 // Most paths end in a failed conversion.
2825 ImplicitConversionSequence ICS;
2826 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2827
2828 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2829 QualType T2 = Init->getType();
2830
2831 // If the initializer is the address of an overloaded function, try
2832 // to resolve the overloaded function. If all goes well, T2 is the
2833 // type of the resulting function.
2834 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2835 DeclAccessPair Found;
2836 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2837 false, Found))
2838 T2 = Fn->getType();
2839 }
2840
2841 // Compute some basic properties of the types and the initializer.
2842 bool isRValRef = DeclType->isRValueReferenceType();
2843 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002844 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002845 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002846 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002847 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2848 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002849
Douglas Gregorabe183d2010-04-13 16:31:36 +00002850
Sebastian Redl4680bf22010-06-30 18:13:39 +00002851 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002852 // A reference to type "cv1 T1" is initialized by an expression
2853 // of type "cv2 T2" as follows:
2854
Sebastian Redl4680bf22010-06-30 18:13:39 +00002855 // -- If reference is an lvalue reference and the initializer expression
2856 // The next bullet point (T1 is a function) is pretty much equivalent to this
2857 // one, so it's handled here.
2858 if (!isRValRef || T1->isFunctionType()) {
2859 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2860 // reference-compatible with "cv2 T2," or
2861 //
2862 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2863 if (InitCategory.isLValue() &&
2864 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002865 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002866 // When a parameter of reference type binds directly (8.5.3)
2867 // to an argument expression, the implicit conversion sequence
2868 // is the identity conversion, unless the argument expression
2869 // has a type that is a derived class of the parameter type,
2870 // in which case the implicit conversion sequence is a
2871 // derived-to-base Conversion (13.3.3.1).
2872 ICS.setStandard();
2873 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002874 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2875 : ObjCConversion? ICK_Compatible_Conversion
2876 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002877 ICS.Standard.Third = ICK_Identity;
2878 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2879 ICS.Standard.setToType(0, T2);
2880 ICS.Standard.setToType(1, T1);
2881 ICS.Standard.setToType(2, T1);
2882 ICS.Standard.ReferenceBinding = true;
2883 ICS.Standard.DirectBinding = true;
2884 ICS.Standard.RRefBinding = isRValRef;
2885 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002886
Sebastian Redl4680bf22010-06-30 18:13:39 +00002887 // Nothing more to do: the inaccessibility/ambiguity check for
2888 // derived-to-base conversions is suppressed when we're
2889 // computing the implicit conversion sequence (C++
2890 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002891 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002892 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002893
Sebastian Redl4680bf22010-06-30 18:13:39 +00002894 // -- has a class type (i.e., T2 is a class type), where T1 is
2895 // not reference-related to T2, and can be implicitly
2896 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2897 // is reference-compatible with "cv3 T3" 92) (this
2898 // conversion is selected by enumerating the applicable
2899 // conversion functions (13.3.1.6) and choosing the best
2900 // one through overload resolution (13.3)),
2901 if (!SuppressUserConversions && T2->isRecordType() &&
2902 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2903 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002904 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2905 Init, T2, /*AllowRvalues=*/false,
2906 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002907 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002908 }
2909 }
2910
Sebastian Redl4680bf22010-06-30 18:13:39 +00002911 // -- Otherwise, the reference shall be an lvalue reference to a
2912 // non-volatile const type (i.e., cv1 shall be const), or the reference
2913 // shall be an rvalue reference and the initializer expression shall be
2914 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002915 //
2916 // We actually handle one oddity of C++ [over.ics.ref] at this
2917 // point, which is that, due to p2 (which short-circuits reference
2918 // binding by only attempting a simple conversion for non-direct
2919 // bindings) and p3's strange wording, we allow a const volatile
2920 // reference to bind to an rvalue. Hence the check for the presence
2921 // of "const" rather than checking for "const" being the only
2922 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002923 // This is also the point where rvalue references and lvalue inits no longer
2924 // go together.
2925 if ((!isRValRef && !T1.isConstQualified()) ||
2926 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002927 return ICS;
2928
Sebastian Redl4680bf22010-06-30 18:13:39 +00002929 // -- If T1 is a function type, then
2930 // -- if T2 is the same type as T1, the reference is bound to the
2931 // initializer expression lvalue;
2932 // -- if T2 is a class type and the initializer expression can be
2933 // implicitly converted to an lvalue of type T1 [...], the
2934 // reference is bound to the function lvalue that is the result
2935 // of the conversion;
2936 // This is the same as for the lvalue case above, so it was handled there.
2937 // -- otherwise, the program is ill-formed.
2938 // This is the one difference to the lvalue case.
2939 if (T1->isFunctionType())
2940 return ICS;
2941
2942 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002943 // -- the initializer expression is an rvalue and "cv1 T1"
2944 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002945 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002946 // -- T1 is not reference-related to T2 and the initializer
2947 // expression can be implicitly converted to an rvalue
2948 // of type "cv3 T3" (this conversion is selected by
2949 // enumerating the applicable conversion functions
2950 // (13.3.1.6) and choosing the best one through overload
2951 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002952 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002953 // then the reference is bound to the initializer
2954 // expression rvalue in the first case and to the object
2955 // that is the result of the conversion in the second case
2956 // (or, in either case, to the appropriate base class
2957 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00002958 if (T2->isRecordType()) {
2959 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2960 // direct binding in C++0x but not in C++03.
2961 if (InitCategory.isRValue() &&
2962 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2963 ICS.setStandard();
2964 ICS.Standard.First = ICK_Identity;
2965 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2966 : ObjCConversion? ICK_Compatible_Conversion
2967 : ICK_Identity;
2968 ICS.Standard.Third = ICK_Identity;
2969 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2970 ICS.Standard.setToType(0, T2);
2971 ICS.Standard.setToType(1, T1);
2972 ICS.Standard.setToType(2, T1);
2973 ICS.Standard.ReferenceBinding = true;
2974 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2975 ICS.Standard.RRefBinding = isRValRef;
2976 ICS.Standard.CopyConstructor = 0;
2977 return ICS;
2978 }
2979
2980 // Second case: not reference-related.
2981 if (RefRelationship == Sema::Ref_Incompatible &&
2982 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2983 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2984 Init, T2, /*AllowRvalues=*/true,
2985 AllowExplicit))
2986 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002987 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002988
Douglas Gregorabe183d2010-04-13 16:31:36 +00002989 // -- Otherwise, a temporary of type "cv1 T1" is created and
2990 // initialized from the initializer expression using the
2991 // rules for a non-reference copy initialization (8.5). The
2992 // reference is then bound to the temporary. If T1 is
2993 // reference-related to T2, cv1 must be the same
2994 // cv-qualification as, or greater cv-qualification than,
2995 // cv2; otherwise, the program is ill-formed.
2996 if (RefRelationship == Sema::Ref_Related) {
2997 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2998 // we would be reference-compatible or reference-compatible with
2999 // added qualification. But that wasn't the case, so the reference
3000 // initialization fails.
3001 return ICS;
3002 }
3003
3004 // If at least one of the types is a class type, the types are not
3005 // related, and we aren't allowed any user conversions, the
3006 // reference binding fails. This case is important for breaking
3007 // recursion, since TryImplicitConversion below will attempt to
3008 // create a temporary through the use of a copy constructor.
3009 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3010 (T1->isRecordType() || T2->isRecordType()))
3011 return ICS;
3012
3013 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003014 // When a parameter of reference type is not bound directly to
3015 // an argument expression, the conversion sequence is the one
3016 // required to convert the argument expression to the
3017 // underlying type of the reference according to
3018 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3019 // to copy-initializing a temporary of the underlying type with
3020 // the argument expression. Any difference in top-level
3021 // cv-qualification is subsumed by the initialization itself
3022 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003023 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3024 /*AllowExplicit=*/false,
3025 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003026
3027 // Of course, that's still a reference binding.
3028 if (ICS.isStandard()) {
3029 ICS.Standard.ReferenceBinding = true;
3030 ICS.Standard.RRefBinding = isRValRef;
3031 } else if (ICS.isUserDefined()) {
3032 ICS.UserDefined.After.ReferenceBinding = true;
3033 ICS.UserDefined.After.RRefBinding = isRValRef;
3034 }
3035 return ICS;
3036}
3037
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003038/// TryCopyInitialization - Try to copy-initialize a value of type
3039/// ToType from the expression From. Return the implicit conversion
3040/// sequence required to pass this argument, which may be a bad
3041/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003042/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003043/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003044static ImplicitConversionSequence
3045TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003046 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003047 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003048 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003049 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003050 /*FIXME:*/From->getLocStart(),
3051 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003052 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003053
John McCall120d63c2010-08-24 20:38:10 +00003054 return TryImplicitConversion(S, From, ToType,
3055 SuppressUserConversions,
3056 /*AllowExplicit=*/false,
3057 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003058}
3059
Douglas Gregor96176b32008-11-18 23:14:02 +00003060/// TryObjectArgumentInitialization - Try to initialize the object
3061/// parameter of the given member function (@c Method) from the
3062/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003063static ImplicitConversionSequence
3064TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3065 CXXMethodDecl *Method,
3066 CXXRecordDecl *ActingContext) {
3067 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003068 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3069 // const volatile object.
3070 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3071 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003072 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003073
3074 // Set up the conversion sequence as a "bad" conversion, to allow us
3075 // to exit early.
3076 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003077
3078 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003079 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003080 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003081 FromType = PT->getPointeeType();
3082
3083 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003084
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003085 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003086 // where X is the class of which the function is a member
3087 // (C++ [over.match.funcs]p4). However, when finding an implicit
3088 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003089 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003090 // (C++ [over.match.funcs]p5). We perform a simplified version of
3091 // reference binding here, that allows class rvalues to bind to
3092 // non-constant references.
3093
3094 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3095 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003096 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003097 if (ImplicitParamType.getCVRQualifiers()
3098 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003099 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003100 ICS.setBad(BadConversionSequence::bad_qualifiers,
3101 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003102 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003103 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003104
3105 // Check that we have either the same type or a derived type. It
3106 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003107 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003108 ImplicitConversionKind SecondKind;
3109 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3110 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003111 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003112 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003113 else {
John McCallb1bdc622010-02-25 01:37:24 +00003114 ICS.setBad(BadConversionSequence::unrelated_class,
3115 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003116 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003117 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003118
3119 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003120 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003121 ICS.Standard.setAsIdentityConversion();
3122 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003123 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003124 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003125 ICS.Standard.ReferenceBinding = true;
3126 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003127 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003128 return ICS;
3129}
3130
3131/// PerformObjectArgumentInitialization - Perform initialization of
3132/// the implicit object parameter for the given Method with the given
3133/// expression.
3134bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003135Sema::PerformObjectArgumentInitialization(Expr *&From,
3136 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003137 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003138 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003139 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003140 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003141 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003142
Ted Kremenek6217b802009-07-29 21:53:49 +00003143 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003144 FromRecordType = PT->getPointeeType();
3145 DestType = Method->getThisType(Context);
3146 } else {
3147 FromRecordType = From->getType();
3148 DestType = ImplicitParamRecordType;
3149 }
3150
John McCall701c89e2009-12-03 04:06:58 +00003151 // Note that we always use the true parent context when performing
3152 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003153 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003154 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003155 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003156 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003157 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003158 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003159 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003160
Douglas Gregor5fccd362010-03-03 23:55:11 +00003161 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003162 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003163
Douglas Gregor5fccd362010-03-03 23:55:11 +00003164 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003165 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003166 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003167 return false;
3168}
3169
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003170/// TryContextuallyConvertToBool - Attempt to contextually convert the
3171/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003172static ImplicitConversionSequence
3173TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003174 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003175 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003176 // FIXME: Are these flags correct?
3177 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003178 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003179 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003180}
3181
3182/// PerformContextuallyConvertToBool - Perform a contextual conversion
3183/// of the expression From to bool (C++0x [conv]p3).
3184bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003185 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003186 if (!ICS.isBad())
3187 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003188
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003189 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003190 return Diag(From->getSourceRange().getBegin(),
3191 diag::err_typecheck_bool_condition)
3192 << From->getType() << From->getSourceRange();
3193 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003194}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003195
3196/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3197/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003198static ImplicitConversionSequence
3199TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3200 QualType Ty = S.Context.getObjCIdType();
3201 return TryImplicitConversion(S, From, Ty,
3202 // FIXME: Are these flags correct?
3203 /*SuppressUserConversions=*/false,
3204 /*AllowExplicit=*/true,
3205 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003206}
John McCall120d63c2010-08-24 20:38:10 +00003207
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003208/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3209/// of the expression From to 'id'.
3210bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003211 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003212 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003213 if (!ICS.isBad())
3214 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3215 return true;
3216}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003217
Douglas Gregorc30614b2010-06-29 23:17:37 +00003218/// \brief Attempt to convert the given expression to an integral or
3219/// enumeration type.
3220///
3221/// This routine will attempt to convert an expression of class type to an
3222/// integral or enumeration type, if that class type only has a single
3223/// conversion to an integral or enumeration type.
3224///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003225/// \param Loc The source location of the construct that requires the
3226/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003227///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003228/// \param FromE The expression we're converting from.
3229///
3230/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3231/// have integral or enumeration type.
3232///
3233/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3234/// incomplete class type.
3235///
3236/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3237/// explicit conversion function (because no implicit conversion functions
3238/// were available). This is a recovery mode.
3239///
3240/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3241/// showing which conversion was picked.
3242///
3243/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3244/// conversion function that could convert to integral or enumeration type.
3245///
3246/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3247/// usable conversion function.
3248///
3249/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3250/// function, which may be an extension in this case.
3251///
3252/// \returns The expression, converted to an integral or enumeration type if
3253/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003254ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003255Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003256 const PartialDiagnostic &NotIntDiag,
3257 const PartialDiagnostic &IncompleteDiag,
3258 const PartialDiagnostic &ExplicitConvDiag,
3259 const PartialDiagnostic &ExplicitConvNote,
3260 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003261 const PartialDiagnostic &AmbigNote,
3262 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003263 // We can't perform any more checking for type-dependent expressions.
3264 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003265 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003266
3267 // If the expression already has integral or enumeration type, we're golden.
3268 QualType T = From->getType();
3269 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003270 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003271
3272 // FIXME: Check for missing '()' if T is a function type?
3273
3274 // If we don't have a class type in C++, there's no way we can get an
3275 // expression of integral or enumeration type.
3276 const RecordType *RecordTy = T->getAs<RecordType>();
3277 if (!RecordTy || !getLangOptions().CPlusPlus) {
3278 Diag(Loc, NotIntDiag)
3279 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003280 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003281 }
3282
3283 // We must have a complete class type.
3284 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003285 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003286
3287 // Look for a conversion to an integral or enumeration type.
3288 UnresolvedSet<4> ViableConversions;
3289 UnresolvedSet<4> ExplicitConversions;
3290 const UnresolvedSetImpl *Conversions
3291 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3292
3293 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3294 E = Conversions->end();
3295 I != E;
3296 ++I) {
3297 if (CXXConversionDecl *Conversion
3298 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3299 if (Conversion->getConversionType().getNonReferenceType()
3300 ->isIntegralOrEnumerationType()) {
3301 if (Conversion->isExplicit())
3302 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3303 else
3304 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3305 }
3306 }
3307
3308 switch (ViableConversions.size()) {
3309 case 0:
3310 if (ExplicitConversions.size() == 1) {
3311 DeclAccessPair Found = ExplicitConversions[0];
3312 CXXConversionDecl *Conversion
3313 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3314
3315 // The user probably meant to invoke the given explicit
3316 // conversion; use it.
3317 QualType ConvTy
3318 = Conversion->getConversionType().getNonReferenceType();
3319 std::string TypeStr;
3320 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3321
3322 Diag(Loc, ExplicitConvDiag)
3323 << T << ConvTy
3324 << FixItHint::CreateInsertion(From->getLocStart(),
3325 "static_cast<" + TypeStr + ">(")
3326 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3327 ")");
3328 Diag(Conversion->getLocation(), ExplicitConvNote)
3329 << ConvTy->isEnumeralType() << ConvTy;
3330
3331 // If we aren't in a SFINAE context, build a call to the
3332 // explicit conversion function.
3333 if (isSFINAEContext())
3334 return ExprError();
3335
3336 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003337 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003338 }
3339
3340 // We'll complain below about a non-integral condition type.
3341 break;
3342
3343 case 1: {
3344 // Apply this conversion.
3345 DeclAccessPair Found = ViableConversions[0];
3346 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003347
3348 CXXConversionDecl *Conversion
3349 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3350 QualType ConvTy
3351 = Conversion->getConversionType().getNonReferenceType();
3352 if (ConvDiag.getDiagID()) {
3353 if (isSFINAEContext())
3354 return ExprError();
3355
3356 Diag(Loc, ConvDiag)
3357 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3358 }
3359
John McCall9ae2f072010-08-23 23:25:46 +00003360 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003361 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003362 break;
3363 }
3364
3365 default:
3366 Diag(Loc, AmbigDiag)
3367 << T << From->getSourceRange();
3368 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3369 CXXConversionDecl *Conv
3370 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3371 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3372 Diag(Conv->getLocation(), AmbigNote)
3373 << ConvTy->isEnumeralType() << ConvTy;
3374 }
John McCall9ae2f072010-08-23 23:25:46 +00003375 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003376 }
3377
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003378 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003379 Diag(Loc, NotIntDiag)
3380 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003381
John McCall9ae2f072010-08-23 23:25:46 +00003382 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003383}
3384
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003385/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003386/// candidate functions, using the given function call arguments. If
3387/// @p SuppressUserConversions, then don't allow user-defined
3388/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003389///
3390/// \para PartialOverloading true if we are performing "partial" overloading
3391/// based on an incomplete set of function arguments. This feature is used by
3392/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003393void
3394Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003395 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003396 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003397 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003398 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003399 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003400 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003401 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003402 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003403 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003404 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003405
Douglas Gregor88a35142008-12-22 05:46:06 +00003406 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003407 if (!isa<CXXConstructorDecl>(Method)) {
3408 // If we get here, it's because we're calling a member function
3409 // that is named without a member access expression (e.g.,
3410 // "this->f") that was either written explicitly or created
3411 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003412 // function, e.g., X::f(). We use an empty type for the implied
3413 // object argument (C++ [over.call.func]p3), and the acting context
3414 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003415 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003416 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003417 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003418 return;
3419 }
3420 // We treat a constructor like a non-member function, since its object
3421 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003422 }
3423
Douglas Gregorfd476482009-11-13 23:59:09 +00003424 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003425 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003426
Douglas Gregor7edfb692009-11-23 12:27:39 +00003427 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003428 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003429
Douglas Gregor66724ea2009-11-14 01:20:54 +00003430 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3431 // C++ [class.copy]p3:
3432 // A member function template is never instantiated to perform the copy
3433 // of a class object to an object of its class type.
3434 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3435 if (NumArgs == 1 &&
3436 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003437 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3438 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003439 return;
3440 }
3441
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003442 // Add this candidate
3443 CandidateSet.push_back(OverloadCandidate());
3444 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003445 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003446 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003447 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003448 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003449 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003450
3451 unsigned NumArgsInProto = Proto->getNumArgs();
3452
3453 // (C++ 13.3.2p2): A candidate function having fewer than m
3454 // parameters is viable only if it has an ellipsis in its parameter
3455 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003456 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3457 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003458 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003459 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003460 return;
3461 }
3462
3463 // (C++ 13.3.2p2): A candidate function having more than m parameters
3464 // is viable only if the (m+1)st parameter has a default argument
3465 // (8.3.6). For the purposes of overload resolution, the
3466 // parameter list is truncated on the right, so that there are
3467 // exactly m parameters.
3468 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003469 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003470 // Not enough arguments.
3471 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003472 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003473 return;
3474 }
3475
3476 // Determine the implicit conversion sequences for each of the
3477 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003478 Candidate.Conversions.resize(NumArgs);
3479 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3480 if (ArgIdx < NumArgsInProto) {
3481 // (C++ 13.3.2p3): for F to be a viable function, there shall
3482 // exist for each argument an implicit conversion sequence
3483 // (13.3.3.1) that converts that argument to the corresponding
3484 // parameter of F.
3485 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003486 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003487 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003488 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003489 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003490 if (Candidate.Conversions[ArgIdx].isBad()) {
3491 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003492 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003493 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003494 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003495 } else {
3496 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3497 // argument for which there is no corresponding parameter is
3498 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003499 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003500 }
3501 }
3502}
3503
Douglas Gregor063daf62009-03-13 18:40:31 +00003504/// \brief Add all of the function declarations in the given function set to
3505/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003506void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003507 Expr **Args, unsigned NumArgs,
3508 OverloadCandidateSet& CandidateSet,
3509 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003510 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003511 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3512 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003513 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003514 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003515 cast<CXXMethodDecl>(FD)->getParent(),
3516 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003517 CandidateSet, SuppressUserConversions);
3518 else
John McCall9aa472c2010-03-19 07:35:19 +00003519 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003520 SuppressUserConversions);
3521 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003522 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003523 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3524 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003525 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003526 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003527 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003528 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003529 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003530 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003531 else
John McCall9aa472c2010-03-19 07:35:19 +00003532 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003533 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003534 Args, NumArgs, CandidateSet,
3535 SuppressUserConversions);
3536 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003537 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003538}
3539
John McCall314be4e2009-11-17 07:50:12 +00003540/// AddMethodCandidate - Adds a named decl (which is some kind of
3541/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003542void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003543 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003544 Expr **Args, unsigned NumArgs,
3545 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003546 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003547 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003548 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003549
3550 if (isa<UsingShadowDecl>(Decl))
3551 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3552
3553 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3554 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3555 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003556 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3557 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003558 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003559 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003560 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003561 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003562 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003563 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003564 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003565 }
3566}
3567
Douglas Gregor96176b32008-11-18 23:14:02 +00003568/// AddMethodCandidate - Adds the given C++ member function to the set
3569/// of candidate functions, using the given function call arguments
3570/// and the object argument (@c Object). For example, in a call
3571/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3572/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3573/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003574/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003575void
John McCall9aa472c2010-03-19 07:35:19 +00003576Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003577 CXXRecordDecl *ActingContext, QualType ObjectType,
3578 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003579 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003580 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003581 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003582 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003583 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003584 assert(!isa<CXXConstructorDecl>(Method) &&
3585 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003586
Douglas Gregor3f396022009-09-28 04:47:19 +00003587 if (!CandidateSet.isNewCandidate(Method))
3588 return;
3589
Douglas Gregor7edfb692009-11-23 12:27:39 +00003590 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003591 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003592
Douglas Gregor96176b32008-11-18 23:14:02 +00003593 // Add this candidate
3594 CandidateSet.push_back(OverloadCandidate());
3595 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003596 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003597 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003598 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003599 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003600
3601 unsigned NumArgsInProto = Proto->getNumArgs();
3602
3603 // (C++ 13.3.2p2): A candidate function having fewer than m
3604 // parameters is viable only if it has an ellipsis in its parameter
3605 // list (8.3.5).
3606 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3607 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003608 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003609 return;
3610 }
3611
3612 // (C++ 13.3.2p2): A candidate function having more than m parameters
3613 // is viable only if the (m+1)st parameter has a default argument
3614 // (8.3.6). For the purposes of overload resolution, the
3615 // parameter list is truncated on the right, so that there are
3616 // exactly m parameters.
3617 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3618 if (NumArgs < MinRequiredArgs) {
3619 // Not enough arguments.
3620 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003621 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003622 return;
3623 }
3624
3625 Candidate.Viable = true;
3626 Candidate.Conversions.resize(NumArgs + 1);
3627
John McCall701c89e2009-12-03 04:06:58 +00003628 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003629 // The implicit object argument is ignored.
3630 Candidate.IgnoreObjectArgument = true;
3631 else {
3632 // Determine the implicit conversion sequence for the object
3633 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003634 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003635 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3636 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003637 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003638 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003639 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003640 return;
3641 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003642 }
3643
3644 // Determine the implicit conversion sequences for each of the
3645 // arguments.
3646 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3647 if (ArgIdx < NumArgsInProto) {
3648 // (C++ 13.3.2p3): for F to be a viable function, there shall
3649 // exist for each argument an implicit conversion sequence
3650 // (13.3.3.1) that converts that argument to the corresponding
3651 // parameter of F.
3652 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003653 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003654 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003655 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003656 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003657 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003658 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003659 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003660 break;
3661 }
3662 } else {
3663 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3664 // argument for which there is no corresponding parameter is
3665 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003666 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003667 }
3668 }
3669}
Douglas Gregora9333192010-05-08 17:41:32 +00003670
Douglas Gregor6b906862009-08-21 00:16:32 +00003671/// \brief Add a C++ member function template as a candidate to the candidate
3672/// set, using template argument deduction to produce an appropriate member
3673/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003674void
Douglas Gregor6b906862009-08-21 00:16:32 +00003675Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003676 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003677 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003678 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003679 QualType ObjectType,
3680 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003681 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003682 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003683 if (!CandidateSet.isNewCandidate(MethodTmpl))
3684 return;
3685
Douglas Gregor6b906862009-08-21 00:16:32 +00003686 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003687 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003688 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003689 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003690 // candidate functions in the usual way.113) A given name can refer to one
3691 // or more function templates and also to a set of overloaded non-template
3692 // functions. In such a case, the candidate functions generated from each
3693 // function template are combined with the set of non-template candidate
3694 // functions.
John McCall5769d612010-02-08 23:07:23 +00003695 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003696 FunctionDecl *Specialization = 0;
3697 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003698 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003699 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003700 CandidateSet.push_back(OverloadCandidate());
3701 OverloadCandidate &Candidate = CandidateSet.back();
3702 Candidate.FoundDecl = FoundDecl;
3703 Candidate.Function = MethodTmpl->getTemplatedDecl();
3704 Candidate.Viable = false;
3705 Candidate.FailureKind = ovl_fail_bad_deduction;
3706 Candidate.IsSurrogate = false;
3707 Candidate.IgnoreObjectArgument = false;
3708 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3709 Info);
3710 return;
3711 }
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Douglas Gregor6b906862009-08-21 00:16:32 +00003713 // Add the function template specialization produced by template argument
3714 // deduction as a candidate.
3715 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003716 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003717 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003718 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003719 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003720 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003721}
3722
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003723/// \brief Add a C++ function template specialization as a candidate
3724/// in the candidate set, using template argument deduction to produce
3725/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003726void
Douglas Gregore53060f2009-06-25 22:08:12 +00003727Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003728 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003729 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003730 Expr **Args, unsigned NumArgs,
3731 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003732 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003733 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3734 return;
3735
Douglas Gregore53060f2009-06-25 22:08:12 +00003736 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003737 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003738 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003739 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003740 // candidate functions in the usual way.113) A given name can refer to one
3741 // or more function templates and also to a set of overloaded non-template
3742 // functions. In such a case, the candidate functions generated from each
3743 // function template are combined with the set of non-template candidate
3744 // functions.
John McCall5769d612010-02-08 23:07:23 +00003745 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003746 FunctionDecl *Specialization = 0;
3747 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003748 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003749 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003750 CandidateSet.push_back(OverloadCandidate());
3751 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003752 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003753 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3754 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003755 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003756 Candidate.IsSurrogate = false;
3757 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003758 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3759 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003760 return;
3761 }
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Douglas Gregore53060f2009-06-25 22:08:12 +00003763 // Add the function template specialization produced by template argument
3764 // deduction as a candidate.
3765 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003766 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003767 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003768}
Mike Stump1eb44332009-09-09 15:08:12 +00003769
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003770/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003771/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003772/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003773/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003774/// (which may or may not be the same type as the type that the
3775/// conversion function produces).
3776void
3777Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003778 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003779 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003780 Expr *From, QualType ToType,
3781 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003782 assert(!Conversion->getDescribedFunctionTemplate() &&
3783 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003784 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003785 if (!CandidateSet.isNewCandidate(Conversion))
3786 return;
3787
Douglas Gregor7edfb692009-11-23 12:27:39 +00003788 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003789 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003790
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003791 // Add this candidate
3792 CandidateSet.push_back(OverloadCandidate());
3793 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003794 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003795 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003796 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003797 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003798 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003799 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003800 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003801 Candidate.Viable = true;
3802 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003803
Douglas Gregorbca39322010-08-19 15:37:02 +00003804 // C++ [over.match.funcs]p4:
3805 // For conversion functions, the function is considered to be a member of
3806 // the class of the implicit implied object argument for the purpose of
3807 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003808 //
3809 // Determine the implicit conversion sequence for the implicit
3810 // object parameter.
3811 QualType ImplicitParamType = From->getType();
3812 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3813 ImplicitParamType = FromPtrType->getPointeeType();
3814 CXXRecordDecl *ConversionContext
3815 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3816
3817 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003818 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003819 ConversionContext);
3820
John McCall1d318332010-01-12 00:44:57 +00003821 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003822 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003823 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003824 return;
3825 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003826
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003827 // We won't go through a user-define type conversion function to convert a
3828 // derived to base as such conversions are given Conversion Rank. They only
3829 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3830 QualType FromCanon
3831 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3832 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3833 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3834 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003835 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003836 return;
3837 }
3838
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003839 // To determine what the conversion from the result of calling the
3840 // conversion function to the type we're eventually trying to
3841 // convert to (ToType), we need to synthesize a call to the
3842 // conversion function and attempt copy initialization from it. This
3843 // makes sure that we get the right semantics with respect to
3844 // lvalues/rvalues and the type. Fortunately, we can allocate this
3845 // call on the stack and we don't need its arguments to be
3846 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003847 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003848 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003849 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3850 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00003851 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00003852 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003853
3854 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003855 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3856 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003857 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003858 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003859 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003860 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003861 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003862 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003863 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003864
John McCall1d318332010-01-12 00:44:57 +00003865 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003866 case ImplicitConversionSequence::StandardConversion:
3867 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003868
3869 // C++ [over.ics.user]p3:
3870 // If the user-defined conversion is specified by a specialization of a
3871 // conversion function template, the second standard conversion sequence
3872 // shall have exact match rank.
3873 if (Conversion->getPrimaryTemplate() &&
3874 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3875 Candidate.Viable = false;
3876 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3877 }
3878
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003879 break;
3880
3881 case ImplicitConversionSequence::BadConversion:
3882 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003883 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003884 break;
3885
3886 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003887 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003888 "Can only end up with a standard conversion sequence or failure");
3889 }
3890}
3891
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003892/// \brief Adds a conversion function template specialization
3893/// candidate to the overload set, using template argument deduction
3894/// to deduce the template arguments of the conversion function
3895/// template from the type that we are converting to (C++
3896/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003897void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003898Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003899 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003900 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003901 Expr *From, QualType ToType,
3902 OverloadCandidateSet &CandidateSet) {
3903 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3904 "Only conversion function templates permitted here");
3905
Douglas Gregor3f396022009-09-28 04:47:19 +00003906 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3907 return;
3908
John McCall5769d612010-02-08 23:07:23 +00003909 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003910 CXXConversionDecl *Specialization = 0;
3911 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003912 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003913 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003914 CandidateSet.push_back(OverloadCandidate());
3915 OverloadCandidate &Candidate = CandidateSet.back();
3916 Candidate.FoundDecl = FoundDecl;
3917 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3918 Candidate.Viable = false;
3919 Candidate.FailureKind = ovl_fail_bad_deduction;
3920 Candidate.IsSurrogate = false;
3921 Candidate.IgnoreObjectArgument = false;
3922 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3923 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003924 return;
3925 }
Mike Stump1eb44332009-09-09 15:08:12 +00003926
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003927 // Add the conversion function template specialization produced by
3928 // template argument deduction as a candidate.
3929 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003930 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003931 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003932}
3933
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003934/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3935/// converts the given @c Object to a function pointer via the
3936/// conversion function @c Conversion, and then attempts to call it
3937/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3938/// the type of function that we'll eventually be calling.
3939void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003940 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003941 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003942 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003943 QualType ObjectType,
3944 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003945 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003946 if (!CandidateSet.isNewCandidate(Conversion))
3947 return;
3948
Douglas Gregor7edfb692009-11-23 12:27:39 +00003949 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003950 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003951
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003952 CandidateSet.push_back(OverloadCandidate());
3953 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003954 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003955 Candidate.Function = 0;
3956 Candidate.Surrogate = Conversion;
3957 Candidate.Viable = true;
3958 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003959 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003960 Candidate.Conversions.resize(NumArgs + 1);
3961
3962 // Determine the implicit conversion sequence for the implicit
3963 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003964 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00003965 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3966 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003967 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003968 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003969 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003970 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003971 return;
3972 }
3973
3974 // The first conversion is actually a user-defined conversion whose
3975 // first conversion is ObjectInit's standard conversion (which is
3976 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003977 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003978 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003979 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003980 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003981 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003982 = Candidate.Conversions[0].UserDefined.Before;
3983 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3984
Mike Stump1eb44332009-09-09 15:08:12 +00003985 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003986 unsigned NumArgsInProto = Proto->getNumArgs();
3987
3988 // (C++ 13.3.2p2): A candidate function having fewer than m
3989 // parameters is viable only if it has an ellipsis in its parameter
3990 // list (8.3.5).
3991 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3992 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003993 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003994 return;
3995 }
3996
3997 // Function types don't have any default arguments, so just check if
3998 // we have enough arguments.
3999 if (NumArgs < NumArgsInProto) {
4000 // Not enough arguments.
4001 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004002 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004003 return;
4004 }
4005
4006 // Determine the implicit conversion sequences for each of the
4007 // arguments.
4008 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4009 if (ArgIdx < NumArgsInProto) {
4010 // (C++ 13.3.2p3): for F to be a viable function, there shall
4011 // exist for each argument an implicit conversion sequence
4012 // (13.3.3.1) that converts that argument to the corresponding
4013 // parameter of F.
4014 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004015 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004016 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004017 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004018 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004019 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004020 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004021 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004022 break;
4023 }
4024 } else {
4025 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4026 // argument for which there is no corresponding parameter is
4027 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004028 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004029 }
4030 }
4031}
4032
Douglas Gregor063daf62009-03-13 18:40:31 +00004033/// \brief Add overload candidates for overloaded operators that are
4034/// member functions.
4035///
4036/// Add the overloaded operator candidates that are member functions
4037/// for the operator Op that was used in an operator expression such
4038/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4039/// CandidateSet will store the added overload candidates. (C++
4040/// [over.match.oper]).
4041void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4042 SourceLocation OpLoc,
4043 Expr **Args, unsigned NumArgs,
4044 OverloadCandidateSet& CandidateSet,
4045 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004046 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4047
4048 // C++ [over.match.oper]p3:
4049 // For a unary operator @ with an operand of a type whose
4050 // cv-unqualified version is T1, and for a binary operator @ with
4051 // a left operand of a type whose cv-unqualified version is T1 and
4052 // a right operand of a type whose cv-unqualified version is T2,
4053 // three sets of candidate functions, designated member
4054 // candidates, non-member candidates and built-in candidates, are
4055 // constructed as follows:
4056 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004057
4058 // -- If T1 is a class type, the set of member candidates is the
4059 // result of the qualified lookup of T1::operator@
4060 // (13.3.1.1.1); otherwise, the set of member candidates is
4061 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004062 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004063 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004064 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004065 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004066
John McCalla24dc2e2009-11-17 02:14:36 +00004067 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4068 LookupQualifiedName(Operators, T1Rec->getDecl());
4069 Operators.suppressDiagnostics();
4070
Mike Stump1eb44332009-09-09 15:08:12 +00004071 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004072 OperEnd = Operators.end();
4073 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004074 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004075 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004076 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004077 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004078 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004079}
4080
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004081/// AddBuiltinCandidate - Add a candidate for a built-in
4082/// operator. ResultTy and ParamTys are the result and parameter types
4083/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004084/// arguments being passed to the candidate. IsAssignmentOperator
4085/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004086/// operator. NumContextualBoolArguments is the number of arguments
4087/// (at the beginning of the argument list) that will be contextually
4088/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004089void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004090 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004091 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004092 bool IsAssignmentOperator,
4093 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004094 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004095 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004096
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004097 // Add this candidate
4098 CandidateSet.push_back(OverloadCandidate());
4099 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004100 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004101 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004102 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004103 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004104 Candidate.BuiltinTypes.ResultTy = ResultTy;
4105 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4106 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4107
4108 // Determine the implicit conversion sequences for each of the
4109 // arguments.
4110 Candidate.Viable = true;
4111 Candidate.Conversions.resize(NumArgs);
4112 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004113 // C++ [over.match.oper]p4:
4114 // For the built-in assignment operators, conversions of the
4115 // left operand are restricted as follows:
4116 // -- no temporaries are introduced to hold the left operand, and
4117 // -- no user-defined conversions are applied to the left
4118 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004119 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004120 //
4121 // We block these conversions by turning off user-defined
4122 // conversions, since that is the only way that initialization of
4123 // a reference to a non-class type can occur from something that
4124 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004125 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004126 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004127 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004128 Candidate.Conversions[ArgIdx]
4129 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004130 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004131 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004132 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004133 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004134 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004135 }
John McCall1d318332010-01-12 00:44:57 +00004136 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004137 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004138 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004139 break;
4140 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004141 }
4142}
4143
4144/// BuiltinCandidateTypeSet - A set of types that will be used for the
4145/// candidate operator functions for built-in operators (C++
4146/// [over.built]). The types are separated into pointer types and
4147/// enumeration types.
4148class BuiltinCandidateTypeSet {
4149 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004150 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004151
4152 /// PointerTypes - The set of pointer types that will be used in the
4153 /// built-in candidates.
4154 TypeSet PointerTypes;
4155
Sebastian Redl78eb8742009-04-19 21:53:20 +00004156 /// MemberPointerTypes - The set of member pointer types that will be
4157 /// used in the built-in candidates.
4158 TypeSet MemberPointerTypes;
4159
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004160 /// EnumerationTypes - The set of enumeration types that will be
4161 /// used in the built-in candidates.
4162 TypeSet EnumerationTypes;
4163
Douglas Gregor26bcf672010-05-19 03:21:00 +00004164 /// \brief The set of vector types that will be used in the built-in
4165 /// candidates.
4166 TypeSet VectorTypes;
4167
Douglas Gregor5842ba92009-08-24 15:23:48 +00004168 /// Sema - The semantic analysis instance where we are building the
4169 /// candidate type set.
4170 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004171
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004172 /// Context - The AST context in which we will build the type sets.
4173 ASTContext &Context;
4174
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004175 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4176 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004177 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004178
4179public:
4180 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004181 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004182
Mike Stump1eb44332009-09-09 15:08:12 +00004183 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004184 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004185
Douglas Gregor573d9c32009-10-21 23:19:44 +00004186 void AddTypesConvertedFrom(QualType Ty,
4187 SourceLocation Loc,
4188 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004189 bool AllowExplicitConversions,
4190 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004191
4192 /// pointer_begin - First pointer type found;
4193 iterator pointer_begin() { return PointerTypes.begin(); }
4194
Sebastian Redl78eb8742009-04-19 21:53:20 +00004195 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004196 iterator pointer_end() { return PointerTypes.end(); }
4197
Sebastian Redl78eb8742009-04-19 21:53:20 +00004198 /// member_pointer_begin - First member pointer type found;
4199 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4200
4201 /// member_pointer_end - Past the last member pointer type found;
4202 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4203
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004204 /// enumeration_begin - First enumeration type found;
4205 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4206
Sebastian Redl78eb8742009-04-19 21:53:20 +00004207 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004208 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004209
4210 iterator vector_begin() { return VectorTypes.begin(); }
4211 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004212};
4213
Sebastian Redl78eb8742009-04-19 21:53:20 +00004214/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004215/// the set of pointer types along with any more-qualified variants of
4216/// that type. For example, if @p Ty is "int const *", this routine
4217/// will add "int const *", "int const volatile *", "int const
4218/// restrict *", and "int const volatile restrict *" to the set of
4219/// pointer types. Returns true if the add of @p Ty itself succeeded,
4220/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004221///
4222/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004223bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004224BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4225 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004226
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004227 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004228 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004229 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004230
4231 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004232 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004233 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004234 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004235 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004236 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004237 buildObjCPtr = true;
4238 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004239 else
4240 assert(false && "type was not a pointer type!");
4241 }
4242 else
4243 PointeeTy = PointerTy->getPointeeType();
4244
Sebastian Redla9efada2009-11-18 20:39:26 +00004245 // Don't add qualified variants of arrays. For one, they're not allowed
4246 // (the qualifier would sink to the element type), and for another, the
4247 // only overload situation where it matters is subscript or pointer +- int,
4248 // and those shouldn't have qualifier variants anyway.
4249 if (PointeeTy->isArrayType())
4250 return true;
John McCall0953e762009-09-24 19:53:00 +00004251 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004252 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004253 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004254 bool hasVolatile = VisibleQuals.hasVolatile();
4255 bool hasRestrict = VisibleQuals.hasRestrict();
4256
John McCall0953e762009-09-24 19:53:00 +00004257 // Iterate through all strict supersets of BaseCVR.
4258 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4259 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004260 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4261 // in the types.
4262 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4263 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004264 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004265 if (!buildObjCPtr)
4266 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4267 else
4268 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004269 }
4270
4271 return true;
4272}
4273
Sebastian Redl78eb8742009-04-19 21:53:20 +00004274/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4275/// to the set of pointer types along with any more-qualified variants of
4276/// that type. For example, if @p Ty is "int const *", this routine
4277/// will add "int const *", "int const volatile *", "int const
4278/// restrict *", and "int const volatile restrict *" to the set of
4279/// pointer types. Returns true if the add of @p Ty itself succeeded,
4280/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004281///
4282/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004283bool
4284BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4285 QualType Ty) {
4286 // Insert this type.
4287 if (!MemberPointerTypes.insert(Ty))
4288 return false;
4289
John McCall0953e762009-09-24 19:53:00 +00004290 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4291 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004292
John McCall0953e762009-09-24 19:53:00 +00004293 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004294 // Don't add qualified variants of arrays. For one, they're not allowed
4295 // (the qualifier would sink to the element type), and for another, the
4296 // only overload situation where it matters is subscript or pointer +- int,
4297 // and those shouldn't have qualifier variants anyway.
4298 if (PointeeTy->isArrayType())
4299 return true;
John McCall0953e762009-09-24 19:53:00 +00004300 const Type *ClassTy = PointerTy->getClass();
4301
4302 // Iterate through all strict supersets of the pointee type's CVR
4303 // qualifiers.
4304 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4305 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4306 if ((CVR | BaseCVR) != CVR) continue;
4307
4308 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4309 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004310 }
4311
4312 return true;
4313}
4314
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004315/// AddTypesConvertedFrom - Add each of the types to which the type @p
4316/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004317/// primarily interested in pointer types and enumeration types. We also
4318/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004319/// AllowUserConversions is true if we should look at the conversion
4320/// functions of a class type, and AllowExplicitConversions if we
4321/// should also include the explicit conversion functions of a class
4322/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004323void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004324BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004325 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004326 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004327 bool AllowExplicitConversions,
4328 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004329 // Only deal with canonical types.
4330 Ty = Context.getCanonicalType(Ty);
4331
4332 // Look through reference types; they aren't part of the type of an
4333 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004334 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004335 Ty = RefTy->getPointeeType();
4336
4337 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004338 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004339
Sebastian Redla65b5512009-11-05 16:36:20 +00004340 // If we're dealing with an array type, decay to the pointer.
4341 if (Ty->isArrayType())
4342 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004343 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4344 PointerTypes.insert(Ty);
4345 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004346 // Insert our type, and its more-qualified variants, into the set
4347 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004348 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004349 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004350 } else if (Ty->isMemberPointerType()) {
4351 // Member pointers are far easier, since the pointee can't be converted.
4352 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4353 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004354 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004355 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004356 } else if (Ty->isVectorType()) {
4357 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004358 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004359 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004360 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004361 // No conversion functions in incomplete types.
4362 return;
4363 }
Mike Stump1eb44332009-09-09 15:08:12 +00004364
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004365 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004366 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004367 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004368 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004369 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004370 NamedDecl *D = I.getDecl();
4371 if (isa<UsingShadowDecl>(D))
4372 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004373
Mike Stump1eb44332009-09-09 15:08:12 +00004374 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004375 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004376 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004377 continue;
4378
John McCall32daa422010-03-31 01:36:47 +00004379 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004380 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004381 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004382 VisibleQuals);
4383 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004384 }
4385 }
4386 }
4387}
4388
Douglas Gregor19b7b152009-08-24 13:43:27 +00004389/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4390/// the volatile- and non-volatile-qualified assignment operators for the
4391/// given type to the candidate set.
4392static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4393 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004394 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004395 unsigned NumArgs,
4396 OverloadCandidateSet &CandidateSet) {
4397 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004398
Douglas Gregor19b7b152009-08-24 13:43:27 +00004399 // T& operator=(T&, T)
4400 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4401 ParamTypes[1] = T;
4402 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4403 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004404
Douglas Gregor19b7b152009-08-24 13:43:27 +00004405 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4406 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004407 ParamTypes[0]
4408 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004409 ParamTypes[1] = T;
4410 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004411 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004412 }
4413}
Mike Stump1eb44332009-09-09 15:08:12 +00004414
Sebastian Redl9994a342009-10-25 17:03:50 +00004415/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4416/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004417static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4418 Qualifiers VRQuals;
4419 const RecordType *TyRec;
4420 if (const MemberPointerType *RHSMPType =
4421 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004422 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004423 else
4424 TyRec = ArgExpr->getType()->getAs<RecordType>();
4425 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004426 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004427 VRQuals.addVolatile();
4428 VRQuals.addRestrict();
4429 return VRQuals;
4430 }
4431
4432 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004433 if (!ClassDecl->hasDefinition())
4434 return VRQuals;
4435
John McCalleec51cf2010-01-20 00:46:10 +00004436 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004437 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004438
John McCalleec51cf2010-01-20 00:46:10 +00004439 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004440 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004441 NamedDecl *D = I.getDecl();
4442 if (isa<UsingShadowDecl>(D))
4443 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4444 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004445 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4446 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4447 CanTy = ResTypeRef->getPointeeType();
4448 // Need to go down the pointer/mempointer chain and add qualifiers
4449 // as see them.
4450 bool done = false;
4451 while (!done) {
4452 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4453 CanTy = ResTypePtr->getPointeeType();
4454 else if (const MemberPointerType *ResTypeMPtr =
4455 CanTy->getAs<MemberPointerType>())
4456 CanTy = ResTypeMPtr->getPointeeType();
4457 else
4458 done = true;
4459 if (CanTy.isVolatileQualified())
4460 VRQuals.addVolatile();
4461 if (CanTy.isRestrictQualified())
4462 VRQuals.addRestrict();
4463 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4464 return VRQuals;
4465 }
4466 }
4467 }
4468 return VRQuals;
4469}
4470
Douglas Gregor74253732008-11-19 15:42:04 +00004471/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4472/// operator overloads to the candidate set (C++ [over.built]), based
4473/// on the operator @p Op and the arguments given. For example, if the
4474/// operator is a binary '+', this routine might add "int
4475/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004476void
Mike Stump1eb44332009-09-09 15:08:12 +00004477Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004478 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004479 Expr **Args, unsigned NumArgs,
4480 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004481 // The set of "promoted arithmetic types", which are the arithmetic
4482 // types are that preserved by promotion (C++ [over.built]p2). Note
4483 // that the first few of these types are the promoted integral
4484 // types; these types need to be first.
4485 // FIXME: What about complex?
4486 const unsigned FirstIntegralType = 0;
4487 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004488 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004489 LastPromotedIntegralType = 13;
4490 const unsigned FirstPromotedArithmeticType = 7,
4491 LastPromotedArithmeticType = 16;
4492 const unsigned NumArithmeticTypes = 16;
4493 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004494 Context.BoolTy, Context.CharTy, Context.WCharTy,
4495// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004496 Context.SignedCharTy, Context.ShortTy,
4497 Context.UnsignedCharTy, Context.UnsignedShortTy,
4498 Context.IntTy, Context.LongTy, Context.LongLongTy,
4499 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4500 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4501 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004502 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4503 "Invalid first promoted integral type");
4504 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4505 == Context.UnsignedLongLongTy &&
4506 "Invalid last promoted integral type");
4507 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4508 "Invalid first promoted arithmetic type");
4509 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4510 == Context.LongDoubleTy &&
4511 "Invalid last promoted arithmetic type");
4512
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004513 // Find all of the types that the arguments can convert to, but only
4514 // if the operator we're looking at has built-in operator candidates
4515 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004516 Qualifiers VisibleTypeConversionsQuals;
4517 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004518 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4519 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4520
Douglas Gregor5842ba92009-08-24 15:23:48 +00004521 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004522 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4523 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4524 OpLoc,
4525 true,
4526 (Op == OO_Exclaim ||
4527 Op == OO_AmpAmp ||
4528 Op == OO_PipePipe),
4529 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004530
Douglas Gregor661b4932010-09-12 04:28:07 +00004531 // C++ [over.built]p1:
4532 // If there is a user-written candidate with the same name and parameter
4533 // types as a built-in candidate operator function, the built-in operator
4534 // function is hidden and is not included in the set of candidate functions.
4535 //
4536 // The text is actually in a note, but if we don't implement it then we end
4537 // up with ambiguities when the user provides an overloaded operator for
4538 // an enumeration type. Note that only enumeration types have this problem,
4539 // so we track which enumeration types we've seen operators for.
4540 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4541 UserDefinedBinaryOperators;
4542
4543 if (CandidateTypes.enumeration_begin() != CandidateTypes.enumeration_end()) {
4544 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4545 CEnd = CandidateSet.end();
4546 C != CEnd; ++C) {
4547 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4548 continue;
4549
4550 // Check if the first parameter is of enumeration type.
4551 QualType FirstParamType
4552 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4553 if (!FirstParamType->isEnumeralType())
4554 continue;
4555
4556 // Check if the second parameter is of enumeration type.
4557 QualType SecondParamType
4558 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4559 if (!SecondParamType->isEnumeralType())
4560 continue;
4561
4562 // Add this operator to the set of known user-defined operators.
4563 UserDefinedBinaryOperators.insert(
4564 std::make_pair(Context.getCanonicalType(FirstParamType),
4565 Context.getCanonicalType(SecondParamType)));
4566 }
4567 }
4568
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004569 bool isComparison = false;
4570 switch (Op) {
4571 case OO_None:
4572 case NUM_OVERLOADED_OPERATORS:
4573 assert(false && "Expected an overloaded operator");
4574 break;
4575
Douglas Gregor74253732008-11-19 15:42:04 +00004576 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004577 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004578 goto UnaryStar;
4579 else
4580 goto BinaryStar;
4581 break;
4582
4583 case OO_Plus: // '+' is either unary or binary
4584 if (NumArgs == 1)
4585 goto UnaryPlus;
4586 else
4587 goto BinaryPlus;
4588 break;
4589
4590 case OO_Minus: // '-' is either unary or binary
4591 if (NumArgs == 1)
4592 goto UnaryMinus;
4593 else
4594 goto BinaryMinus;
4595 break;
4596
4597 case OO_Amp: // '&' is either unary or binary
4598 if (NumArgs == 1)
4599 goto UnaryAmp;
4600 else
4601 goto BinaryAmp;
4602
4603 case OO_PlusPlus:
4604 case OO_MinusMinus:
4605 // C++ [over.built]p3:
4606 //
4607 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4608 // is either volatile or empty, there exist candidate operator
4609 // functions of the form
4610 //
4611 // VQ T& operator++(VQ T&);
4612 // T operator++(VQ T&, int);
4613 //
4614 // C++ [over.built]p4:
4615 //
4616 // For every pair (T, VQ), where T is an arithmetic type other
4617 // than bool, and VQ is either volatile or empty, there exist
4618 // candidate operator functions of the form
4619 //
4620 // VQ T& operator--(VQ T&);
4621 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004622 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004623 Arith < NumArithmeticTypes; ++Arith) {
4624 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004625 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004626 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004627
4628 // Non-volatile version.
4629 if (NumArgs == 1)
4630 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4631 else
4632 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004633 // heuristic to reduce number of builtin candidates in the set.
4634 // Add volatile version only if there are conversions to a volatile type.
4635 if (VisibleTypeConversionsQuals.hasVolatile()) {
4636 // Volatile version
4637 ParamTypes[0]
4638 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4639 if (NumArgs == 1)
4640 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4641 else
4642 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4643 }
Douglas Gregor74253732008-11-19 15:42:04 +00004644 }
4645
4646 // C++ [over.built]p5:
4647 //
4648 // For every pair (T, VQ), where T is a cv-qualified or
4649 // cv-unqualified object type, and VQ is either volatile or
4650 // empty, there exist candidate operator functions of the form
4651 //
4652 // T*VQ& operator++(T*VQ&);
4653 // T*VQ& operator--(T*VQ&);
4654 // T* operator++(T*VQ&, int);
4655 // T* operator--(T*VQ&, int);
4656 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4657 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4658 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004659 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004660 continue;
4661
Mike Stump1eb44332009-09-09 15:08:12 +00004662 QualType ParamTypes[2] = {
4663 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004664 };
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Douglas Gregor74253732008-11-19 15:42:04 +00004666 // Without volatile
4667 if (NumArgs == 1)
4668 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4669 else
4670 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4671
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004672 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4673 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004674 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004675 ParamTypes[0]
4676 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004677 if (NumArgs == 1)
4678 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4679 else
4680 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4681 }
4682 }
4683 break;
4684
4685 UnaryStar:
4686 // C++ [over.built]p6:
4687 // For every cv-qualified or cv-unqualified object type T, there
4688 // exist candidate operator functions of the form
4689 //
4690 // T& operator*(T*);
4691 //
4692 // C++ [over.built]p7:
4693 // For every function type T, there exist candidate operator
4694 // functions of the form
4695 // T& operator*(T*);
4696 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4697 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4698 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00004699 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004700 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004701 &ParamTy, Args, 1, CandidateSet);
4702 }
4703 break;
4704
4705 UnaryPlus:
4706 // C++ [over.built]p8:
4707 // For every type T, there exist candidate operator functions of
4708 // the form
4709 //
4710 // T* operator+(T*);
4711 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4712 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4713 QualType ParamTy = *Ptr;
4714 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4715 }
Mike Stump1eb44332009-09-09 15:08:12 +00004716
Douglas Gregor74253732008-11-19 15:42:04 +00004717 // Fall through
4718
4719 UnaryMinus:
4720 // C++ [over.built]p9:
4721 // For every promoted arithmetic type T, there exist candidate
4722 // operator functions of the form
4723 //
4724 // T operator+(T);
4725 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004726 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004727 Arith < LastPromotedArithmeticType; ++Arith) {
4728 QualType ArithTy = ArithmeticTypes[Arith];
4729 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4730 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004731
4732 // Extension: We also add these operators for vector types.
4733 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4734 VecEnd = CandidateTypes.vector_end();
4735 Vec != VecEnd; ++Vec) {
4736 QualType VecTy = *Vec;
4737 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4738 }
Douglas Gregor74253732008-11-19 15:42:04 +00004739 break;
4740
4741 case OO_Tilde:
4742 // C++ [over.built]p10:
4743 // For every promoted integral type T, there exist candidate
4744 // operator functions of the form
4745 //
4746 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004747 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004748 Int < LastPromotedIntegralType; ++Int) {
4749 QualType IntTy = ArithmeticTypes[Int];
4750 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4751 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004752
4753 // Extension: We also add this operator for vector types.
4754 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4755 VecEnd = CandidateTypes.vector_end();
4756 Vec != VecEnd; ++Vec) {
4757 QualType VecTy = *Vec;
4758 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4759 }
Douglas Gregor74253732008-11-19 15:42:04 +00004760 break;
4761
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004762 case OO_New:
4763 case OO_Delete:
4764 case OO_Array_New:
4765 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004766 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004767 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004768 break;
4769
4770 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004771 UnaryAmp:
4772 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004773 // C++ [over.match.oper]p3:
4774 // -- For the operator ',', the unary operator '&', or the
4775 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004776 break;
4777
Douglas Gregor19b7b152009-08-24 13:43:27 +00004778 case OO_EqualEqual:
4779 case OO_ExclaimEqual:
4780 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004781 // For every pointer to member type T, there exist candidate operator
4782 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004783 //
4784 // bool operator==(T,T);
4785 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004786 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004787 MemPtr = CandidateTypes.member_pointer_begin(),
4788 MemPtrEnd = CandidateTypes.member_pointer_end();
4789 MemPtr != MemPtrEnd;
4790 ++MemPtr) {
4791 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4792 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4793 }
Mike Stump1eb44332009-09-09 15:08:12 +00004794
Douglas Gregor19b7b152009-08-24 13:43:27 +00004795 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004796
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004797 case OO_Less:
4798 case OO_Greater:
4799 case OO_LessEqual:
4800 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004801 // C++ [over.built]p15:
4802 //
4803 // For every pointer or enumeration type T, there exist
4804 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004805 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004806 // bool operator<(T, T);
4807 // bool operator>(T, T);
4808 // bool operator<=(T, T);
4809 // bool operator>=(T, T);
4810 // bool operator==(T, T);
4811 // bool operator!=(T, T);
4812 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4813 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4814 QualType ParamTypes[2] = { *Ptr, *Ptr };
4815 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4816 }
Mike Stump1eb44332009-09-09 15:08:12 +00004817 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004818 = CandidateTypes.enumeration_begin();
4819 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4820 QualType ParamTypes[2] = { *Enum, *Enum };
Douglas Gregor661b4932010-09-12 04:28:07 +00004821 CanQualType CanonType = Context.getCanonicalType(*Enum);
4822 if (!UserDefinedBinaryOperators.count(
4823 std::make_pair(CanonType, CanonType)))
4824 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004825 }
4826
4827 // Fall through.
4828 isComparison = true;
4829
Douglas Gregor74253732008-11-19 15:42:04 +00004830 BinaryPlus:
4831 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004832 if (!isComparison) {
4833 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4834
4835 // C++ [over.built]p13:
4836 //
4837 // For every cv-qualified or cv-unqualified object type T
4838 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004839 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004840 // T* operator+(T*, ptrdiff_t);
4841 // T& operator[](T*, ptrdiff_t); [BELOW]
4842 // T* operator-(T*, ptrdiff_t);
4843 // T* operator+(ptrdiff_t, T*);
4844 // T& operator[](ptrdiff_t, T*); [BELOW]
4845 //
4846 // C++ [over.built]p14:
4847 //
4848 // For every T, where T is a pointer to object type, there
4849 // exist candidate operator functions of the form
4850 //
4851 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004852 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004853 = CandidateTypes.pointer_begin();
4854 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4855 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4856
4857 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4858 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4859
4860 if (Op == OO_Plus) {
4861 // T* operator+(ptrdiff_t, T*);
4862 ParamTypes[0] = ParamTypes[1];
4863 ParamTypes[1] = *Ptr;
4864 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4865 } else {
4866 // ptrdiff_t operator-(T, T);
4867 ParamTypes[1] = *Ptr;
4868 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4869 Args, 2, CandidateSet);
4870 }
4871 }
4872 }
4873 // Fall through
4874
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004875 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004876 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004877 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004878 // C++ [over.built]p12:
4879 //
4880 // For every pair of promoted arithmetic types L and R, there
4881 // exist candidate operator functions of the form
4882 //
4883 // LR operator*(L, R);
4884 // LR operator/(L, R);
4885 // LR operator+(L, R);
4886 // LR operator-(L, R);
4887 // bool operator<(L, R);
4888 // bool operator>(L, R);
4889 // bool operator<=(L, R);
4890 // bool operator>=(L, R);
4891 // bool operator==(L, R);
4892 // bool operator!=(L, R);
4893 //
4894 // where LR is the result of the usual arithmetic conversions
4895 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004896 //
4897 // C++ [over.built]p24:
4898 //
4899 // For every pair of promoted arithmetic types L and R, there exist
4900 // candidate operator functions of the form
4901 //
4902 // LR operator?(bool, L, R);
4903 //
4904 // where LR is the result of the usual arithmetic conversions
4905 // between types L and R.
4906 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004907 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004908 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004909 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004910 Right < LastPromotedArithmeticType; ++Right) {
4911 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004912 QualType Result
4913 = isComparison
4914 ? Context.BoolTy
4915 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004916 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4917 }
4918 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004919
4920 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4921 // conditional operator for vector types.
4922 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4923 Vec1End = CandidateTypes.vector_end();
4924 Vec1 != Vec1End; ++Vec1)
4925 for (BuiltinCandidateTypeSet::iterator
4926 Vec2 = CandidateTypes.vector_begin(),
4927 Vec2End = CandidateTypes.vector_end();
4928 Vec2 != Vec2End; ++Vec2) {
4929 QualType LandR[2] = { *Vec1, *Vec2 };
4930 QualType Result;
4931 if (isComparison)
4932 Result = Context.BoolTy;
4933 else {
4934 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4935 Result = *Vec1;
4936 else
4937 Result = *Vec2;
4938 }
4939
4940 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4941 }
4942
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004943 break;
4944
4945 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004946 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004947 case OO_Caret:
4948 case OO_Pipe:
4949 case OO_LessLess:
4950 case OO_GreaterGreater:
4951 // C++ [over.built]p17:
4952 //
4953 // For every pair of promoted integral types L and R, there
4954 // exist candidate operator functions of the form
4955 //
4956 // LR operator%(L, R);
4957 // LR operator&(L, R);
4958 // LR operator^(L, R);
4959 // LR operator|(L, R);
4960 // L operator<<(L, R);
4961 // L operator>>(L, R);
4962 //
4963 // where LR is the result of the usual arithmetic conversions
4964 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004965 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004966 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004967 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004968 Right < LastPromotedIntegralType; ++Right) {
4969 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4970 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4971 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004972 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004973 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4974 }
4975 }
4976 break;
4977
4978 case OO_Equal:
4979 // C++ [over.built]p20:
4980 //
4981 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004982 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004983 // empty, there exist candidate operator functions of the form
4984 //
4985 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004986 for (BuiltinCandidateTypeSet::iterator
4987 Enum = CandidateTypes.enumeration_begin(),
4988 EnumEnd = CandidateTypes.enumeration_end();
4989 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004990 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004991 CandidateSet);
4992 for (BuiltinCandidateTypeSet::iterator
4993 MemPtr = CandidateTypes.member_pointer_begin(),
4994 MemPtrEnd = CandidateTypes.member_pointer_end();
4995 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004996 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004997 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004998
4999 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005000
5001 case OO_PlusEqual:
5002 case OO_MinusEqual:
5003 // C++ [over.built]p19:
5004 //
5005 // For every pair (T, VQ), where T is any type and VQ is either
5006 // volatile or empty, there exist candidate operator functions
5007 // of the form
5008 //
5009 // T*VQ& operator=(T*VQ&, T*);
5010 //
5011 // C++ [over.built]p21:
5012 //
5013 // For every pair (T, VQ), where T is a cv-qualified or
5014 // cv-unqualified object type and VQ is either volatile or
5015 // empty, there exist candidate operator functions of the form
5016 //
5017 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5018 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5019 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5020 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5021 QualType ParamTypes[2];
5022 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5023
5024 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005025 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005026 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5027 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005028
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005029 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5030 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00005031 // volatile version
John McCall0953e762009-09-24 19:53:00 +00005032 ParamTypes[0]
5033 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005034 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5035 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00005036 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005037 }
5038 // Fall through.
5039
5040 case OO_StarEqual:
5041 case OO_SlashEqual:
5042 // C++ [over.built]p18:
5043 //
5044 // For every triple (L, VQ, R), where L is an arithmetic type,
5045 // VQ is either volatile or empty, and R is a promoted
5046 // arithmetic type, there exist candidate operator functions of
5047 // the form
5048 //
5049 // VQ L& operator=(VQ L&, R);
5050 // VQ L& operator*=(VQ L&, R);
5051 // VQ L& operator/=(VQ L&, R);
5052 // VQ L& operator+=(VQ L&, R);
5053 // VQ L& operator-=(VQ L&, R);
5054 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005055 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005056 Right < LastPromotedArithmeticType; ++Right) {
5057 QualType ParamTypes[2];
5058 ParamTypes[1] = ArithmeticTypes[Right];
5059
5060 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005061 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005062 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5063 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005064
5065 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005066 if (VisibleTypeConversionsQuals.hasVolatile()) {
5067 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5068 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5069 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5070 /*IsAssigmentOperator=*/Op == OO_Equal);
5071 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005072 }
5073 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005074
5075 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5076 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
5077 Vec1End = CandidateTypes.vector_end();
5078 Vec1 != Vec1End; ++Vec1)
5079 for (BuiltinCandidateTypeSet::iterator
5080 Vec2 = CandidateTypes.vector_begin(),
5081 Vec2End = CandidateTypes.vector_end();
5082 Vec2 != Vec2End; ++Vec2) {
5083 QualType ParamTypes[2];
5084 ParamTypes[1] = *Vec2;
5085 // Add this built-in operator as a candidate (VQ is empty).
5086 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5087 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5088 /*IsAssigmentOperator=*/Op == OO_Equal);
5089
5090 // Add this built-in operator as a candidate (VQ is 'volatile').
5091 if (VisibleTypeConversionsQuals.hasVolatile()) {
5092 ParamTypes[0] = Context.getVolatileType(*Vec1);
5093 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5094 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5095 /*IsAssigmentOperator=*/Op == OO_Equal);
5096 }
5097 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005098 break;
5099
5100 case OO_PercentEqual:
5101 case OO_LessLessEqual:
5102 case OO_GreaterGreaterEqual:
5103 case OO_AmpEqual:
5104 case OO_CaretEqual:
5105 case OO_PipeEqual:
5106 // C++ [over.built]p22:
5107 //
5108 // For every triple (L, VQ, R), where L is an integral type, VQ
5109 // is either volatile or empty, and R is a promoted integral
5110 // type, there exist candidate operator functions of the form
5111 //
5112 // VQ L& operator%=(VQ L&, R);
5113 // VQ L& operator<<=(VQ L&, R);
5114 // VQ L& operator>>=(VQ L&, R);
5115 // VQ L& operator&=(VQ L&, R);
5116 // VQ L& operator^=(VQ L&, R);
5117 // VQ L& operator|=(VQ L&, R);
5118 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005119 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005120 Right < LastPromotedIntegralType; ++Right) {
5121 QualType ParamTypes[2];
5122 ParamTypes[1] = ArithmeticTypes[Right];
5123
5124 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005125 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005126 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005127 if (VisibleTypeConversionsQuals.hasVolatile()) {
5128 // Add this built-in operator as a candidate (VQ is 'volatile').
5129 ParamTypes[0] = ArithmeticTypes[Left];
5130 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5131 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5132 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5133 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005134 }
5135 }
5136 break;
5137
Douglas Gregor74253732008-11-19 15:42:04 +00005138 case OO_Exclaim: {
5139 // C++ [over.operator]p23:
5140 //
5141 // There also exist candidate operator functions of the form
5142 //
Mike Stump1eb44332009-09-09 15:08:12 +00005143 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005144 // bool operator&&(bool, bool); [BELOW]
5145 // bool operator||(bool, bool); [BELOW]
5146 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005147 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5148 /*IsAssignmentOperator=*/false,
5149 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005150 break;
5151 }
5152
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005153 case OO_AmpAmp:
5154 case OO_PipePipe: {
5155 // C++ [over.operator]p23:
5156 //
5157 // There also exist candidate operator functions of the form
5158 //
Douglas Gregor74253732008-11-19 15:42:04 +00005159 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005160 // bool operator&&(bool, bool);
5161 // bool operator||(bool, bool);
5162 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005163 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5164 /*IsAssignmentOperator=*/false,
5165 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005166 break;
5167 }
5168
5169 case OO_Subscript:
5170 // C++ [over.built]p13:
5171 //
5172 // For every cv-qualified or cv-unqualified object type T there
5173 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005174 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005175 // T* operator+(T*, ptrdiff_t); [ABOVE]
5176 // T& operator[](T*, ptrdiff_t);
5177 // T* operator-(T*, ptrdiff_t); [ABOVE]
5178 // T* operator+(ptrdiff_t, T*); [ABOVE]
5179 // T& operator[](ptrdiff_t, T*);
5180 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5181 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5182 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005183 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005184 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005185
5186 // T& operator[](T*, ptrdiff_t)
5187 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5188
5189 // T& operator[](ptrdiff_t, T*);
5190 ParamTypes[0] = ParamTypes[1];
5191 ParamTypes[1] = *Ptr;
5192 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005193 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005194 break;
5195
5196 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005197 // C++ [over.built]p11:
5198 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5199 // C1 is the same type as C2 or is a derived class of C2, T is an object
5200 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5201 // there exist candidate operator functions of the form
5202 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5203 // where CV12 is the union of CV1 and CV2.
5204 {
5205 for (BuiltinCandidateTypeSet::iterator Ptr =
5206 CandidateTypes.pointer_begin();
5207 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5208 QualType C1Ty = (*Ptr);
5209 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005210 QualifierCollector Q1;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005211 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5212 if (!isa<RecordType>(C1))
5213 continue;
5214 // heuristic to reduce number of builtin candidates in the set.
5215 // Add volatile/restrict version only if there are conversions to a
5216 // volatile/restrict type.
5217 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5218 continue;
5219 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5220 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005221 for (BuiltinCandidateTypeSet::iterator
5222 MemPtr = CandidateTypes.member_pointer_begin(),
5223 MemPtrEnd = CandidateTypes.member_pointer_end();
5224 MemPtr != MemPtrEnd; ++MemPtr) {
5225 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5226 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005227 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005228 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5229 break;
5230 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5231 // build CV12 T&
5232 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005233 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5234 T.isVolatileQualified())
5235 continue;
5236 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5237 T.isRestrictQualified())
5238 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005239 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005240 QualType ResultTy = Context.getLValueReferenceType(T);
5241 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5242 }
5243 }
5244 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005245 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005246
5247 case OO_Conditional:
5248 // Note that we don't consider the first argument, since it has been
5249 // contextually converted to bool long ago. The candidates below are
5250 // therefore added as binary.
5251 //
5252 // C++ [over.built]p24:
5253 // For every type T, where T is a pointer or pointer-to-member type,
5254 // there exist candidate operator functions of the form
5255 //
5256 // T operator?(bool, T, T);
5257 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005258 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5259 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5260 QualType ParamTypes[2] = { *Ptr, *Ptr };
5261 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5262 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00005263 for (BuiltinCandidateTypeSet::iterator Ptr =
5264 CandidateTypes.member_pointer_begin(),
5265 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5266 QualType ParamTypes[2] = { *Ptr, *Ptr };
5267 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5268 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005269 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005270 }
5271}
5272
Douglas Gregorfa047642009-02-04 00:32:51 +00005273/// \brief Add function candidates found via argument-dependent lookup
5274/// to the set of overloading candidates.
5275///
5276/// This routine performs argument-dependent name lookup based on the
5277/// given function name (which may also be an operator name) and adds
5278/// all of the overload candidates found by ADL to the overload
5279/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005280void
Douglas Gregorfa047642009-02-04 00:32:51 +00005281Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005282 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005283 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005284 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005285 OverloadCandidateSet& CandidateSet,
5286 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005287 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005288
John McCalla113e722010-01-26 06:04:06 +00005289 // FIXME: This approach for uniquing ADL results (and removing
5290 // redundant candidates from the set) relies on pointer-equality,
5291 // which means we need to key off the canonical decl. However,
5292 // always going back to the canonical decl might not get us the
5293 // right set of default arguments. What default arguments are
5294 // we supposed to consider on ADL candidates, anyway?
5295
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005296 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005297 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005298
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005299 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005300 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5301 CandEnd = CandidateSet.end();
5302 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005303 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005304 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005305 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005306 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005307 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005308
5309 // For each of the ADL candidates we found, add it to the overload
5310 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005311 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005312 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005313 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005314 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005315 continue;
5316
John McCall9aa472c2010-03-19 07:35:19 +00005317 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005318 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005319 } else
John McCall6e266892010-01-26 03:27:55 +00005320 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005321 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005322 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005323 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005324}
5325
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005326/// isBetterOverloadCandidate - Determines whether the first overload
5327/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005328bool
John McCall120d63c2010-08-24 20:38:10 +00005329isBetterOverloadCandidate(Sema &S,
5330 const OverloadCandidate& Cand1,
5331 const OverloadCandidate& Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005332 SourceLocation Loc,
5333 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005334 // Define viable functions to be better candidates than non-viable
5335 // functions.
5336 if (!Cand2.Viable)
5337 return Cand1.Viable;
5338 else if (!Cand1.Viable)
5339 return false;
5340
Douglas Gregor88a35142008-12-22 05:46:06 +00005341 // C++ [over.match.best]p1:
5342 //
5343 // -- if F is a static member function, ICS1(F) is defined such
5344 // that ICS1(F) is neither better nor worse than ICS1(G) for
5345 // any function G, and, symmetrically, ICS1(G) is neither
5346 // better nor worse than ICS1(F).
5347 unsigned StartArg = 0;
5348 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5349 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005350
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005351 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005352 // A viable function F1 is defined to be a better function than another
5353 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005354 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005355 unsigned NumArgs = Cand1.Conversions.size();
5356 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5357 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005358 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005359 switch (CompareImplicitConversionSequences(S,
5360 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005361 Cand2.Conversions[ArgIdx])) {
5362 case ImplicitConversionSequence::Better:
5363 // Cand1 has a better conversion sequence.
5364 HasBetterConversion = true;
5365 break;
5366
5367 case ImplicitConversionSequence::Worse:
5368 // Cand1 can't be better than Cand2.
5369 return false;
5370
5371 case ImplicitConversionSequence::Indistinguishable:
5372 // Do nothing.
5373 break;
5374 }
5375 }
5376
Mike Stump1eb44332009-09-09 15:08:12 +00005377 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005378 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005379 if (HasBetterConversion)
5380 return true;
5381
Mike Stump1eb44332009-09-09 15:08:12 +00005382 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005383 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005384 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005385 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5386 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005387
5388 // -- F1 and F2 are function template specializations, and the function
5389 // template for F1 is more specialized than the template for F2
5390 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005391 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005392 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5393 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005394 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005395 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5396 Cand2.Function->getPrimaryTemplate(),
5397 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005398 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5399 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005400 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005401
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005402 // -- the context is an initialization by user-defined conversion
5403 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5404 // from the return type of F1 to the destination type (i.e.,
5405 // the type of the entity being initialized) is a better
5406 // conversion sequence than the standard conversion sequence
5407 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005408 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005409 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005410 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005411 switch (CompareStandardConversionSequences(S,
5412 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005413 Cand2.FinalConversion)) {
5414 case ImplicitConversionSequence::Better:
5415 // Cand1 has a better conversion sequence.
5416 return true;
5417
5418 case ImplicitConversionSequence::Worse:
5419 // Cand1 can't be better than Cand2.
5420 return false;
5421
5422 case ImplicitConversionSequence::Indistinguishable:
5423 // Do nothing
5424 break;
5425 }
5426 }
5427
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005428 return false;
5429}
5430
Mike Stump1eb44332009-09-09 15:08:12 +00005431/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005432/// within an overload candidate set.
5433///
5434/// \param CandidateSet the set of candidate functions.
5435///
5436/// \param Loc the location of the function name (or operator symbol) for
5437/// which overload resolution occurs.
5438///
Mike Stump1eb44332009-09-09 15:08:12 +00005439/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005440/// function, Best points to the candidate function found.
5441///
5442/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005443OverloadingResult
5444OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005445 iterator& Best,
5446 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005447 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005448 Best = end();
5449 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5450 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005451 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5452 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005453 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005454 }
5455
5456 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005457 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005458 return OR_No_Viable_Function;
5459
5460 // Make sure that this function is better than every other viable
5461 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005462 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005463 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005464 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005465 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5466 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00005467 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005468 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005469 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005470 }
Mike Stump1eb44332009-09-09 15:08:12 +00005471
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005472 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005473 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005474 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005475 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005476 return OR_Deleted;
5477
Douglas Gregore0762c92009-06-19 23:52:42 +00005478 // C++ [basic.def.odr]p2:
5479 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005480 // when referred to from a potentially-evaluated expression. [Note: this
5481 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005482 // (clause 13), user-defined conversions (12.3.2), allocation function for
5483 // placement new (5.3.4), as well as non-default initialization (8.5).
5484 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005485 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005486 return OR_Success;
5487}
5488
John McCall3c80f572010-01-12 02:15:36 +00005489namespace {
5490
5491enum OverloadCandidateKind {
5492 oc_function,
5493 oc_method,
5494 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005495 oc_function_template,
5496 oc_method_template,
5497 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005498 oc_implicit_default_constructor,
5499 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005500 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005501};
5502
John McCall220ccbf2010-01-13 00:25:19 +00005503OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5504 FunctionDecl *Fn,
5505 std::string &Description) {
5506 bool isTemplate = false;
5507
5508 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5509 isTemplate = true;
5510 Description = S.getTemplateArgumentBindingsText(
5511 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5512 }
John McCallb1622a12010-01-06 09:43:14 +00005513
5514 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005515 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005516 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005517
John McCall3c80f572010-01-12 02:15:36 +00005518 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5519 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005520 }
5521
5522 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5523 // This actually gets spelled 'candidate function' for now, but
5524 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005525 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005526 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005527
5528 assert(Meth->isCopyAssignment()
5529 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005530 return oc_implicit_copy_assignment;
5531 }
5532
John McCall220ccbf2010-01-13 00:25:19 +00005533 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005534}
5535
5536} // end anonymous namespace
5537
5538// Notes the location of an overload candidate.
5539void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005540 std::string FnDesc;
5541 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5542 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5543 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005544}
5545
John McCall1d318332010-01-12 00:44:57 +00005546/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5547/// "lead" diagnostic; it will be given two arguments, the source and
5548/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00005549void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5550 Sema &S,
5551 SourceLocation CaretLoc,
5552 const PartialDiagnostic &PDiag) const {
5553 S.Diag(CaretLoc, PDiag)
5554 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00005555 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00005556 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5557 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00005558 }
John McCall81201622010-01-08 04:41:39 +00005559}
5560
John McCall1d318332010-01-12 00:44:57 +00005561namespace {
5562
John McCalladbb8f82010-01-13 09:16:55 +00005563void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5564 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5565 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005566 assert(Cand->Function && "for now, candidate must be a function");
5567 FunctionDecl *Fn = Cand->Function;
5568
5569 // There's a conversion slot for the object argument if this is a
5570 // non-constructor method. Note that 'I' corresponds the
5571 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005572 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005573 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005574 if (I == 0)
5575 isObjectArgument = true;
5576 else
5577 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005578 }
5579
John McCall220ccbf2010-01-13 00:25:19 +00005580 std::string FnDesc;
5581 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5582
John McCalladbb8f82010-01-13 09:16:55 +00005583 Expr *FromExpr = Conv.Bad.FromExpr;
5584 QualType FromTy = Conv.Bad.getFromType();
5585 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005586
John McCall5920dbb2010-02-02 02:42:52 +00005587 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005588 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005589 Expr *E = FromExpr->IgnoreParens();
5590 if (isa<UnaryOperator>(E))
5591 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005592 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005593
5594 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5595 << (unsigned) FnKind << FnDesc
5596 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5597 << ToTy << Name << I+1;
5598 return;
5599 }
5600
John McCall258b2032010-01-23 08:10:49 +00005601 // Do some hand-waving analysis to see if the non-viability is due
5602 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005603 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5604 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5605 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5606 CToTy = RT->getPointeeType();
5607 else {
5608 // TODO: detect and diagnose the full richness of const mismatches.
5609 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5610 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5611 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5612 }
5613
5614 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5615 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5616 // It is dumb that we have to do this here.
5617 while (isa<ArrayType>(CFromTy))
5618 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5619 while (isa<ArrayType>(CToTy))
5620 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5621
5622 Qualifiers FromQs = CFromTy.getQualifiers();
5623 Qualifiers ToQs = CToTy.getQualifiers();
5624
5625 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5626 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5627 << (unsigned) FnKind << FnDesc
5628 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5629 << FromTy
5630 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5631 << (unsigned) isObjectArgument << I+1;
5632 return;
5633 }
5634
5635 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5636 assert(CVR && "unexpected qualifiers mismatch");
5637
5638 if (isObjectArgument) {
5639 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5640 << (unsigned) FnKind << FnDesc
5641 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5642 << FromTy << (CVR - 1);
5643 } else {
5644 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5645 << (unsigned) FnKind << FnDesc
5646 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5647 << FromTy << (CVR - 1) << I+1;
5648 }
5649 return;
5650 }
5651
John McCall258b2032010-01-23 08:10:49 +00005652 // Diagnose references or pointers to incomplete types differently,
5653 // since it's far from impossible that the incompleteness triggered
5654 // the failure.
5655 QualType TempFromTy = FromTy.getNonReferenceType();
5656 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5657 TempFromTy = PTy->getPointeeType();
5658 if (TempFromTy->isIncompleteType()) {
5659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5660 << (unsigned) FnKind << FnDesc
5661 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5662 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5663 return;
5664 }
5665
Douglas Gregor85789812010-06-30 23:01:39 +00005666 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005667 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005668 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5669 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5670 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5671 FromPtrTy->getPointeeType()) &&
5672 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5673 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5674 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5675 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005676 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005677 }
5678 } else if (const ObjCObjectPointerType *FromPtrTy
5679 = FromTy->getAs<ObjCObjectPointerType>()) {
5680 if (const ObjCObjectPointerType *ToPtrTy
5681 = ToTy->getAs<ObjCObjectPointerType>())
5682 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5683 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5684 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5685 FromPtrTy->getPointeeType()) &&
5686 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005687 BaseToDerivedConversion = 2;
5688 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5689 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5690 !FromTy->isIncompleteType() &&
5691 !ToRefTy->getPointeeType()->isIncompleteType() &&
5692 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5693 BaseToDerivedConversion = 3;
5694 }
5695
5696 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005697 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005698 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005699 << (unsigned) FnKind << FnDesc
5700 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005701 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005702 << FromTy << ToTy << I+1;
5703 return;
5704 }
5705
John McCall651f3ee2010-01-14 03:28:57 +00005706 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5708 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005709 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005710 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005711}
5712
5713void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5714 unsigned NumFormalArgs) {
5715 // TODO: treat calls to a missing default constructor as a special case
5716
5717 FunctionDecl *Fn = Cand->Function;
5718 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5719
5720 unsigned MinParams = Fn->getMinRequiredArguments();
5721
5722 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005723 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005724 unsigned mode, modeCount;
5725 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005726 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5727 (Cand->FailureKind == ovl_fail_bad_deduction &&
5728 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005729 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5730 mode = 0; // "at least"
5731 else
5732 mode = 2; // "exactly"
5733 modeCount = MinParams;
5734 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005735 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5736 (Cand->FailureKind == ovl_fail_bad_deduction &&
5737 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005738 if (MinParams != FnTy->getNumArgs())
5739 mode = 1; // "at most"
5740 else
5741 mode = 2; // "exactly"
5742 modeCount = FnTy->getNumArgs();
5743 }
5744
5745 std::string Description;
5746 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5747
5748 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005749 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5750 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005751}
5752
John McCall342fec42010-02-01 18:53:26 +00005753/// Diagnose a failed template-argument deduction.
5754void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5755 Expr **Args, unsigned NumArgs) {
5756 FunctionDecl *Fn = Cand->Function; // pattern
5757
Douglas Gregora9333192010-05-08 17:41:32 +00005758 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005759 NamedDecl *ParamD;
5760 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5761 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5762 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005763 switch (Cand->DeductionFailure.Result) {
5764 case Sema::TDK_Success:
5765 llvm_unreachable("TDK_success while diagnosing bad deduction");
5766
5767 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005768 assert(ParamD && "no parameter found for incomplete deduction result");
5769 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5770 << ParamD->getDeclName();
5771 return;
5772 }
5773
John McCall57e97782010-08-05 09:05:08 +00005774 case Sema::TDK_Underqualified: {
5775 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5776 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5777
5778 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5779
5780 // Param will have been canonicalized, but it should just be a
5781 // qualified version of ParamD, so move the qualifiers to that.
5782 QualifierCollector Qs(S.Context);
5783 Qs.strip(Param);
5784 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5785 assert(S.Context.hasSameType(Param, NonCanonParam));
5786
5787 // Arg has also been canonicalized, but there's nothing we can do
5788 // about that. It also doesn't matter as much, because it won't
5789 // have any template parameters in it (because deduction isn't
5790 // done on dependent types).
5791 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5792
5793 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5794 << ParamD->getDeclName() << Arg << NonCanonParam;
5795 return;
5796 }
5797
5798 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005799 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005800 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005801 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005802 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005803 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005804 which = 1;
5805 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005806 which = 2;
5807 }
5808
5809 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5810 << which << ParamD->getDeclName()
5811 << *Cand->DeductionFailure.getFirstArg()
5812 << *Cand->DeductionFailure.getSecondArg();
5813 return;
5814 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005815
Douglas Gregorf1a84452010-05-08 19:15:54 +00005816 case Sema::TDK_InvalidExplicitArguments:
5817 assert(ParamD && "no parameter found for invalid explicit arguments");
5818 if (ParamD->getDeclName())
5819 S.Diag(Fn->getLocation(),
5820 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5821 << ParamD->getDeclName();
5822 else {
5823 int index = 0;
5824 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5825 index = TTP->getIndex();
5826 else if (NonTypeTemplateParmDecl *NTTP
5827 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5828 index = NTTP->getIndex();
5829 else
5830 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5831 S.Diag(Fn->getLocation(),
5832 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5833 << (index + 1);
5834 }
5835 return;
5836
Douglas Gregora18592e2010-05-08 18:13:28 +00005837 case Sema::TDK_TooManyArguments:
5838 case Sema::TDK_TooFewArguments:
5839 DiagnoseArityMismatch(S, Cand, NumArgs);
5840 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005841
5842 case Sema::TDK_InstantiationDepth:
5843 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5844 return;
5845
5846 case Sema::TDK_SubstitutionFailure: {
5847 std::string ArgString;
5848 if (TemplateArgumentList *Args
5849 = Cand->DeductionFailure.getTemplateArgumentList())
5850 ArgString = S.getTemplateArgumentBindingsText(
5851 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5852 *Args);
5853 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5854 << ArgString;
5855 return;
5856 }
Douglas Gregora9333192010-05-08 17:41:32 +00005857
John McCall342fec42010-02-01 18:53:26 +00005858 // TODO: diagnose these individually, then kill off
5859 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005860 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005861 case Sema::TDK_FailedOverloadResolution:
5862 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5863 return;
5864 }
5865}
5866
5867/// Generates a 'note' diagnostic for an overload candidate. We've
5868/// already generated a primary error at the call site.
5869///
5870/// It really does need to be a single diagnostic with its caret
5871/// pointed at the candidate declaration. Yes, this creates some
5872/// major challenges of technical writing. Yes, this makes pointing
5873/// out problems with specific arguments quite awkward. It's still
5874/// better than generating twenty screens of text for every failed
5875/// overload.
5876///
5877/// It would be great to be able to express per-candidate problems
5878/// more richly for those diagnostic clients that cared, but we'd
5879/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005880void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5881 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005882 FunctionDecl *Fn = Cand->Function;
5883
John McCall81201622010-01-08 04:41:39 +00005884 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005885 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005886 std::string FnDesc;
5887 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005888
5889 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005890 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005891 return;
John McCall81201622010-01-08 04:41:39 +00005892 }
5893
John McCall220ccbf2010-01-13 00:25:19 +00005894 // We don't really have anything else to say about viable candidates.
5895 if (Cand->Viable) {
5896 S.NoteOverloadCandidate(Fn);
5897 return;
5898 }
John McCall1d318332010-01-12 00:44:57 +00005899
John McCalladbb8f82010-01-13 09:16:55 +00005900 switch (Cand->FailureKind) {
5901 case ovl_fail_too_many_arguments:
5902 case ovl_fail_too_few_arguments:
5903 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005904
John McCalladbb8f82010-01-13 09:16:55 +00005905 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005906 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5907
John McCall717e8912010-01-23 05:17:32 +00005908 case ovl_fail_trivial_conversion:
5909 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005910 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005911 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005912
John McCallb1bdc622010-02-25 01:37:24 +00005913 case ovl_fail_bad_conversion: {
5914 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5915 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005916 if (Cand->Conversions[I].isBad())
5917 return DiagnoseBadConversion(S, Cand, I);
5918
5919 // FIXME: this currently happens when we're called from SemaInit
5920 // when user-conversion overload fails. Figure out how to handle
5921 // those conditions and diagnose them well.
5922 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005923 }
John McCallb1bdc622010-02-25 01:37:24 +00005924 }
John McCalla1d7d622010-01-08 00:58:21 +00005925}
5926
5927void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5928 // Desugar the type of the surrogate down to a function type,
5929 // retaining as many typedefs as possible while still showing
5930 // the function type (and, therefore, its parameter types).
5931 QualType FnType = Cand->Surrogate->getConversionType();
5932 bool isLValueReference = false;
5933 bool isRValueReference = false;
5934 bool isPointer = false;
5935 if (const LValueReferenceType *FnTypeRef =
5936 FnType->getAs<LValueReferenceType>()) {
5937 FnType = FnTypeRef->getPointeeType();
5938 isLValueReference = true;
5939 } else if (const RValueReferenceType *FnTypeRef =
5940 FnType->getAs<RValueReferenceType>()) {
5941 FnType = FnTypeRef->getPointeeType();
5942 isRValueReference = true;
5943 }
5944 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5945 FnType = FnTypePtr->getPointeeType();
5946 isPointer = true;
5947 }
5948 // Desugar down to a function type.
5949 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5950 // Reconstruct the pointer/reference as appropriate.
5951 if (isPointer) FnType = S.Context.getPointerType(FnType);
5952 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5953 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5954
5955 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5956 << FnType;
5957}
5958
5959void NoteBuiltinOperatorCandidate(Sema &S,
5960 const char *Opc,
5961 SourceLocation OpLoc,
5962 OverloadCandidate *Cand) {
5963 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5964 std::string TypeStr("operator");
5965 TypeStr += Opc;
5966 TypeStr += "(";
5967 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5968 if (Cand->Conversions.size() == 1) {
5969 TypeStr += ")";
5970 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5971 } else {
5972 TypeStr += ", ";
5973 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5974 TypeStr += ")";
5975 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5976 }
5977}
5978
5979void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5980 OverloadCandidate *Cand) {
5981 unsigned NoOperands = Cand->Conversions.size();
5982 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5983 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005984 if (ICS.isBad()) break; // all meaningless after first invalid
5985 if (!ICS.isAmbiguous()) continue;
5986
John McCall120d63c2010-08-24 20:38:10 +00005987 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005988 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005989 }
5990}
5991
John McCall1b77e732010-01-15 23:32:50 +00005992SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5993 if (Cand->Function)
5994 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005995 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005996 return Cand->Surrogate->getLocation();
5997 return SourceLocation();
5998}
5999
John McCallbf65c0b2010-01-12 00:48:53 +00006000struct CompareOverloadCandidatesForDisplay {
6001 Sema &S;
6002 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006003
6004 bool operator()(const OverloadCandidate *L,
6005 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006006 // Fast-path this check.
6007 if (L == R) return false;
6008
John McCall81201622010-01-08 04:41:39 +00006009 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006010 if (L->Viable) {
6011 if (!R->Viable) return true;
6012
6013 // TODO: introduce a tri-valued comparison for overload
6014 // candidates. Would be more worthwhile if we had a sort
6015 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006016 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6017 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006018 } else if (R->Viable)
6019 return false;
John McCall81201622010-01-08 04:41:39 +00006020
John McCall1b77e732010-01-15 23:32:50 +00006021 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006022
John McCall1b77e732010-01-15 23:32:50 +00006023 // Criteria by which we can sort non-viable candidates:
6024 if (!L->Viable) {
6025 // 1. Arity mismatches come after other candidates.
6026 if (L->FailureKind == ovl_fail_too_many_arguments ||
6027 L->FailureKind == ovl_fail_too_few_arguments)
6028 return false;
6029 if (R->FailureKind == ovl_fail_too_many_arguments ||
6030 R->FailureKind == ovl_fail_too_few_arguments)
6031 return true;
John McCall81201622010-01-08 04:41:39 +00006032
John McCall717e8912010-01-23 05:17:32 +00006033 // 2. Bad conversions come first and are ordered by the number
6034 // of bad conversions and quality of good conversions.
6035 if (L->FailureKind == ovl_fail_bad_conversion) {
6036 if (R->FailureKind != ovl_fail_bad_conversion)
6037 return true;
6038
6039 // If there's any ordering between the defined conversions...
6040 // FIXME: this might not be transitive.
6041 assert(L->Conversions.size() == R->Conversions.size());
6042
6043 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006044 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6045 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006046 switch (CompareImplicitConversionSequences(S,
6047 L->Conversions[I],
6048 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006049 case ImplicitConversionSequence::Better:
6050 leftBetter++;
6051 break;
6052
6053 case ImplicitConversionSequence::Worse:
6054 leftBetter--;
6055 break;
6056
6057 case ImplicitConversionSequence::Indistinguishable:
6058 break;
6059 }
6060 }
6061 if (leftBetter > 0) return true;
6062 if (leftBetter < 0) return false;
6063
6064 } else if (R->FailureKind == ovl_fail_bad_conversion)
6065 return false;
6066
John McCall1b77e732010-01-15 23:32:50 +00006067 // TODO: others?
6068 }
6069
6070 // Sort everything else by location.
6071 SourceLocation LLoc = GetLocationForCandidate(L);
6072 SourceLocation RLoc = GetLocationForCandidate(R);
6073
6074 // Put candidates without locations (e.g. builtins) at the end.
6075 if (LLoc.isInvalid()) return false;
6076 if (RLoc.isInvalid()) return true;
6077
6078 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006079 }
6080};
6081
John McCall717e8912010-01-23 05:17:32 +00006082/// CompleteNonViableCandidate - Normally, overload resolution only
6083/// computes up to the first
6084void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6085 Expr **Args, unsigned NumArgs) {
6086 assert(!Cand->Viable);
6087
6088 // Don't do anything on failures other than bad conversion.
6089 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6090
6091 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006092 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006093 unsigned ConvCount = Cand->Conversions.size();
6094 while (true) {
6095 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6096 ConvIdx++;
6097 if (Cand->Conversions[ConvIdx - 1].isBad())
6098 break;
6099 }
6100
6101 if (ConvIdx == ConvCount)
6102 return;
6103
John McCallb1bdc622010-02-25 01:37:24 +00006104 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6105 "remaining conversion is initialized?");
6106
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006107 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006108 // operation somehow.
6109 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006110
6111 const FunctionProtoType* Proto;
6112 unsigned ArgIdx = ConvIdx;
6113
6114 if (Cand->IsSurrogate) {
6115 QualType ConvType
6116 = Cand->Surrogate->getConversionType().getNonReferenceType();
6117 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6118 ConvType = ConvPtrType->getPointeeType();
6119 Proto = ConvType->getAs<FunctionProtoType>();
6120 ArgIdx--;
6121 } else if (Cand->Function) {
6122 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6123 if (isa<CXXMethodDecl>(Cand->Function) &&
6124 !isa<CXXConstructorDecl>(Cand->Function))
6125 ArgIdx--;
6126 } else {
6127 // Builtin binary operator with a bad first conversion.
6128 assert(ConvCount <= 3);
6129 for (; ConvIdx != ConvCount; ++ConvIdx)
6130 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006131 = TryCopyInitialization(S, Args[ConvIdx],
6132 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6133 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006134 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006135 return;
6136 }
6137
6138 // Fill in the rest of the conversions.
6139 unsigned NumArgsInProto = Proto->getNumArgs();
6140 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6141 if (ArgIdx < NumArgsInProto)
6142 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006143 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6144 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006145 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006146 else
6147 Cand->Conversions[ConvIdx].setEllipsis();
6148 }
6149}
6150
John McCalla1d7d622010-01-08 00:58:21 +00006151} // end anonymous namespace
6152
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006153/// PrintOverloadCandidates - When overload resolution fails, prints
6154/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006155/// set.
John McCall120d63c2010-08-24 20:38:10 +00006156void OverloadCandidateSet::NoteCandidates(Sema &S,
6157 OverloadCandidateDisplayKind OCD,
6158 Expr **Args, unsigned NumArgs,
6159 const char *Opc,
6160 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006161 // Sort the candidates by viability and position. Sorting directly would
6162 // be prohibitive, so we make a set of pointers and sort those.
6163 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006164 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6165 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006166 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006167 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006168 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006169 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006170 if (Cand->Function || Cand->IsSurrogate)
6171 Cands.push_back(Cand);
6172 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6173 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006174 }
6175 }
6176
John McCallbf65c0b2010-01-12 00:48:53 +00006177 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006178 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006179
John McCall1d318332010-01-12 00:44:57 +00006180 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006181
John McCall81201622010-01-08 04:41:39 +00006182 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006183 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006184 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006185 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6186 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006187
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006188 // Set an arbitrary limit on the number of candidate functions we'll spam
6189 // the user with. FIXME: This limit should depend on details of the
6190 // candidate list.
6191 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6192 break;
6193 }
6194 ++CandsShown;
6195
John McCalla1d7d622010-01-08 00:58:21 +00006196 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006197 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006198 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006199 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006200 else {
6201 assert(Cand->Viable &&
6202 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006203 // Generally we only see ambiguities including viable builtin
6204 // operators if overload resolution got screwed up by an
6205 // ambiguous user-defined conversion.
6206 //
6207 // FIXME: It's quite possible for different conversions to see
6208 // different ambiguities, though.
6209 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006210 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006211 ReportedAmbiguousConversions = true;
6212 }
John McCalla1d7d622010-01-08 00:58:21 +00006213
John McCall1d318332010-01-12 00:44:57 +00006214 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006215 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006216 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006217 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006218
6219 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006220 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006221}
6222
John McCall9aa472c2010-03-19 07:35:19 +00006223static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006224 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006225 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006226
John McCall9aa472c2010-03-19 07:35:19 +00006227 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006228}
6229
Douglas Gregor904eed32008-11-10 20:40:00 +00006230/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6231/// an overloaded function (C++ [over.over]), where @p From is an
6232/// expression with overloaded function type and @p ToType is the type
6233/// we're trying to resolve to. For example:
6234///
6235/// @code
6236/// int f(double);
6237/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006238///
Douglas Gregor904eed32008-11-10 20:40:00 +00006239/// int (*pfd)(double) = f; // selects f(double)
6240/// @endcode
6241///
6242/// This routine returns the resulting FunctionDecl if it could be
6243/// resolved, and NULL otherwise. When @p Complain is true, this
6244/// routine will emit diagnostics if there is an error.
6245FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006246Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006247 bool Complain,
6248 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006249 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006250 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006251 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006252 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006253 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006254 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006255 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006256 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006257 FunctionType = MemTypePtr->getPointeeType();
6258 IsMember = true;
6259 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006260
Douglas Gregor904eed32008-11-10 20:40:00 +00006261 // C++ [over.over]p1:
6262 // [...] [Note: any redundant set of parentheses surrounding the
6263 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006264 // C++ [over.over]p1:
6265 // [...] The overloaded function name can be preceded by the &
6266 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006267 // However, remember whether the expression has member-pointer form:
6268 // C++ [expr.unary.op]p4:
6269 // A pointer to member is only formed when an explicit & is used
6270 // and its operand is a qualified-id not enclosed in
6271 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006272 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6273 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006274
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006275 // We expect a pointer or reference to function, or a function pointer.
6276 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6277 if (!FunctionType->isFunctionType()) {
6278 if (Complain)
6279 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6280 << OvlExpr->getName() << ToType;
6281
6282 return 0;
6283 }
6284
John McCallfb97e752010-08-24 22:52:39 +00006285 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006286 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006287 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006288 if (!Complain) return 0;
6289
6290 // TODO: Should we condition this on whether any functions might
6291 // have matched, or is it more appropriate to do that in callers?
6292 // TODO: a fixit wouldn't hurt.
6293 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6294 << ToType << OvlExpr->getSourceRange();
6295 return 0;
6296 }
6297
6298 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6299 if (OvlExpr->hasExplicitTemplateArgs()) {
6300 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6301 ExplicitTemplateArgs = &ETABuffer;
6302 }
6303
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006304 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006305
Douglas Gregor904eed32008-11-10 20:40:00 +00006306 // Look through all of the overloaded functions, searching for one
6307 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006308 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006309 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6310
Douglas Gregor00aeb522009-07-08 23:33:52 +00006311 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006312 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6313 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006314 // Look through any using declarations to find the underlying function.
6315 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6316
Douglas Gregor904eed32008-11-10 20:40:00 +00006317 // C++ [over.over]p3:
6318 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006319 // targets of type "pointer-to-function" or "reference-to-function."
6320 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006321 // type "pointer-to-member-function."
6322 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006323
Mike Stump1eb44332009-09-09 15:08:12 +00006324 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006325 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006326 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006327 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006328 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006329 // static when converting to member pointer.
6330 if (Method->isStatic() == IsMember)
6331 continue;
6332 } else if (IsMember)
6333 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006334
Douglas Gregor00aeb522009-07-08 23:33:52 +00006335 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006336 // If the name is a function template, template argument deduction is
6337 // done (14.8.2.2), and if the argument deduction succeeds, the
6338 // resulting template argument list is used to generate a single
6339 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006340 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006341 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00006342 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006343 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006344 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006345 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006346 FunctionType, Specialization, Info)) {
6347 // FIXME: make a note of the failed deduction for diagnostics.
6348 (void)Result;
6349 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006350 // FIXME: If the match isn't exact, shouldn't we just drop this as
6351 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00006352 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006353 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00006354 Matches.push_back(std::make_pair(I.getPair(),
6355 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006356 }
John McCallba135432009-11-21 08:51:07 +00006357
6358 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006359 }
Mike Stump1eb44332009-09-09 15:08:12 +00006360
Chandler Carruthbd647292009-12-29 06:17:27 +00006361 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006362 // Skip non-static functions when converting to pointer, and static
6363 // when converting to member pointer.
6364 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006365 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006366
6367 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006368 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006369 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006370 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006371 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006372
Chandler Carruthbd647292009-12-29 06:17:27 +00006373 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006374 QualType ResultTy;
6375 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6376 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6377 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006378 Matches.push_back(std::make_pair(I.getPair(),
6379 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006380 FoundNonTemplateFunction = true;
6381 }
Mike Stump1eb44332009-09-09 15:08:12 +00006382 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006383 }
6384
Douglas Gregor00aeb522009-07-08 23:33:52 +00006385 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006386 if (Matches.empty()) {
6387 if (Complain) {
6388 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6389 << OvlExpr->getName() << FunctionType;
6390 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6391 E = OvlExpr->decls_end();
6392 I != E; ++I)
6393 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6394 NoteOverloadCandidate(F);
6395 }
6396
Douglas Gregor00aeb522009-07-08 23:33:52 +00006397 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006398 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006399 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00006400 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006401 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00006402 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006403 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006404 return Result;
6405 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006406
6407 // C++ [over.over]p4:
6408 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006409 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006410 // [...] and any given function template specialization F1 is
6411 // eliminated if the set contains a second function template
6412 // specialization whose function template is more specialized
6413 // than the function template of F1 according to the partial
6414 // ordering rules of 14.5.5.2.
6415
6416 // The algorithm specified above is quadratic. We instead use a
6417 // two-pass algorithm (similar to the one used to identify the
6418 // best viable function in an overload set) that identifies the
6419 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006420
6421 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6422 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6423 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006424
6425 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006426 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006427 TPOC_Other, From->getLocStart(),
6428 PDiag(),
6429 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006430 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006431 PDiag(diag::note_ovl_candidate)
6432 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00006433 if (Result == MatchesCopy.end())
6434 return 0;
6435
John McCallc373d482010-01-27 01:50:18 +00006436 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006437 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00006438 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006439 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00006440 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6441 }
John McCallc373d482010-01-27 01:50:18 +00006442 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006443 }
Mike Stump1eb44332009-09-09 15:08:12 +00006444
Douglas Gregor312a2022009-09-26 03:56:17 +00006445 // [...] any function template specializations in the set are
6446 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006447 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006448 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006449 ++I;
6450 else {
John McCall9aa472c2010-03-19 07:35:19 +00006451 Matches[I] = Matches[--N];
6452 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006453 }
6454 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006455
Mike Stump1eb44332009-09-09 15:08:12 +00006456 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006457 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006458 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006459 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006460 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00006461 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00006462 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00006463 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6464 }
John McCall9aa472c2010-03-19 07:35:19 +00006465 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006466 }
Mike Stump1eb44332009-09-09 15:08:12 +00006467
Douglas Gregor00aeb522009-07-08 23:33:52 +00006468 // FIXME: We should probably return the same thing that BestViableFunction
6469 // returns (even if we issue the diagnostics here).
6470 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006471 << Matches[0].second->getDeclName();
6472 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6473 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00006474 return 0;
6475}
6476
Douglas Gregor4b52e252009-12-21 23:17:24 +00006477/// \brief Given an expression that refers to an overloaded function, try to
6478/// resolve that overloaded function expression down to a single function.
6479///
6480/// This routine can only resolve template-ids that refer to a single function
6481/// template, where that template-id refers to a single template whose template
6482/// arguments are either provided by the template-id or have defaults,
6483/// as described in C++0x [temp.arg.explicit]p3.
6484FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6485 // C++ [over.over]p1:
6486 // [...] [Note: any redundant set of parentheses surrounding the
6487 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006488 // C++ [over.over]p1:
6489 // [...] The overloaded function name can be preceded by the &
6490 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006491
6492 if (From->getType() != Context.OverloadTy)
6493 return 0;
6494
John McCall9c72c602010-08-27 09:08:28 +00006495 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00006496
6497 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006498 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006499 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006500
6501 TemplateArgumentListInfo ExplicitTemplateArgs;
6502 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006503
6504 // Look through all of the overloaded functions, searching for one
6505 // whose type matches exactly.
6506 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006507 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6508 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006509 // C++0x [temp.arg.explicit]p3:
6510 // [...] In contexts where deduction is done and fails, or in contexts
6511 // where deduction is not done, if a template argument list is
6512 // specified and it, along with any default template arguments,
6513 // identifies a single function template specialization, then the
6514 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006515 FunctionTemplateDecl *FunctionTemplate
6516 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006517
6518 // C++ [over.over]p2:
6519 // If the name is a function template, template argument deduction is
6520 // done (14.8.2.2), and if the argument deduction succeeds, the
6521 // resulting template argument list is used to generate a single
6522 // function template specialization, which is added to the set of
6523 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006524 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006525 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006526 if (TemplateDeductionResult Result
6527 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6528 Specialization, Info)) {
6529 // FIXME: make a note of the failed deduction for diagnostics.
6530 (void)Result;
6531 continue;
6532 }
6533
6534 // Multiple matches; we can't resolve to a single declaration.
6535 if (Matched)
6536 return 0;
6537
6538 Matched = Specialization;
6539 }
6540
6541 return Matched;
6542}
6543
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006544/// \brief Add a single candidate to the overload set.
6545static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006546 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006547 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006548 Expr **Args, unsigned NumArgs,
6549 OverloadCandidateSet &CandidateSet,
6550 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006551 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006552 if (isa<UsingShadowDecl>(Callee))
6553 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6554
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006555 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006556 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006557 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006558 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006559 return;
John McCallba135432009-11-21 08:51:07 +00006560 }
6561
6562 if (FunctionTemplateDecl *FuncTemplate
6563 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006564 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6565 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006566 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006567 return;
6568 }
6569
6570 assert(false && "unhandled case in overloaded call candidate");
6571
6572 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006573}
6574
6575/// \brief Add the overload candidates named by callee and/or found by argument
6576/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006577void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006578 Expr **Args, unsigned NumArgs,
6579 OverloadCandidateSet &CandidateSet,
6580 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006581
6582#ifndef NDEBUG
6583 // Verify that ArgumentDependentLookup is consistent with the rules
6584 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006585 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006586 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6587 // and let Y be the lookup set produced by argument dependent
6588 // lookup (defined as follows). If X contains
6589 //
6590 // -- a declaration of a class member, or
6591 //
6592 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006593 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006594 //
6595 // -- a declaration that is neither a function or a function
6596 // template
6597 //
6598 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006599
John McCall3b4294e2009-12-16 12:17:52 +00006600 if (ULE->requiresADL()) {
6601 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6602 E = ULE->decls_end(); I != E; ++I) {
6603 assert(!(*I)->getDeclContext()->isRecord());
6604 assert(isa<UsingShadowDecl>(*I) ||
6605 !(*I)->getDeclContext()->isFunctionOrMethod());
6606 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006607 }
6608 }
6609#endif
6610
John McCall3b4294e2009-12-16 12:17:52 +00006611 // It would be nice to avoid this copy.
6612 TemplateArgumentListInfo TABuffer;
6613 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6614 if (ULE->hasExplicitTemplateArgs()) {
6615 ULE->copyTemplateArgumentsInto(TABuffer);
6616 ExplicitTemplateArgs = &TABuffer;
6617 }
6618
6619 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6620 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006621 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006622 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006623 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006624
John McCall3b4294e2009-12-16 12:17:52 +00006625 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006626 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6627 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006628 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006629 CandidateSet,
6630 PartialOverloading);
6631}
John McCall578b69b2009-12-16 08:11:27 +00006632
6633/// Attempts to recover from a call where no functions were found.
6634///
6635/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00006636static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006637BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006638 UnresolvedLookupExpr *ULE,
6639 SourceLocation LParenLoc,
6640 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006641 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006642
6643 CXXScopeSpec SS;
6644 if (ULE->getQualifier()) {
6645 SS.setScopeRep(ULE->getQualifier());
6646 SS.setRange(ULE->getQualifierRange());
6647 }
6648
John McCall3b4294e2009-12-16 12:17:52 +00006649 TemplateArgumentListInfo TABuffer;
6650 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6651 if (ULE->hasExplicitTemplateArgs()) {
6652 ULE->copyTemplateArgumentsInto(TABuffer);
6653 ExplicitTemplateArgs = &TABuffer;
6654 }
6655
John McCall578b69b2009-12-16 08:11:27 +00006656 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6657 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006658 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00006659 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006660
John McCall3b4294e2009-12-16 12:17:52 +00006661 assert(!R.empty() && "lookup results empty despite recovery");
6662
6663 // Build an implicit member call if appropriate. Just drop the
6664 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00006665 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006666 if ((*R.begin())->isCXXClassMember())
6667 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6668 else if (ExplicitTemplateArgs)
6669 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6670 else
6671 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6672
6673 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006674 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006675
6676 // This shouldn't cause an infinite loop because we're giving it
6677 // an expression with non-empty lookup results, which should never
6678 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00006679 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00006680 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006681}
Douglas Gregord7a95972010-06-08 17:35:15 +00006682
Douglas Gregorf6b89692008-11-26 05:54:23 +00006683/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006684/// (which eventually refers to the declaration Func) and the call
6685/// arguments Args/NumArgs, attempt to resolve the function call down
6686/// to a specific function. If overload resolution succeeds, returns
6687/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006688/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006689/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00006690ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006691Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006692 SourceLocation LParenLoc,
6693 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006694 SourceLocation RParenLoc) {
6695#ifndef NDEBUG
6696 if (ULE->requiresADL()) {
6697 // To do ADL, we must have found an unqualified name.
6698 assert(!ULE->getQualifier() && "qualified name with ADL");
6699
6700 // We don't perform ADL for implicit declarations of builtins.
6701 // Verify that this was correctly set up.
6702 FunctionDecl *F;
6703 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6704 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6705 F->getBuiltinID() && F->isImplicit())
6706 assert(0 && "performing ADL for builtin");
6707
6708 // We don't perform ADL in C.
6709 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6710 }
6711#endif
6712
John McCall5769d612010-02-08 23:07:23 +00006713 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006714
John McCall3b4294e2009-12-16 12:17:52 +00006715 // Add the functions denoted by the callee to the set of candidate
6716 // functions, including those from argument-dependent lookup.
6717 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006718
6719 // If we found nothing, try to recover.
6720 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6721 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006722 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006723 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00006724 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006725
Douglas Gregorf6b89692008-11-26 05:54:23 +00006726 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006727 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006728 case OR_Success: {
6729 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006730 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006731 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006732 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006733 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6734 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006735
6736 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006737 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006738 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006739 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006740 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006741 break;
6742
6743 case OR_Ambiguous:
6744 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006745 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006746 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006747 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006748
6749 case OR_Deleted:
6750 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6751 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006752 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006753 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006754 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006755 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006756 }
6757
Douglas Gregorff331c12010-07-25 18:17:45 +00006758 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00006759 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006760}
6761
John McCall6e266892010-01-26 03:27:55 +00006762static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006763 return Functions.size() > 1 ||
6764 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6765}
6766
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006767/// \brief Create a unary operation that may resolve to an overloaded
6768/// operator.
6769///
6770/// \param OpLoc The location of the operator itself (e.g., '*').
6771///
6772/// \param OpcIn The UnaryOperator::Opcode that describes this
6773/// operator.
6774///
6775/// \param Functions The set of non-member functions that will be
6776/// considered by overload resolution. The caller needs to build this
6777/// set based on the context using, e.g.,
6778/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6779/// set should not contain any member functions; those will be added
6780/// by CreateOverloadedUnaryOp().
6781///
6782/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00006783ExprResult
John McCall6e266892010-01-26 03:27:55 +00006784Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6785 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00006786 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006787 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006788
6789 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6790 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6791 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00006792 // TODO: provide better source location info.
6793 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006794
6795 Expr *Args[2] = { Input, 0 };
6796 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006797
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006798 // For post-increment and post-decrement, add the implicit '0' as
6799 // the second argument, so that we know this is a post-increment or
6800 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00006801 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006802 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006803 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6804 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006805 NumArgs = 2;
6806 }
6807
6808 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006809 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00006810 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006811 Opc,
6812 Context.DependentTy,
6813 OpLoc));
6814
John McCallc373d482010-01-27 01:50:18 +00006815 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006816 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006817 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006818 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006819 /*ADL*/ true, IsOverloaded(Fns),
6820 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006821 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6822 &Args[0], NumArgs,
6823 Context.DependentTy,
6824 OpLoc));
6825 }
6826
6827 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006828 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006829
6830 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006831 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006832
6833 // Add operator candidates that are member functions.
6834 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6835
John McCall6e266892010-01-26 03:27:55 +00006836 // Add candidates from ADL.
6837 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006838 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006839 /*ExplicitTemplateArgs*/ 0,
6840 CandidateSet);
6841
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006842 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006843 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006844
6845 // Perform overload resolution.
6846 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006847 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006848 case OR_Success: {
6849 // We found a built-in operator or an overloaded operator.
6850 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006851
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006852 if (FnDecl) {
6853 // We matched an overloaded operator. Build a call to that
6854 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006855
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006856 // Convert the arguments.
6857 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006858 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006859
John McCall6bb80172010-03-30 21:47:33 +00006860 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6861 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006862 return ExprError();
6863 } else {
6864 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00006865 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00006866 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006867 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006868 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00006869 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00006870 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006871 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00006872 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006873 }
6874
John McCallb697e082010-05-06 18:15:07 +00006875 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6876
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006877 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006878 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006879
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006880 // Build the actual expression node.
6881 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6882 SourceLocation());
6883 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006884
Eli Friedman4c3b8962009-11-18 03:58:17 +00006885 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00006886 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00006887 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall9ae2f072010-08-23 23:25:46 +00006888 Args, NumArgs, ResultTy, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00006889
John McCall9ae2f072010-08-23 23:25:46 +00006890 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00006891 FnDecl))
6892 return ExprError();
6893
John McCall9ae2f072010-08-23 23:25:46 +00006894 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006895 } else {
6896 // We matched a built-in operator. Convert the arguments, then
6897 // break out so that we will build the appropriate built-in
6898 // operator node.
6899 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006900 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006901 return ExprError();
6902
6903 break;
6904 }
6905 }
6906
6907 case OR_No_Viable_Function:
6908 // No viable function; fall through to handling this as a
6909 // built-in operator, which will produce an error message for us.
6910 break;
6911
6912 case OR_Ambiguous:
6913 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6914 << UnaryOperator::getOpcodeStr(Opc)
6915 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006916 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
6917 Args, NumArgs,
6918 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006919 return ExprError();
6920
6921 case OR_Deleted:
6922 Diag(OpLoc, diag::err_ovl_deleted_oper)
6923 << Best->Function->isDeleted()
6924 << UnaryOperator::getOpcodeStr(Opc)
6925 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006926 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006927 return ExprError();
6928 }
6929
6930 // Either we found no viable overloaded operator or we matched a
6931 // built-in operator. In either case, fall through to trying to
6932 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00006933 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006934}
6935
Douglas Gregor063daf62009-03-13 18:40:31 +00006936/// \brief Create a binary operation that may resolve to an overloaded
6937/// operator.
6938///
6939/// \param OpLoc The location of the operator itself (e.g., '+').
6940///
6941/// \param OpcIn The BinaryOperator::Opcode that describes this
6942/// operator.
6943///
6944/// \param Functions The set of non-member functions that will be
6945/// considered by overload resolution. The caller needs to build this
6946/// set based on the context using, e.g.,
6947/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6948/// set should not contain any member functions; those will be added
6949/// by CreateOverloadedBinOp().
6950///
6951/// \param LHS Left-hand argument.
6952/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00006953ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006954Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006955 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006956 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006957 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006958 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006959 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006960
6961 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6962 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6963 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6964
6965 // If either side is type-dependent, create an appropriate dependent
6966 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006967 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006968 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006969 // If there are no functions to store, just build a dependent
6970 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00006971 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006972 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6973 Context.DependentTy, OpLoc));
6974
6975 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6976 Context.DependentTy,
6977 Context.DependentTy,
6978 Context.DependentTy,
6979 OpLoc));
6980 }
John McCall6e266892010-01-26 03:27:55 +00006981
6982 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006983 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00006984 // TODO: provide better source location info in DNLoc component.
6985 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00006986 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006987 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006988 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006989 /*ADL*/ true, IsOverloaded(Fns),
6990 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006991 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006992 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006993 Context.DependentTy,
6994 OpLoc));
6995 }
6996
6997 // If this is the .* operator, which is not overloadable, just
6998 // create a built-in binary operator.
John McCall2de56d12010-08-25 11:45:40 +00006999 if (Opc == BO_PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007000 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007001
Sebastian Redl275c2b42009-11-18 23:10:33 +00007002 // If this is the assignment operator, we only perform overload resolution
7003 // if the left-hand side is a class or enumeration type. This is actually
7004 // a hack. The standard requires that we do overload resolution between the
7005 // various built-in candidates, but as DR507 points out, this can lead to
7006 // problems. So we do it this way, which pretty much follows what GCC does.
7007 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007008 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007009 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007010
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007011 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007012 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007013
7014 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007015 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007016
7017 // Add operator candidates that are member functions.
7018 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7019
John McCall6e266892010-01-26 03:27:55 +00007020 // Add candidates from ADL.
7021 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7022 Args, 2,
7023 /*ExplicitTemplateArgs*/ 0,
7024 CandidateSet);
7025
Douglas Gregor063daf62009-03-13 18:40:31 +00007026 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007027 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007028
7029 // Perform overload resolution.
7030 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007031 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007032 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007033 // We found a built-in operator or an overloaded operator.
7034 FunctionDecl *FnDecl = Best->Function;
7035
7036 if (FnDecl) {
7037 // We matched an overloaded operator. Build a call to that
7038 // operator.
7039
7040 // Convert the arguments.
7041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007042 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007043 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007044
John McCall60d7b3a2010-08-24 06:29:42 +00007045 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007046 = PerformCopyInitialization(
7047 InitializedEntity::InitializeParameter(
7048 FnDecl->getParamDecl(0)),
7049 SourceLocation(),
7050 Owned(Args[1]));
7051 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007052 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007053
Douglas Gregor5fccd362010-03-03 23:55:11 +00007054 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007055 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007056 return ExprError();
7057
7058 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007059 } else {
7060 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007061 ExprResult Arg0
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007062 = PerformCopyInitialization(
7063 InitializedEntity::InitializeParameter(
7064 FnDecl->getParamDecl(0)),
7065 SourceLocation(),
7066 Owned(Args[0]));
7067 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007068 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007069
John McCall60d7b3a2010-08-24 06:29:42 +00007070 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007071 = PerformCopyInitialization(
7072 InitializedEntity::InitializeParameter(
7073 FnDecl->getParamDecl(1)),
7074 SourceLocation(),
7075 Owned(Args[1]));
7076 if (Arg1.isInvalid())
7077 return ExprError();
7078 Args[0] = LHS = Arg0.takeAs<Expr>();
7079 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007080 }
7081
John McCallb697e082010-05-06 18:15:07 +00007082 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7083
Douglas Gregor063daf62009-03-13 18:40:31 +00007084 // Determine the result type
7085 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007086 = FnDecl->getType()->getAs<FunctionType>()
7087 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007088
7089 // Build the actual expression node.
7090 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00007091 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007092 UsualUnaryConversions(FnExpr);
7093
John McCall9ae2f072010-08-23 23:25:46 +00007094 CXXOperatorCallExpr *TheCall =
7095 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7096 Args, 2, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007097
John McCall9ae2f072010-08-23 23:25:46 +00007098 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007099 FnDecl))
7100 return ExprError();
7101
John McCall9ae2f072010-08-23 23:25:46 +00007102 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007103 } else {
7104 // We matched a built-in operator. Convert the arguments, then
7105 // break out so that we will build the appropriate built-in
7106 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007107 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007108 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007109 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007110 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007111 return ExprError();
7112
7113 break;
7114 }
7115 }
7116
Douglas Gregor33074752009-09-30 21:46:01 +00007117 case OR_No_Viable_Function: {
7118 // C++ [over.match.oper]p9:
7119 // If the operator is the operator , [...] and there are no
7120 // viable functions, then the operator is assumed to be the
7121 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007122 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007123 break;
7124
Sebastian Redl8593c782009-05-21 11:50:50 +00007125 // For class as left operand for assignment or compound assigment operator
7126 // do not fall through to handling in built-in, but report that no overloaded
7127 // assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007128 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007129 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007130 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007131 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7132 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007133 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007134 } else {
7135 // No viable function; try to create a built-in operation, which will
7136 // produce an error. Then, show the non-viable candidates.
7137 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007138 }
Douglas Gregor33074752009-09-30 21:46:01 +00007139 assert(Result.isInvalid() &&
7140 "C++ binary operator overloading is missing candidates!");
7141 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007142 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7143 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007144 return move(Result);
7145 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007146
7147 case OR_Ambiguous:
7148 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7149 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007150 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007151 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7152 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007153 return ExprError();
7154
7155 case OR_Deleted:
7156 Diag(OpLoc, diag::err_ovl_deleted_oper)
7157 << Best->Function->isDeleted()
7158 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007159 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007160 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007161 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007162 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007163
Douglas Gregor33074752009-09-30 21:46:01 +00007164 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007165 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007166}
7167
John McCall60d7b3a2010-08-24 06:29:42 +00007168ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007169Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7170 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007171 Expr *Base, Expr *Idx) {
7172 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007173 DeclarationName OpName =
7174 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7175
7176 // If either side is type-dependent, create an appropriate dependent
7177 // expression.
7178 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7179
John McCallc373d482010-01-27 01:50:18 +00007180 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007181 // CHECKME: no 'operator' keyword?
7182 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7183 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007184 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007185 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007186 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007187 /*ADL*/ true, /*Overloaded*/ false,
7188 UnresolvedSetIterator(),
7189 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007190 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007191
Sebastian Redlf322ed62009-10-29 20:17:01 +00007192 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7193 Args, 2,
7194 Context.DependentTy,
7195 RLoc));
7196 }
7197
7198 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007199 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007200
7201 // Subscript can only be overloaded as a member function.
7202
7203 // Add operator candidates that are member functions.
7204 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7205
7206 // Add builtin operator candidates.
7207 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7208
7209 // Perform overload resolution.
7210 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007211 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007212 case OR_Success: {
7213 // We found a built-in operator or an overloaded operator.
7214 FunctionDecl *FnDecl = Best->Function;
7215
7216 if (FnDecl) {
7217 // We matched an overloaded operator. Build a call to that
7218 // operator.
7219
John McCall9aa472c2010-03-19 07:35:19 +00007220 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007221 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007222
Sebastian Redlf322ed62009-10-29 20:17:01 +00007223 // Convert the arguments.
7224 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007225 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007226 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007227 return ExprError();
7228
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007229 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007230 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007231 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7232 FnDecl->getParamDecl(0)),
7233 SourceLocation(),
7234 Owned(Args[1]));
7235 if (InputInit.isInvalid())
7236 return ExprError();
7237
7238 Args[1] = InputInit.takeAs<Expr>();
7239
Sebastian Redlf322ed62009-10-29 20:17:01 +00007240 // Determine the result type
7241 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007242 = FnDecl->getType()->getAs<FunctionType>()
7243 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007244
7245 // Build the actual expression node.
7246 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7247 LLoc);
7248 UsualUnaryConversions(FnExpr);
7249
John McCall9ae2f072010-08-23 23:25:46 +00007250 CXXOperatorCallExpr *TheCall =
7251 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7252 FnExpr, Args, 2,
7253 ResultTy, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007254
John McCall9ae2f072010-08-23 23:25:46 +00007255 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007256 FnDecl))
7257 return ExprError();
7258
John McCall9ae2f072010-08-23 23:25:46 +00007259 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007260 } else {
7261 // We matched a built-in operator. Convert the arguments, then
7262 // break out so that we will build the appropriate built-in
7263 // operator node.
7264 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007265 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007266 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007267 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007268 return ExprError();
7269
7270 break;
7271 }
7272 }
7273
7274 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007275 if (CandidateSet.empty())
7276 Diag(LLoc, diag::err_ovl_no_oper)
7277 << Args[0]->getType() << /*subscript*/ 0
7278 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7279 else
7280 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7281 << Args[0]->getType()
7282 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007283 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7284 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007285 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007286 }
7287
7288 case OR_Ambiguous:
7289 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7290 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007291 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7292 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007293 return ExprError();
7294
7295 case OR_Deleted:
7296 Diag(LLoc, diag::err_ovl_deleted_oper)
7297 << Best->Function->isDeleted() << "[]"
7298 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007299 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7300 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007301 return ExprError();
7302 }
7303
7304 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007305 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007306}
7307
Douglas Gregor88a35142008-12-22 05:46:06 +00007308/// BuildCallToMemberFunction - Build a call to a member
7309/// function. MemExpr is the expression that refers to the member
7310/// function (and includes the object parameter), Args/NumArgs are the
7311/// arguments to the function call (not including the object
7312/// parameter). The caller needs to validate that the member
7313/// expression refers to a member function or an overloaded member
7314/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007315ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007316Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7317 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007318 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007319 // Dig out the member expression. This holds both the object
7320 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007321 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7322
John McCall129e2df2009-11-30 22:42:35 +00007323 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007324 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007325 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007326 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007327 if (isa<MemberExpr>(NakedMemExpr)) {
7328 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007329 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007330 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007331 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007332 } else {
7333 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007334 Qualifier = UnresExpr->getQualifier();
7335
John McCall701c89e2009-12-03 04:06:58 +00007336 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007337
Douglas Gregor88a35142008-12-22 05:46:06 +00007338 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007339 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007340
John McCallaa81e162009-12-01 22:10:20 +00007341 // FIXME: avoid copy.
7342 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7343 if (UnresExpr->hasExplicitTemplateArgs()) {
7344 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7345 TemplateArgs = &TemplateArgsBuffer;
7346 }
7347
John McCall129e2df2009-11-30 22:42:35 +00007348 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7349 E = UnresExpr->decls_end(); I != E; ++I) {
7350
John McCall701c89e2009-12-03 04:06:58 +00007351 NamedDecl *Func = *I;
7352 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7353 if (isa<UsingShadowDecl>(Func))
7354 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7355
John McCall129e2df2009-11-30 22:42:35 +00007356 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007357 // If explicit template arguments were provided, we can't call a
7358 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007359 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007360 continue;
7361
John McCall9aa472c2010-03-19 07:35:19 +00007362 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007363 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007364 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007365 } else {
John McCall129e2df2009-11-30 22:42:35 +00007366 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007367 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007368 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007369 CandidateSet,
7370 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007371 }
Douglas Gregordec06662009-08-21 18:42:58 +00007372 }
Mike Stump1eb44332009-09-09 15:08:12 +00007373
John McCall129e2df2009-11-30 22:42:35 +00007374 DeclarationName DeclName = UnresExpr->getMemberName();
7375
Douglas Gregor88a35142008-12-22 05:46:06 +00007376 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007377 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7378 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007379 case OR_Success:
7380 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007381 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007382 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007383 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007384 break;
7385
7386 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007387 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007388 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007389 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007390 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007391 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007392 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007393
7394 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007395 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007396 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007397 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007398 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007399 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007400
7401 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007402 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007403 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007404 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007405 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007406 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007407 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007408 }
7409
John McCall6bb80172010-03-30 21:47:33 +00007410 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007411
John McCallaa81e162009-12-01 22:10:20 +00007412 // If overload resolution picked a static member, build a
7413 // non-member call based on that function.
7414 if (Method->isStatic()) {
7415 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7416 Args, NumArgs, RParenLoc);
7417 }
7418
John McCall129e2df2009-11-30 22:42:35 +00007419 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007420 }
7421
7422 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007423 CXXMemberCallExpr *TheCall =
7424 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7425 Method->getCallResultType(),
7426 RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007427
Anders Carlssoneed3e692009-10-10 00:06:20 +00007428 // Check for a valid return type.
7429 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007430 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007431 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007432
Douglas Gregor88a35142008-12-22 05:46:06 +00007433 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007434 // We only need to do this if there was actually an overload; otherwise
7435 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007436 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007437 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007438 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7439 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007440 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007441 MemExpr->setBase(ObjectArg);
7442
7443 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007444 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00007445 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007446 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007447 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007448
John McCall9ae2f072010-08-23 23:25:46 +00007449 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00007450 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007451
John McCall9ae2f072010-08-23 23:25:46 +00007452 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00007453}
7454
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007455/// BuildCallToObjectOfClassType - Build a call to an object of class
7456/// type (C++ [over.call.object]), which can end up invoking an
7457/// overloaded function call operator (@c operator()) or performing a
7458/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00007459ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007460Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007461 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007462 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007463 SourceLocation RParenLoc) {
7464 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007465 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007466
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007467 // C++ [over.call.object]p1:
7468 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007469 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007470 // candidate functions includes at least the function call
7471 // operators of T. The function call operators of T are obtained by
7472 // ordinary lookup of the name operator() in the context of
7473 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007474 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007475 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007476
7477 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007478 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007479 << Object->getSourceRange()))
7480 return true;
7481
John McCalla24dc2e2009-11-17 02:14:36 +00007482 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7483 LookupQualifiedName(R, Record->getDecl());
7484 R.suppressDiagnostics();
7485
Douglas Gregor593564b2009-11-15 07:48:03 +00007486 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007487 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007488 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007489 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007490 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007491 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007492
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007493 // C++ [over.call.object]p2:
7494 // In addition, for each conversion function declared in T of the
7495 // form
7496 //
7497 // operator conversion-type-id () cv-qualifier;
7498 //
7499 // where cv-qualifier is the same cv-qualification as, or a
7500 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007501 // denotes the type "pointer to function of (P1,...,Pn) returning
7502 // R", or the type "reference to pointer to function of
7503 // (P1,...,Pn) returning R", or the type "reference to function
7504 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007505 // is also considered as a candidate function. Similarly,
7506 // surrogate call functions are added to the set of candidate
7507 // functions for each conversion function declared in an
7508 // accessible base class provided the function is not hidden
7509 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007510 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007511 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007512 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007513 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007514 NamedDecl *D = *I;
7515 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7516 if (isa<UsingShadowDecl>(D))
7517 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7518
Douglas Gregor4a27d702009-10-21 06:18:39 +00007519 // Skip over templated conversion functions; they aren't
7520 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007521 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007522 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007523
John McCall701c89e2009-12-03 04:06:58 +00007524 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007525
Douglas Gregor4a27d702009-10-21 06:18:39 +00007526 // Strip the reference type (if any) and then the pointer type (if
7527 // any) to get down to what might be a function type.
7528 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7529 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7530 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007531
Douglas Gregor4a27d702009-10-21 06:18:39 +00007532 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007533 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007534 Object->getType(), Args, NumArgs,
7535 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007536 }
Mike Stump1eb44332009-09-09 15:08:12 +00007537
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007538 // Perform overload resolution.
7539 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007540 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7541 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007542 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007543 // Overload resolution succeeded; we'll build the appropriate call
7544 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007545 break;
7546
7547 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007548 if (CandidateSet.empty())
7549 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7550 << Object->getType() << /*call*/ 1
7551 << Object->getSourceRange();
7552 else
7553 Diag(Object->getSourceRange().getBegin(),
7554 diag::err_ovl_no_viable_object_call)
7555 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007556 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007557 break;
7558
7559 case OR_Ambiguous:
7560 Diag(Object->getSourceRange().getBegin(),
7561 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007562 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007563 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007564 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007565
7566 case OR_Deleted:
7567 Diag(Object->getSourceRange().getBegin(),
7568 diag::err_ovl_deleted_object_call)
7569 << Best->Function->isDeleted()
7570 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007572 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007573 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007574
Douglas Gregorff331c12010-07-25 18:17:45 +00007575 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007576 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007577
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007578 if (Best->Function == 0) {
7579 // Since there is no function declaration, this is one of the
7580 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007581 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007582 = cast<CXXConversionDecl>(
7583 Best->Conversions[0].UserDefined.ConversionFunction);
7584
John McCall9aa472c2010-03-19 07:35:19 +00007585 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007586 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007587
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007588 // We selected one of the surrogate functions that converts the
7589 // object parameter to a function pointer. Perform the conversion
7590 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007591
7592 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007593 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007594 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7595 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007596
John McCallf312b1e2010-08-26 23:41:50 +00007597 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007598 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007599 }
7600
John McCall9aa472c2010-03-19 07:35:19 +00007601 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007602 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007603
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007604 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7605 // that calls this method, using Object for the implicit object
7606 // parameter and passing along the remaining arguments.
7607 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007608 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007609
7610 unsigned NumArgsInProto = Proto->getNumArgs();
7611 unsigned NumArgsToCheck = NumArgs;
7612
7613 // Build the full argument list for the method call (the
7614 // implicit object parameter is placed at the beginning of the
7615 // list).
7616 Expr **MethodArgs;
7617 if (NumArgs < NumArgsInProto) {
7618 NumArgsToCheck = NumArgsInProto;
7619 MethodArgs = new Expr*[NumArgsInProto + 1];
7620 } else {
7621 MethodArgs = new Expr*[NumArgs + 1];
7622 }
7623 MethodArgs[0] = Object;
7624 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7625 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007626
7627 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007628 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007629 UsualUnaryConversions(NewFn);
7630
7631 // Once we've built TheCall, all of the expressions are properly
7632 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007633 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007634 CXXOperatorCallExpr *TheCall =
7635 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7636 MethodArgs, NumArgs + 1,
7637 ResultTy, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007638 delete [] MethodArgs;
7639
John McCall9ae2f072010-08-23 23:25:46 +00007640 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00007641 Method))
7642 return true;
7643
Douglas Gregor518fda12009-01-13 05:10:00 +00007644 // We may have default arguments. If so, we need to allocate more
7645 // slots in the call for them.
7646 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007647 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007648 else if (NumArgs > NumArgsInProto)
7649 NumArgsToCheck = NumArgsInProto;
7650
Chris Lattner312531a2009-04-12 08:11:20 +00007651 bool IsError = false;
7652
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007653 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007654 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007655 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007656 TheCall->setArg(0, Object);
7657
Chris Lattner312531a2009-04-12 08:11:20 +00007658
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007659 // Check the argument types.
7660 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007661 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007662 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007663 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007664
Douglas Gregor518fda12009-01-13 05:10:00 +00007665 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007666
John McCall60d7b3a2010-08-24 06:29:42 +00007667 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00007668 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7669 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00007670 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00007671
7672 IsError |= InputInit.isInvalid();
7673 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007674 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00007675 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00007676 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7677 if (DefArg.isInvalid()) {
7678 IsError = true;
7679 break;
7680 }
7681
7682 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007683 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007684
7685 TheCall->setArg(i + 1, Arg);
7686 }
7687
7688 // If this is a variadic call, handle args passed through "...".
7689 if (Proto->isVariadic()) {
7690 // Promote the arguments (C99 6.5.2.2p7).
7691 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7692 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007693 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007694 TheCall->setArg(i + 1, Arg);
7695 }
7696 }
7697
Chris Lattner312531a2009-04-12 08:11:20 +00007698 if (IsError) return true;
7699
John McCall9ae2f072010-08-23 23:25:46 +00007700 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00007701 return true;
7702
John McCall182f7092010-08-24 06:09:16 +00007703 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007704}
7705
Douglas Gregor8ba10742008-11-20 16:27:02 +00007706/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007707/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007708/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00007709ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00007710Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007711 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007712
John McCall5769d612010-02-08 23:07:23 +00007713 SourceLocation Loc = Base->getExprLoc();
7714
Douglas Gregor8ba10742008-11-20 16:27:02 +00007715 // C++ [over.ref]p1:
7716 //
7717 // [...] An expression x->m is interpreted as (x.operator->())->m
7718 // for a class object x of type T if T::operator->() exists and if
7719 // the operator is selected as the best match function by the
7720 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007721 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007722 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007723 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007724
John McCall5769d612010-02-08 23:07:23 +00007725 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007726 PDiag(diag::err_typecheck_incomplete_tag)
7727 << Base->getSourceRange()))
7728 return ExprError();
7729
John McCalla24dc2e2009-11-17 02:14:36 +00007730 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7731 LookupQualifiedName(R, BaseRecord->getDecl());
7732 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007733
7734 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007735 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007736 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007737 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007738 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007739
7740 // Perform overload resolution.
7741 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007742 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007743 case OR_Success:
7744 // Overload resolution succeeded; we'll build the call below.
7745 break;
7746
7747 case OR_No_Viable_Function:
7748 if (CandidateSet.empty())
7749 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007750 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007751 else
7752 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007753 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007754 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007755 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007756
7757 case OR_Ambiguous:
7758 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007759 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007760 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007761 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007762
7763 case OR_Deleted:
7764 Diag(OpLoc, diag::err_ovl_deleted_oper)
7765 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007766 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007767 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007768 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007769 }
7770
John McCall9aa472c2010-03-19 07:35:19 +00007771 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007772 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007773
Douglas Gregor8ba10742008-11-20 16:27:02 +00007774 // Convert the object parameter.
7775 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007776 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7777 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007778 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007779
Douglas Gregor8ba10742008-11-20 16:27:02 +00007780 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007781 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7782 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007783 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007784
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007785 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007786 CXXOperatorCallExpr *TheCall =
7787 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7788 &Base, 1, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007789
John McCall9ae2f072010-08-23 23:25:46 +00007790 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007791 Method))
7792 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007793 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007794}
7795
Douglas Gregor904eed32008-11-10 20:40:00 +00007796/// FixOverloadedFunctionReference - E is an expression that refers to
7797/// a C++ overloaded function (possibly with some parentheses and
7798/// perhaps a '&' around it). We have resolved the overloaded function
7799/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007800/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007801Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007802 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007803 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007804 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7805 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007806 if (SubExpr == PE->getSubExpr())
7807 return PE->Retain();
7808
7809 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7810 }
7811
7812 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007813 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7814 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007815 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007816 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007817 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00007818 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00007819 if (SubExpr == ICE->getSubExpr())
7820 return ICE->Retain();
7821
John McCallf871d0c2010-08-07 06:22:56 +00007822 return ImplicitCastExpr::Create(Context, ICE->getType(),
7823 ICE->getCastKind(),
7824 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00007825 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00007826 }
7827
7828 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00007829 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007830 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007831 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7832 if (Method->isStatic()) {
7833 // Do nothing: static member functions aren't any different
7834 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007835 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007836 // Fix the sub expression, which really has to be an
7837 // UnresolvedLookupExpr holding an overloaded member function
7838 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007839 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7840 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007841 if (SubExpr == UnOp->getSubExpr())
7842 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007843
John McCallba135432009-11-21 08:51:07 +00007844 assert(isa<DeclRefExpr>(SubExpr)
7845 && "fixed to something other than a decl ref");
7846 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7847 && "fixed to a member ref with no nested name qualifier");
7848
7849 // We have taken the address of a pointer to member
7850 // function. Perform the computation here so that we get the
7851 // appropriate pointer to member type.
7852 QualType ClassType
7853 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7854 QualType MemPtrType
7855 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7856
John McCall2de56d12010-08-25 11:45:40 +00007857 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCallba135432009-11-21 08:51:07 +00007858 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007859 }
7860 }
John McCall6bb80172010-03-30 21:47:33 +00007861 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7862 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007863 if (SubExpr == UnOp->getSubExpr())
7864 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007865
John McCall2de56d12010-08-25 11:45:40 +00007866 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00007867 Context.getPointerType(SubExpr->getType()),
7868 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007869 }
John McCallba135432009-11-21 08:51:07 +00007870
7871 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007872 // FIXME: avoid copy.
7873 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007874 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007875 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7876 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007877 }
7878
John McCallba135432009-11-21 08:51:07 +00007879 return DeclRefExpr::Create(Context,
7880 ULE->getQualifier(),
7881 ULE->getQualifierRange(),
7882 Fn,
7883 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007884 Fn->getType(),
7885 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007886 }
7887
John McCall129e2df2009-11-30 22:42:35 +00007888 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007889 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007890 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7891 if (MemExpr->hasExplicitTemplateArgs()) {
7892 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7893 TemplateArgs = &TemplateArgsBuffer;
7894 }
John McCalld5532b62009-11-23 01:53:49 +00007895
John McCallaa81e162009-12-01 22:10:20 +00007896 Expr *Base;
7897
7898 // If we're filling in
7899 if (MemExpr->isImplicitAccess()) {
7900 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7901 return DeclRefExpr::Create(Context,
7902 MemExpr->getQualifier(),
7903 MemExpr->getQualifierRange(),
7904 Fn,
7905 MemExpr->getMemberLoc(),
7906 Fn->getType(),
7907 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007908 } else {
7909 SourceLocation Loc = MemExpr->getMemberLoc();
7910 if (MemExpr->getQualifier())
7911 Loc = MemExpr->getQualifierRange().getBegin();
7912 Base = new (Context) CXXThisExpr(Loc,
7913 MemExpr->getBaseType(),
7914 /*isImplicit=*/true);
7915 }
John McCallaa81e162009-12-01 22:10:20 +00007916 } else
7917 Base = MemExpr->getBase()->Retain();
7918
7919 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007920 MemExpr->isArrow(),
7921 MemExpr->getQualifier(),
7922 MemExpr->getQualifierRange(),
7923 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007924 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00007925 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00007926 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007927 Fn->getType());
7928 }
7929
Douglas Gregor699ee522009-11-20 19:42:02 +00007930 assert(false && "Invalid reference to overloaded function");
7931 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007932}
7933
John McCall60d7b3a2010-08-24 06:29:42 +00007934ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7935 DeclAccessPair Found,
7936 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007937 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007938}
7939
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007940} // end namespace clang